texts: Is it possible to sample sound with arduino?

texts:
I have the arduino duemilanove with atMega328.
The frequency is 16Mhz.

I want to sample and record from the audio jack.
I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.

That means this is unfeasible with my arduino, since my frequency is only 16MHz?


texts: How to fix memory-leak code in ESP8266/NodeMCU caused by string concenation?

texts:
I have following code in loop() in NodeMCU.

This part is before setup():

String serial_data_read = "";   // for incoming serial string data
String serial_data = "";   // for incoming serial string data

This part is in loop():

if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   serial_data_read = "";
   Serial.print("P");
   while(Serial.available()) {
      character = Serial.read();
      serial_data_read.concat(character);
   }
   serial_data = serial_data_read;
}

I don't understand C programming that much, but I think it has something to do with memory leaking and eventually running out of memory. It runs for around 20 minutes and then just stops. When I manually restart NodeMCU it runs again fine.

I would be very grateful for any help, how to rewrite my code so it doesn't leak memory. Thank you very much.


texts: How to connect a digital sensor through SPI

texts:
I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections (user guide):

I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.

Code:

//modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

#include <SPI.h>

const int ID = 0x00;
const int FIFO = 0x11;
const byte READ = 0b11111100;
const byte WRITE = 0b00000010;

const int dataReadyPin = 6;
const int chipSelectPin = 7;

void setup() {
    Serial.begin(9600);

    // put your setup code here, to run once:
    SPI.begin();

    // initalize the  data ready and chip select pins:
    pinMode(dataReadyPin, INPUT);
    pinMode(chipSelectPin, OUTPUT);

    delay(100);
    readRegister(ID);
}

void loop() {
    if (digitalRead(dataReadyPin) == HIGH){
        Serial.println("data ready");
        delay(500);
    }
}
void readRegister (byte thisRegister){
    byte inByte = 0 ;
    Serial.println(thisRegister, BIN);

    thisRegister = thisRegister<< 2;
    byte dataToSend = thisRegister & READ;
    Serial.println(thisRegister, BIN);
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(dataToSend);
    inByte = SPI.transfer(0x00);
    Serial.println("data: ");
    Serial.println(inByte);
}


texts: Prevent 5V output on Arduino Nano 5V pin

texts:
I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.

I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.

Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V

EDIT:
There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?


texts: Arduino Uno powers off when circuit plugged in to +5V and GND pins

texts:
I have a max7219 driving an 8 digit 7 segment LED array with forward current of 20mA and typical forward voltage of 1.85V. I'm trying to power this through my arduino UNO (which itself is drawing power from USB), and have the max7219 chip's +5V and ISet(+resistor) and ground pins connected to the respective pins on the arduino.  When I try to plug this in, the arduino will not power up, but removing the jumpers from +5V and GND allows the arduino to power up.

I have confirmed with my multimeter that there is no short between any of the power cables on my led circuit.

The voltage supplied by the arduino works normally if I connect it up to a simple resistor and led on a breadboard.

The voltage across the +5V & GND pins on the arduino drops from 5V to 0V if the jumpers are inserted whilst the arduino is powered up.

I thought perhaps the circuit was trying to draw too much power from the USB, so tried higher resistor values than my initial resistor (20K), to no effect.

What else could be causing this?


texts: How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed?

texts:
I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors?
I

I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

(a) The serial communication is between two Atmega328P Chips, and using rather long wires
(b) The serial communication is between two Atmega328P Chips, and using rather short wires
(c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted.
Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be more necessary for (b) and almost certainly necessary for (c).

Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?


texts: Arduino micro lost connection after first programming

texts:
I have just programmed a new micro, loaded the basic blink code in it. After that neither my laptop, nor my desktop sees it anyway with the following usb error:

Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: USB disconnect, device number 8
[Fri Apr  1 14:32:03 2016] usb 1-2: new full-speed USB device number 9 using ohci_hcd
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62

If I push the reset button on it it comes back a bit then disappears again:

22620.495256] usb 1-2: New USB device found, idVendor=2341, idProduct=0037
[22620.495263] usb 1-2: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[22620.495268] usb 1-2: Product: Arduino Micro
[22620.495272] usb 1-2: Manufacturer: Arduino LLC
[22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[22627.966141] usb 1-2: USB disconnect, device number 32
[22628.432089] usb 1-2: new full-speed USB device number 33 using ohci_hcd
[22628.572111] usb 1-2: device descriptor read/64, error -62

Anybody experienced this? I have tried to reconnect it multiple times to both computers, even tried a new cable doesn't help.


texts: Do Arduino Nano Atmega328p have the same pins as Arduino/Gizduino Uno Atmega328p?


texts: Cannot find Arduino under /dev Directory

texts:
I have the Arduino board connected to a USB port of my machine. But I cannot find it under /dev/ directory in my Ubuntu. Does anyone know how to deal with this issue? By the way, "lsusb"'s output proves that it has been recognized. Here is the output of this command:

Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 007: ID 413c:2105 Dell Computer Corp. Model L100 Keyboard
Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Here is the output of ls -l /dev/ttyACM*

ls: cannot access /dev/ttyACM*: No such file or directory

and the dmesg output when disconnect and reconnect the device:

[1653809.002715] usb 3-11: USB disconnect, device number 13
[1653832.188835] usb 3-11: new full-speed USB device number 14 using xhci_hcd
[1653832.211392] usb 3-11: New USB device found, idVendor=2341, idProduct=0043
[1653832.218400] usb 3-11: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[1653832.226003] usb 3-11: Manufacturer: Arduino (www.arduino.cc)
[1653832.231859] usb 3-11: SerialNumber: 85235353137351708191
[1653832.237468] usb 3-11: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes


texts: Where is Arduino.h on a Mac? Can I download a copy if missing?

texts:
I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.

If it is built in to the tools can I download a copy of this file(s)?


texts:
I have an Arduino Nano and was adding up some values 2^i from 0..7:

void setup() {
  Serial.begin(9600);
  int i,k;
  k = 0;
  for (i=0;i<8;i++){
     k += pow(2, i);
     Serial.println(k);
  }
}

Those numbers should sum up to 255, but that's the output:

1
3
6
13
28
59
122
249

Is my Arduino not working or what can be the reason for this behaviour?


texts: I'm looking for a 2Mhz 24v 100mA Driver circuit for my Piezo transducer. I am not sure that MOSFET could handle that, if it could there are not much design ideas for the same on internet. And there are high frequency LED driver ICs like LT3598, but I'm not sure about those too. Somebody please help me with this.


texts:
I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below

char incomingchar;
void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
//        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}

void loop() {
    if (Serial.available()) {
            // read the incoming char:
            incomingchar = Serial.read();
               if (incomingchar=="g"){
              Serial.println("hello world!");}
              else{
              Serial.println(incomingchar);
    }
}
}

And here is the Python code:

import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')

When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.

Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.


texts: Detect if a chair is occupied using Arduino with some sensors

texts:
I want to detect if a seat is occupied by a person. This is the answer that I found on Stackoverflow.

However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.


texts: Connecting two arduinos with wifi over the Internet

texts:
I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.

Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.

One board with only send data, and one will only receive.

Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.

thx in advance :)


texts: Encode & decode boolean values into a single integer?

texts:
I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE

Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 + 0 + 0 + 8
Result: 9

This is pretty efficient.
But how do I decode the pin states from this best?
Or do you recommend a better way to do this?


texts: Trying to read from AD5934 using Arduino on I2C

texts:
I'm trying to read a block of bytes from an AD5934 Impedance converter (PDF) using I2C.

This is my code so far

Preamble:

#define AD5934_Address                    0xD
#define AD5934_Start_Frequency            0x82
#define AD5934_Block_Read                 0b10100001
#define AD5934_Address_Pointer            0b10110000

Loop:

void loop() {
  readAD5934(AD5934_Start_Frequency, test, 3);
}

Read Function:

byte readAD5934 (int address, long int  data, int len) {
  byte err = 0, counter;

  if (len > 32)
    return 0xFF;

  else if (len > 1) {
    // Part ONE
    Wire.beginTransmission(AD5934_Address);
    Wire.write((byte) AD5934_Address_Pointer);
    Wire.write((byte) address);

    err = Wire.endTransmission();

    // Part TWO
    Wire.beginTransmission(AD5934_Address);
    Wire.write((byte) AD5934_Block_Read);
    Wire.write(len);

    // Part THREE
    Wire.requestFrom(AD5934_Address, len);
    StartHigh = Wire.read();
    StartMed = Wire.read();
    StartLow = Wire.read();
    err = Wire.endTransmission();
  }
return err;
}

For some reason, the Arduino tries to read the three bytes before Part TWO is executed.

I'm aware that I'm ending the I2C transmission after the requestFrom. The datasheet for AD5934 describes how to read a block of bytes on page 26. It does not show a STOP CONDITION before the end.

The oscilloscope shows

START 0001101 WRITE ACK 10110000 ACK 10000010 ACK STOP START 0001101 READ ACK 00000001 ACK 11000111 ACK 11111111 NACK STOP START 0001101 WRITE ACK 10100001 ACK 00000011 ACK STOP

Short:
S 0x0D W A 0xB0 A 0x82 A P S 0x0D R A 0x01 0xC7 0xFF NA P S 0x0D W A 0xA1 A 0x03 A P

The highlighted part (requestFrom and three Wire.read()) should be at the end.

I've spent a long time trying to figure this out, any help would be very much appreciated.

PS. Working on a Sparkfun Pro Micro 5V


texts:
I'm building a weather station that sends the data to a webserver via GET request.

I was wondering if you guys can look into my code and help me.

I looked all over the internet and can't find what's wrong. I'm using an Arduino mega, an Arduino/Telefonica GSM shield and an EE sim card. Thank you very much!

#include <GSM.h>

GSM gsmAccess;
GPRS gprs;
GSMClient client;

const boolean gprsCheck = true;

char server[] = "";

int value = 112358132134;

void setup(){

  Serial.begin(19200);

  if(gprsCheck) {

    boolean notCon = true;

    Serial.println("Establishing connection...");

    while(notCon) {

      if((gsmAccess.begin("") == GSM_READY) & (gprs.attachGPRS("everywhere","eesecure","secure") == GPRS_READY)) {

        notCon = false;

        Serial.println("GPRS connection successful.");
        Serial.println("");
      }

      else {

        Serial.println("GPRS connection failed. Trying again.");
        Serial.println("");

        delay(1000);
      }
    }
  }

  if(!client.available() && !client.connected()) {

    client.stop();
  }

  if (client.connect(server, 80)) {

    Serial.println("Connection successful.");

    client.print( "GET /add.php?");
    client.print("value=");
    client.print(value);
    client.print(" HTTP/1.1\n");
    client.print("Host: ");
    client.print(server);
    client.print("\nConnection: close\n\n");
    client.stop();
    client.stop();

    Serial.println("Data sent.");
  }

  else {

    Serial.println("Error.");
  }
}

void loop() {
}


texts: From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?


texts: This page says to run a shell command I need a "proxy code" running on my computer (Linux Ubuntu). What do they mean by this, and how should I make one?


texts:
I have made a home automation system consisting of a NodeMCU, 4 channel relay board running on Blynk and IFTTT.

At the moment I'm only controlling a string of fairy lights and two LED strips from it, both connected to the relay of course.

The only code running on the NodeMCU is the Blynk ESP8266 Standalone code. Here it is (with the necessary changes of course) -

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
}

void loop()
{
  Blynk.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}

Now the thing is, the NodeMCU automatically disconnects from the WiFi randomly. Sometimes it reconnects immediately, sometimes it doesn't reconnect at all and I have to keep hitting the reset button to get it working again.

This is really annoying as everything I got connected to the NodeMCU also comes on all of a sudden and scares the hell out of me.

The code is all fine, the power supply is stable (5v 1A), all the cables are in place and the NodeMCU is tucked away in a corner where nobody touches it.
I can't seem to work out why is this happening.

Any fixes for this?


texts: Is it possible to power up Arduino upon serial transmission without dropping data?

texts:
I have radiator valves that send readings about the temperature and valve opening to the serial output: Honeywell HR-25.

I want to collect those readings in a central server at home without flashing the thermostat with a custom firmware.

To do that, I need an Arduino (very bare one) that can receive the serial data, but at the same time I need it to be powered down most of the time, or it would kill the battery life of the thermostat.

Can I wake up an Arduino from power down using the serial transmission, and immediately capture the serial data without dropping bits? how?


texts: Programatic FOTA (Firmware-Over-The-Air) upgrades with Uno R3

texts:
I have been searching for a way to upgrade the sketch on my Arduino Uno wirelessly (preferable WiFi, but not a must). Does the Uno support such function?
If not - are there any other boards that might support it?

Also, to further extend on the problem - I wouldn't want to upload a new sketch through the Arduino IDE but rather do it programmatically (trying to integrate it with a version management system of my own).


texts: Wemos D1 mini freezing after a few minutes

texts:
I´m using a Wemos D1 mini board to control a RGB LED Strip and programmed a simple code with the Arduino IDE. The Wemos conects to my Internet just fine and with the IP adress I can change the RGB values of the Strip. Everything works but after a few minutes the board freezes and nothing works. After a reset it works again.

I also conected a simple circuit to the board just to controle a RGB-LED Strip with a few transistors nothing that should cause an issue and also if i conect nothing to the board the problem occurs.

I also tested a example from the Wemos Library but there is the same problem.
Here is my code I used (And sorry if the code isn´t that well programmed I´m a beginner ;)):

#include <ESP8266WiFi.h>

const char* ssid = "my SSID";
const char* pass = "my password";

void setup() {
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) delay(500);

  Serial.begin(9600);
  //Serial.println(WiFi.localIP());
  server.begin();
}
void setColor(String rgb)
{
  String rgb_val = rgb.substring(4, rgb.lastIndexOf('H'));
  String red_val = rgb_val.substring(1,rgb_val.indexOf(':'));
  String green_val = rgb_val.substring(rgb_val.indexOf(':') + 1,rgb_val.indexOf(':',rgb_val.indexOf(':') + 1));
  String blue_val = rgb_val.substring(rgb_val.lastIndexOf(':') + 1);
  int redval = red_val.toInt();
  int greenval = green_val.toInt();
  int blueval = blue_val.toInt();
  analogWrite(D5, redval);
  analogWrite(D2, greenval);
  analogWrite(D1, blueval);

  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

  greenval = greenval >= 1023 ? 1023 : greenval <= 0 ? 0 : greenval;
  if (greenval == 0)
    analogWrite(D1, 0);

  blueval = blueval >= 1023 ? 1023 : blueval <= 0 ? 0 : blueval;
  if (blueval == 0)
    analogWrite(D2, 0);

  return;
}

void loop() {
  //delay(50) //just a test if there are not so many updates
  WiFiClient client = server.available();
  if (!client) return;

  while (!client.available()) delay(1);

  String request = client.readStringUntil('\r');
  client.flush();

  //Serial.print(request);
  setColor(request);
  client.stop();

  client.print("HTTP/1.1 200 OK\r\n");
  client.flush();
  return;
}

Is there someone who know what I have done wrong?


texts: Arduino mini being programmed with CH340G

texts:
So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.

So, this programmer has pinout of 5V|GND|TX|RX|3V3.

I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).

I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.

There's still no connection between them.

Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?


texts: Receiving serial data in groups instead of individually

texts:
I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.

Here is my Uno code:

String sensor1 ="Conductivity Probe ";
float interceptSensor1 = 0.0;
float slopeSensor1 = 960;
String sensor2 ="pH Probe ";
float interceptSensor2 = 13.720;
float slopeSensor2 = -3.838;
int timeBetweenReadings = 2000; // in ms

void setup() {
  Serial.begin(115200);
}

void loop() {
  float analogSensor1 = analogRead(A0);
  float voltageSensor1 = analogSensor1 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
  //converts voltage to sensor reading
  String sensor1Output = sensor1 + sensor1Reading;
  Serial.println(sensor1Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
  float analogSensor2 = analogRead(A1);
  float voltageSensor2 = analogSensor2 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
  String sensor2Output = sensor2 + sensor2Reading;
  Serial.println(sensor2Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
}

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:

Conductivity Probe 807.04

pH Probe 4.12

Conductivity Probe 802.35

pH Probe 4.13

Conductivity Probe 802.35

pH Probe 4.12

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. Conductivity Probe 807.04) and use logic on the ESP8226 to parse the string, isolate the float number (807.04), and  use Conductivity Probe to determine how that number gets further used (in my case, to publish to an MQTT feed called ElectroConductivity).

The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:

  while (Serial.available() == 0) {
  }
  sensorReading = Serial.readString();
  Serial.println(sensorReading);

The data comes in large groups instead of line by line:

pH Probe 4.12
Conductivity Probe 807.04
pH Probe 4.12
Conductivity Probe 807.04

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.

EDIT

When I use sensorReading = Serial.readStringUntil('\n'); instead my output looks like this:

Conductivity PrpH Probe 4.12

Conductivity Probe 816.42

pH Probe 4.12

Conductivity Probe 825.8Conductivity Probe 821.11

Conductivity Probe 821.11

pH Probe pH Probe 4.12

ConductivitypH Probe 4.12


texts: How to make an SMS notification to my phone with Arduino Uno?

texts:
I am planning to make an SMS notification to my phone with Arduino Uno via a push of a button.

I have an Arduino Uno C520A Embedded System. Is it possible to do so with this model ? If yes, which WIFI module should I get ?

I just want to make an API request to the web through the push of a button.


texts:
I would like to control a relay using Wemos D! R1 via a website from anywhere. I managed to control it using local web server and now would like to step it up further.
I'm using the following code which connects to this website and retrieve data as JSON perfectly.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "SSID";
const char* password = "PASS";

void setup () {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        Serial.println("");
        HTTPClient http;  //Declare an object of class HTTPClient
        http.begin("http://jsonplaceholder.typicode.com/users/1");  //Specify request destination
        int httpCode = http.GET();                                                                  //Send the request

        if (httpCode > 0) { //Check the returning code
            String payload = http.getString();   //Get the request response payload
            Serial.println("");                  // Empty Line
            Serial.println(payload);             //Print the response payload
            //////////////// Json code
              StaticJsonDocument<2000> doc;
              DeserializationError error = deserializeJson(doc, payload);
              if (error) {
                Serial.print(F("deserializeJson() failed: "));
                Serial.println(error.c_str());
                return;
              }
              const char* sensor = doc["name"];
              const char* username = doc["username"];
              const char* email = doc["email"];
              const char* address = doc["address"];
              Serial.println(sensor);
              Serial.println(username);
              Serial.println(email);
              Serial.println(address);
            //////////////// End of Json Code
              http.end();   //Close connection
              while ( 0 < 1 ){ delay(10000); }  // to break the loop
            }
    }
    delay(10);    //Send a request every 30 seconds
}

I made a web page that makes AJAX call to a PHP file to retrieve data from MYSQL DB, but when I run it, the monitor keeps printing empty lines forever although connected successfully to my WIFI.

$(document).ready(function(){
$.ajax({
        url: "test.php",
        type: 'GET',
        dataType: 'json', // added data type
    data: ({mobile: 'hi'}),
        success: function(res) {
            console.log(res);
        }
    });
});

The result I'm getting from AJAX is (which you can check visiting this link:
    {"status":"ON"}

I'm using the following code on php file:

<?php
header('Content-type: application/json');
require 'functions.php';
header("Access-Control-Allow-Origin: *");
    $catrecord = mysqli_query($link,"SELECT * FROM `ard`");
        while($catinfo = mysqli_fetch_array($catrecord, MYSQLI_ASSOC)){ $Cat = $catinfo['status']; }
    $responseArray = array('status' => $Cat );

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    header('Content-Type: application/json');
    echo $encoded;
} else {
    echo $responseArray['status'];
}
?>


texts: The Capacitive Sensor library on a D1 Mini

texts:
I want to set up a hand-made capacitive sensor on a D1 Mini, as in this tutorial, so that I can get specific capacitive readings. But I couldn't get the CapacitiveSensor library to work with the D1 Mini. Just to make sure I wasn't crazy, I fired up an Arduino Nano knockoff, and the library worked just fine.

I found a thread from early 2017 on this topic, which had various suggestions, none of which worked.

Does anyone know either how to make this library work with a D1 Mini, or another efficient way of getting capacitive readings on digital pins on a D1 Mini?


texts: Prevent Arduino IDE from rebuilding the core library after every restart

texts:
I have an Arduino IDE 1.8.5 setup (installed from the ZIP file) which I use to work exclusively with a single board. Every time the IDE is restarted, the first compilation takes much longer than subsequent ones. Apparently, the reason is that Arduino IDE rebuilds the core library:

  Archiving built core (caching) in: C:\Users\User\AppData\Local\Temp\arduino_cache_976772\core\core_arduino_avr_mega_cpu_atmega2560_82177ffe36573ad451e992f583fff1d1.a

Is there a way to prevent that and make the IDE keep the cached core library across restarts? I have the "Aggressively cache compiled core" option checked, but it doesn't seem to help.


texts:
Kunal Gupta:
Guys plss help me .... I am having issues in using stepper motor
I have tried both 28bjy with uln2003 and l293d .. giving it output supply of 5V .
Motor is vibrating but its shaft is not moving.
And even if shaft runs then it is different from what is expected by the logic of code
Similarly tried NEMA 17 stepper motor 4.5 KG using drv8825 driver and L293D driver ... Giving 12 v external supply.
And same results as 28bjy .... motor vibrating but its shaft is mot moving as expected or absolutely not moving
I have read and understood all the concept of driving stepper motor by full step method and hafl step method ....and using at first direct examples from net .. but still not figuring out what is the problem


texts: MAX30102 showing Heart rate: 0.00bpm / SpO2: 0%

texts:
I am using a MAX30102 to monitor SpO2 and heart rate using the https://github.com/oxullo/Arduino-MAX30100 library and the minimal example, but it is not showing any value change.
It only shows zero and in the library tester example it is also showing a timeout error for die temperature.
I removed all 3 pull up registers and given 5 v supply.

Please help to get correct result; I will be thankful.


texts: How to use web data from GSM Sim900 to be used as input for Arduino?

texts:
I have a GSM Sim900 connected to an Arduino Uno. I'm successfully able to use HTTP READ commands to show data from the web on the Arduino's serial monitor. It is showing complete HTML from that URL on the serial monitor.

Now, how should I filter data from the web? I mean I just want to display selected numbers in the serial monitor and not the complete HTML.

And secondly, how should I store these numbers into a variable so I could use them as input data for Arduino?

Thank you.


texts: Wemos D1 mini not being shown when connected to macbook

texts:
I have multiple Wemos d1 mini lying around, but can't seem to get them connected to my macbook, to they do not show up in my /dev/tty?

I tried updating the driver, both using home-brew and installing the driver manually -  as suggested here

https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

but nothing seem to work?
I tried different cables? no way to connect to it?


texts:
I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?

void setup() {
   char* ss1 = "";
   char* ss2 = "";
   String txt = "";

   Serial.begin(115200);

   txt = "1234560001a";
   txt.toCharArray(ss1, txt.length());

   Serial.printf("\n\n");
   Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

   // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
   txt = "abcdef";
   txt.toCharArray(ss2, txt.length());

   Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
   Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
}


texts: Is the Uno Vin pin protected by the voltage regulator?

texts: I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?


texts:
So I bought What I tought was a DOIT Wifi-TTL and after a few bad manipulations I wiped the firmware...
That means the leds are not turning on anymore and I see no activity on it when I connect to it with a USB-TTL...
The FCC ID on it says 2al3b-esp-m that seams to indicate a ESP-8285
(https://fccid.io/2AL3B-ESP-M/User-Manual/User-Manual-3413969)
I tried to flash it with Arduino ESP8285 samples and it flash right but I can't figure how / where I could retrieve the functionality that I had in the pas (login the the web server of it and interact with the TTL...
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8285
Features: WiFi, Embedded Flash
Crystal is 26MHz
MAC: 84:0d:8e:41:22:82
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 1MB
Compressed 280400 bytes to 205882...
Wrote 280400 bytes (205882 compressed) at 0x00000000 in 18.3 seconds (effective 122.7 kbit/s)...
Hash of data verified.

Leaving...


texts: Error Outputting Values Arduino Serial.print

texts:
I am experimenting with the following program I found online (with slight modifications):
int x;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 int y = x + 1;
 Serial.print(y);
}

I am encountering an error in Serial monitor output; if I input 1, I get 21 printed. I think what's happening is that every digit in a number gets incremented by 1, and then 1 is put at the end for some reason. For example, if I input 234, my output is 3451. I think the error lies with the line  x = Serial.readString().toInt();, but am unsure how to fix this. Thank you!


texts:
I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.

The Setup

This is the original shiftout function used in Arduino Programming, except that I replaced 1 with HIGH.

#define F_CPU 1000000UL
#define BAUD 9600UL
#define LSBFIRST 0
#define MSBFIRST 1
#define HIGH 0x1
#define LOW  0x0
#define INPUT 0x0
#define OUTPUT 0x1

#include <avr/io.h>
#include <util/delay.h>
#include <USART.h>
#include <pinDefines.h>

#define DATA PD7
#define LATCH PB2
#define CLOCK PB0

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;
    for (i = 0; i < 8; ++i) {
        if (bitOrder == LSBFIRST) {
            PORTD |= (!!(val & (HIGH << i)) << DATA);
            } else {
            PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
        }
        PORTB |= (HIGH << clockPin);
        PORTB &= ~(HIGH << clockPin);
        }
}

Main

int main(void)
{
    initUSART();
    DDRD |= (HIGH << DATA);
    DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

    PORTB |= (HIGH << LATCH);
    shiftOut(DATA, CLOCK, LSBFIRST, 1);
    printBinaryByte(PIND);
    PORTB ^= (HIGH << LATCH);

    /* Replace with your application code */
    while (1)
    {

    }

    return (0);
}

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.

Szenario

PORTD |= (!!(val & (HIGH << 0)) << DATA);

This is what I expect for val = 1

(HIGH << 0) = 00000001
val & (HIGH << 0) = 00000001 & 00000001
!!(val & (HIGH << 0)) = 1
PORTD |= (1 << DATA)

As PORTD is the data pin on the shift register, it should get 00000001.
When I print the binary number within PORTD I get: 10000111 and my LED Array connected to the 74HC595 displays: 10101111

I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?


texts: Run different code on different type of reset in arduino nano

texts:
I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this.
I have 2 leds and my nano... Along with the laptop and any other necessary components.


texts:
Why does this print output -3? xpos can be any value.

void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);

}


texts: What good designs are available for Geiger counters using an Arduino?

texts:
Are there any good circuit designs for Geiger-counter projects using an Arduino?

If so, what Geiger-Muller tubes should I choose to detect different types of radiation?


texts:
I have 5 LDR and Arduino Mega. I connect them and get light level.

void loop() {
// print the analog output in milli volts
int w=analogRead(west);
Serial.print("west = ");

Serial.print(w);
Serial.println(" mv");

int e=analogRead(east);
Serial.print("east = ");

Serial.print(e);
Serial.println(" mv");

int n=analogRead(north);
Serial.print("north = ");

Serial.print(n);
Serial.println(" mv");

int s=analogRead(south);
Serial.print("south = ");

Serial.print(s);
Serial.println(" mv");

int c=analogRead(control);
Serial.print("control = ");

Serial.print(c);
Serial.println(" mv");

delay(1000);

if(e > w)
Serial.println("west");

else if(e < w)
Serial.println("east");

else if(s > n)
Serial.println("south");

else(s < n);
Serial.println("north");

Serial.println("\n");
}

This is my loop and I always see east-north. When west is bigger than east I also see east. What


texts:
my Error is : "exit Status 1 expected ')' before ';' token
This is my Code :
void setup () {

 for (int pin=2; pin <14; pin++) {
pinMode (pin ; OUTPUT)} ;
 }
}

void loop () {
  for (int i=2; i<14; i++) {
    digitalWrite (i, HIGH) ;
    delay(20);
    digitalWrite(i+1,HIGH) ;
    delay(20) ;
    digitalWrite(i+2, HIGH) ;
    delay(20) ;
    digitalWrite(i, LOW) ;
    delay(20) ;
    digitalWrite(i+1, LOW) ;
  }
}

//
for (int i=13; i>1; i--) {
    digitalWrite (i, HIGH) ;
    delay(20);
    digitalWrite(i-1,HIGH) ;
    delay(20) ;
    digitalWrite(i-2, HIGH) ;
    delay(20) ;
    digitalWrite(i, LOW) ;
    delay(20) ;
    digitalWrite(i-1, LOW) ;
}


texts: Arduino Uno pin dead for no reason. Why?

texts:
After struggling with an LCD showing rubbish characters on my previous post, I found that my pin 5 was dead, for no reason. I never connected it to anything except the LCD - I bought it two days ago.

I'm glad that I bought two extra ATmega328P-PU along with it, burned bootloader into it, and it worked, but what causes my pin 5 to be dead?

I did use A5 as an input before, but I don't get how it affected PWM pin 5.

FYI, this is my first time playing with Arduino.


texts:
I'm trying to use the TTS library for Arduino on an Arduino Micro board, which is based on the Leonardo. When I try to compile my sketch I get some errors;

/libraries/TTS/TTS.cpp: In function 'void soundOff()':
/libraries/TTS/TTS.cpp:355: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:355: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void soundOn()':
/libraries/TTS/TTS.cpp:382: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'WGM20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'TCCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'CS20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'WGM22' was not declared in this scope
/libraries/TTS/TTS.cpp:384: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:385: error: 'TCNT2' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void sound(byte)':
/libraries/TTS/TTS.cpp:424: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:425: error: 'TCNT2' was not declared in this scope

Googling revealed that the Leonardo uses different timers. And other things I don't understand! But I couldn't piece together an answer beyond that.

What are the correct constants to use for Leonardo boards, and is there a way I can update the library to work across both?


texts: NRF24 CE and CSN connections without I/O pins easily accessible

texts:
I want 2 Arduinos communicating to each other, but only in one direction.  Arduino A = tx  and Arduino B = rx.

I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library.  No problem.

Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:

Arduino A --- put CSN to GND  and put CE to 3.3V
Arduino B --- put CSN to 3.3V and put CE to 3.3V

As to why?  This would simply help me interface the NFR24 to existing custom PCB's I've made which have no easy access to I/O pins.  My PCB's do have easy access to MISO, MOSI, and SCK.


texts:
EDIT: Changed the title to better express what I'm after.

I've been dabbling in connecting two Arduino Nano 3's with the RFM69HCW breakout for the past 5 days.. but got nowhere.

I've followed the official hookup guide at first, after that didn't work, I've tried the code samples from a Adafruit post, and still nothing.

By 'nothing', I mean that I compiled and uploaded the code to two separate Arduinos that are literally 5cm apart, tried sending messages, broadcasting messages.. etc. but without any success.

Here they are - on two breadboards, but the layout and connections are symmetrical:

Yeah, the bottom one is quite confusing to look at because of the wires, but I lent most of them to friends - so I had to improvise.

To clarify the picture, I connected the Arduino as follows:

D2 -> INT(Interrupt)
D10 -> SS
D11 -> MISO
D12 -> MOSI
D13 -> C(Clock)

One of the codes that I tried: (This is from the official guide, but modified slightly)

#include <RFM69.h>
#include <SPI.h>

#define NETWORKID     0
#define MYNODEID      1 //2 For the other Arduino
#define TONODEID      255

#define FREQUENCY     RF69_915MHZ

#define ENCRYPT       false // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes

#define USEACK        true // Request ACKs or not

RFM69 radio;

void setup()
{
  Serial.begin(9600);
  Serial.print("Node ");
  Serial.print(MYNODEID,DEC);
  Serial.println(" ready");

  radio.initialize(FREQUENCY, MYNODEID, NETWORKID);
  radio.setHighPower();
}

void loop()
{
  static char sendbuffer[62];
  static int sendlength = 0;

  if (Serial.available() > 0)
  {
    char input = Serial.read();

    if (input != '\r')
    {
      sendbuffer[sendlength] = input;
      sendlength++;
    }

    if ((input == '\r') || (sendlength == 61))
    {
      Serial.print("sending to node ");
      Serial.print(TONODEID, DEC);
      Serial.print(", message [");
      for (byte i = 0; i < sendlength; i++)
        Serial.print(sendbuffer[i]);
      Serial.println("]");

      if (radio.sendWithRetry(TONODEID, sendbuffer, sendlength))
        Serial.println("ACK received!");
      else
        Serial.println("no ACK received");

      sendlength = 0;
    }
  }

  if (radio.receiveDone())
  {
    Serial.print("received from node ");
    Serial.print(radio.SENDERID, DEC);
    Serial.print(", message [");

    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);

    Serial.print("], RSSI ");
    Serial.println(radio.RSSI);

    if (radio.ACKRequested())
    {
      radio.sendACK();
      Serial.println("ACK sent");
    }
  }
}

Notes:
Everything is powered by a 5V 2A brick - the RFM69 modules are receiving a stepped down 3.3V from those small thingies connecting two separate breadboard power rails.

Also... I don't have any 915MHz antennas, so I used some 433MHz ones that I had laying around - I'm going to get correct ones later, but right now, for testing them 5cm apart it should be good enough..?

P.S.: I HATE when stuff doesn't have status LEDs, I could really use some on the radio modules.


texts: Making Laser Tripwire with Phone Messaging

texts: I am looking at Arduino and Raspberry Pi and I want to do a pretty advanced project.  I want to make a laser triggered security project that sends a message to either a android or iPhone. First I don't know what exact hardware I need. I have a photo-resister and a laser.  However, I don't know what hardware to buy and how to connect to my phone. I've looked at http://www.smartliving.io/kits.  I also don't know how the messaging would work. Is there already a Arduino and or Raspberry Pi library/hardware for this or would I have to get the data on the Internet and using something like the Twilio API? would Arduino or Raspberry Pi be easier?


texts: Same code in setup() and loop() give different results

texts:
As the answers to this question and this one state, setup() and loop() are identical in the way they execute code (apart from the obvious looping function of loop()).

However.

I get different results with following two pieces of code:

Code run once, in setup()

/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

void setup() {
    LED.setOutput(13); // Digital Pin 13

    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
}

void loop() {
}

Code run once, in loop()

/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

bool hasBeenSet = false;

void setup() {
    LED.setOutput(13); // Digital Pin 13
}

void loop() {
  if (hasBeenSet == false){
    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
    hasBeenSet = true;
  }
}

The difference:

The code run in setup() makes the LED flash once with the desired color.
The code run in loop() makes the LED stay lit with the desired color.

With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the loop() version I can even disconnect the data line after the color has been set, and it will stay lit.

I can only conclude the same code is executed differently in both cases.

Is there some sort of (soft) power reset after setup()? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: http://github.com/cpldcpu/light_ws2812


texts: How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press?

texts:
Question (TL;DR): what is the optimal method to deep sleep (to run an ATtiny45 or ATmega on batteries for 1+ year) but still be able to detect a button press? Is it possible to deep sleep until a button is pressed?

I'm using a classic "debounce" method to detect a button press:

int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

void setup() {
  pinMode(2, INPUT);
}

void loop() {
  int reading = digitalRead(2);
  if (reading != lastButtonState) { lastDebounceTime = millis(); }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == HIGH) {
         // Button pressed, do something here!
         // In my actual code, it sends a packet via RF 433 Mhz
      }
    }
  }
  lastButtonState = reading;
  // snore(20);          // TinySnore here
}

My ATtiny45 should run during 1 year on 3 AA batteries, so I added a deep sleep using TinySnore. It works, and made the consumption go from more than 1mA to 0.2mA (@1 Mhz).

I know it's possible to go down to 5 µA if I snore(1000); but then obviously it won't be able to detect a button press.

I tried various sleep values: snore(10);, snore(20);, snore(50);, etc. but I didn't get consistent results.

Thus the question: how to deep sleep until a button is pressed?

I was thinking about using attachInterrupt() but then what kind of sleep should we use? snore()? delay()?


texts: HC-05 can not use lower pins only 8 and higher

texts:
#include <Arduino.h>
#include <SoftwareSerial.h>

char Incoming_value = 0;

// SoftwareSerial BTSerial( 10, 11 ); // RX | TX +
// SoftwareSerial BTSerial( 9, 10 ); // RX | TX +
// SoftwareSerial BTSerial( 8, 9 ); // RX | TX +
// SoftwareSerial BTSerial( 7, 8 ); // RX | TX - ???
// SoftwareSerial BTSerial( 6, 7 ); // RX | TX - ???
// SoftwareSerial BTSerial( 5, 6 ); // RX | TX - ???
// SoftwareSerial BTSerial( 4, 5 ); // RX | TX - ???
// SoftwareSerial BTSerial( 3, 4 ); // RX | TX - ???

SoftwareSerial BTSerial( 8, 9 ); // RX | TX +

void setup() {
        BTSerial.begin( 9600 );
        pinMode( 13, OUTPUT);
}

void loop() {
        delay( 1000 );
        BTSerial.println( "hello" );
        if( BTSerial.available() > 0 ) {
                BTSerial.println( "BINGO!" );
                Incoming_value = BTSerial.read();
                BTSerial.println( Incoming_value );
                if ( Incoming_value == '1' ) digitalWrite( 13, HIGH );
                else if ( Incoming_value == '0' ) digitalWrite( 13, LOW );
        }
}

My HC-05 Bluetooth module wont't work on lowers digital pins.

  BOARD_TAG = leonardo

It works fine on highers digital pins: 8-9, 9-10 or 10-11 - everything fine.
but 2-3, 3-4, 4-5, 5-6, 6-7 or 7-8 - no....

Why? Should I inject jumper somewhere or what?

And yes: @Majenko, "0,1 - is required to debug from host". I want to have Serial from PC and BTSerial from bluetooth - to have both accesses to device simultaneously.

@Peter_Paul_Kiefer, so, you think, this is impossible with lowest pins, lower than 8?


texts: I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.


texts: Read Voltage at PWM off time, and Current at PWM on time

texts:
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read_ADC_Voltage() during the LOW time, and read_ADC_Current() during the HIGH time.

Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.


texts: Arduino Mini Pro not working with my Neopixel project

texts:
my project involves 9 Neopixel LEDs. I have tested my code with my Arduino Uno board successfully. I'm using a mix of breadboard, jumper wires, and solder to connect everything. Powering the strip of 9 LEDs with 4 AA NiMh rechargable batteries, showing 5.2v on the meter. I've put a capacitor (1000mF 25v) in the circuit, right at the power source.

But when I upload the same code to my Mini (5v/16MHz) and swap it in in place of the Uno, I get nothing. No matter how much I jiggle wires or provide a good ground (which helped me get good results from my Uno). Every now and then by messing with wires, or as a few minutes go by, the first few lights might light up, but not in the right colors and no animation.

Just to test the Mini board I uploaded the sample program "blink" and the mini runs that one properly. So I'm certain my code is getting on there. My program is definitely bigger and involves some quick changes (I'm making an "ebbing" glow of supernatural eyes). Connecting the Mini to the Neopixel strip I soldered a wire with a female jumper onto the board, and my strip of lights has a wire soldered on with a male jumper. As a side note, it takes a little physical handling to get the project to work with the Uno (like pressing a little bit on the data wire in it's plug on the Uno or using a jumper wire in the breadboard clamped in a metal measuring tool and my hand to ground out the circuit). So maybe I'm just experiencing some of the shortcomings of the Mini, but I was under the impression that it would do just about anything the Uno could do. Especially in terms of just providing a data line for the LEDs.

I'm new to Neopixel. This is my first project in fact. So it is entirely possible I'm doing something wrong or there's something I just missed completely, or maybe my luck just sucks and I have some piece of faulty hardware... No idea.

Any suggestions would be most appreciated!


texts: Using MOSI and MISO pins for multiple devices

texts: For the device I am creating, I am hooking up an apa102 led strip to pins 11 and 13 to control each LED. But I would also like to hookup my NRF receiver to the arduino, but I also use pins 11 and 13. My question is can i hookup both to the same pins and control the inputs and outputs through the MOSI amd MISO pins separately!


texts: UART communication, is it possible to use only the TX line?

texts:
I am trying to connect an ESP-01 with an ArduinoMega through the serial port of both, as they use different voltage levels I would need a voltage divider between the TX pin of the Mega (pin 1) and the pin RX of the ESP-01 (pin 4) , it is not difficult to do, but I just need to "send data" from ESP-01 to Mega, then I have a question and it is as follows:

If I just need to send data from one device to the other, could I just connect the TX pin of the ESP-01 to the RX of the Mega? If I do so, will I receive data in the Mega?

Greetings


texts: When is it necessary to use "float" instead of "int"?

texts:
I'm very new to Arduino and I am making a code for a pedometer.  I have a lot of variables and I have used "int" multiple times, but I just came across a code with "float".
Now because my coding background is next to none, I don't really understand the concept of a float and when it's appropriate to use one.
Could someone please give me an explanation.
Thanks!


texts: Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?

texts: The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?


texts: ir sender detecting receiver and display

texts:
I am in a pickle and want to know if you can help me. I have an IR sensor and receiver and want a program that makes a light bulb flash or detect whenever the IR receiver is in range.
So whenever the IR sender detects the receiver, it should print "detect". This will be done using the Arduino program. And it is an Arduino Nano I am using.

These are the things I use:

http://www.dx.com/p/keyestudio-digital-ir-receiver-module-for-arduino-black-429206#.V5gcpzYko-U

http://www.dx.com/p/38khz-ir-infrared-transmitter-module-for-arduino-135040#.V5gcpjYko-U

How should this program look like? Anyone have the code for this?

Never mind the LED blinking, I just want the program to know whenever the receiver is detected and probably display it somehow. My plan is to send the number of times the transmitter detects the receiver to an Android app in the end.


texts: Why do i get additional characters when reading a file through a buffer if buffer size > 15?

texts:
This is a follow up question to How to speed up writing a file to a WifiClient?

I modified the old code to read from one Stream and write to another which looked like this and worked fine albite being a bit slow

while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

to use a buffer, like so

char buffer[300];
size_t bufferSize = sizeof(buffer);

// ...

while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize);

    client.print(buffer);
}
client.flush();

Now, if the buffer size is > 15 (in the above case, it's 300), two additional characters Øb are introduced after the buffer size amount of characters. If the buffer size is <= 15, this does not happen.

If the file to be read contains abcdefg repeated several times, I get the following result for a buffer size of 32:

|-------- 32 characters -------|Øb|-------- 32 characters -------|Øb|-----
abcdefgabcdefgabcdefgabcdefgabcdØbefgabcdefgabcdefgabcdefgabcdefgaØbbcdefg

What's causing those additional characters to appear?

The above output is produced in the browser If I do not specify a charset. if I do, I get � instead of Øb.


texts:
I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.

This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.


texts:
I have written this little snippet of code to interface with EM408 GPS.

#include <SoftwareSerial.h>
SoftwareSerial GPS = SoftwareSerial(2,3);  //rx,tx
void setup()
{
  GPS.begin(4800);
  Serial.begin(9600);
}

void loop()
{
  //Serial.print(GPS.read(), BYTE);
  Serial.write(byte(GPS.read()));  //as of Arduino 1.0
}

Hardware side i have these connections:
ENABLE: 3.3V
Vcc   : 3.3V
Ground: Ground
Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial

However, the values i get are just junk data

ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

I get these without ending...
I experimenting with changing the baud rate, still the same thing goes on.
Any ideas?

EDIT:
I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...


texts: I connected a bipolar stepper motor with an HC-SRO4 distance sensor but the motor doesn't work

texts:
I connected a bipolar stepper motor with an L293D motor driver and a HC-SR04 distance sensor.

Here's the code:

#include<AFMotor.h>
int stepsperrevolution=200;
AF_Stepper motor(stepsperrevolution,1);
int echopin=11;
int trigpin=9;
int dt=2000;
int sensorval;
void setup() {
  Serial.begin(9600);
  motor.setSpeed(10);
  pinMode(echopin,INPUT);
  pinMode(trigpin,OUTPUT);

}

void loop() {

 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 digitalWrite(trigpin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 sensorval=pulseIn(echopin,HIGH);
 Serial.println(sensorval);

if(sensorval<500){
 motor.step(stepsperrevolution,FORWARD,SINGLE);
  delay(dt);
   }

}

The code works.Although, every time the sersorval prints in the serial monitor, it stops when the value is less than 500, and the stepper doesn't move.


texts:
Trying to do serial communication between 2 Arduino Unos.

Code:

#include <SoftwareSerial.h>

int ledPin = 13;
int board;   // 1 = Uno. 2 = Mega.
int on_off;  // 1 = On. 0 = Off.
int buzzerPin = 9;
int Ack_tx = 2; //Acknowledgement tx.
int rec;

void setup()
{
  Serial.begin(9600);      // start serial communication at 9600bps
  Serial1.begin(9600);     // start serial1 communication at 9600bps

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  Serial.flush();
  Serial1.flush();

} // End Setup

void loop()
{

  Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
  //  if(!Serial){ board = Serial.read();}
  while(Serial.available()==0) { // Wait for User to Input Data
  }
  board = Serial.parseInt();  //Read the data the user has input

  Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
  while (Serial.available()==0) { // Wait for User to Input Data
  }
  on_off = Serial.parseInt();

  Serial.println();

  switch (board) {

  case 0:  //Mega board
    if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
    else digitalWrite(ledPin, LOW);              //Select Uno LED Off
    break;  //End Case

  case 1:  //Uno board
    //Serial.println("Off to Uno...");
    //Send on_off info to Uno
    Serial1.write(on_off/256); //Send the Quotient or "how many times" value
    Serial1.write(on_off%256); //Send the Modulo or Remainder.
    delay(50); //Wait for the serial port.

    while(Serial1.available()<2) //Wait for 2 bytes to arrive
     {
      //do nothing
     } //End While

  byte b1=Serial1.read();  //Read Upper byte
  byte b2=Serial1.read();  //Read Lower byte
  rec=(b1*256)+b2;

    if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
    break;
  } //End Switch Case

}

Error:

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

sketch_mar06a:13: error: 'Serial1' was not declared in this scope

   Serial1.begin(9600);     // start serial1 communication at 9600bps

   ^

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

sketch_mar06a:51: error: 'Serial1' was not declared in this scope

     Serial1.write(on_off/256); //Send the Quotient or "how many times" value

     ^

Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
 Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
exit status 1
'Serial1' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This is a very basic problem I know, but nothing on the internet is helping.


texts: Esp8266 server unreachable. Port doesn't open

texts:
I have followed all the instructions provided on  http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...


texts:
Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.


texts: Can I have backup power for an Arduino device?

texts:
I have an arduino project that will work while plugged into a generic outlet. But I want to connect a battery in case the power goes out. I know there are various power sources (coin cell, polymer lithium, 9V, etc.). But if I code my project to use the backup power if the main power goes down, would that mean the backup always has to be running? How would I go about this?

Thanks for the help! Every time you help me you save a kitten!!


texts: how do i get data from the website? using arduino uno and esp8266

texts:
i have hosted a website on the 000webhost. And i have simply written a line in paragraph tags in html file( means i have created a html file..)
so i want to know to know how i get data that data in html file on the serial moniter through esp8266.
i have written a code in the arduino ide which is....
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /index.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

and the response on the serial moniter is
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AT+CIPSEND=4,28

OK
>
Recv 28 bytes

SEND OK

+IPD,4,412:HTTP/1.1 400 Bad Request
Date: Thu, 27 May 2021 18:07:45 GMT
Content-Type: text/html
Content-Length: 154
Connection: close
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 2eaf3c737a5348270ebe7873cab10088

<title>400 Bad Request</title>

400 Bad Request

openresty

4,CLOSED

what does it mean?
thanks in advance.......


texts: Arduino IDE Based Data Logger - Stops Running

texts:
I have created a data logger that writes to a MicroSD on a user defined interval.  The data logger also has the ability to use an xBee unit to transmit the data received to a base station.

This is a link to the code and pictures of the data logger.

I use Arduino IDE for prototyping and coding.  After compiling the code, I use the temp HEX file and upload it to the boards using AVR Studio 4.

The problem I am experiencing is the data loggers will stop running after a random number of recordings.  This can be days or weeks of running before the problem is experienced. This issue rarely occurs when the logger is running in local mode, but occurs often when running with an XBee unit.

A temporary fix I have found for the problem is to add delay(10); before and after the SD card writes.  I do not know why this fixes the problem and would like to find a more appropriate solution.


texts: Problems with detecting button digital state

texts:
I am trying to start an event after pressing and holding the FLASH built-in Nodemcu button for a specific time, I wrote two functions, one for debouncing and detecting the state, the other is to detect the pressing time, I'm not getting any result unless I decrease the input pressing time to less than 1s, which makes the button works as a single-push button, I think i have a problem with debouncing the button, I can't figure out where it is?
/**
* @brief debounces the button and returns the current level high or low
*
* @return int the button state 0: low, 1: high, -1 indetermined
*/
int button_state(int btn)
{
    int const DEBOUNCE = 200;
    static int hi = DEBOUNCE;
    static int lo = 0;
    if (digitalRead(buttonPin[btn]))
    {
        if (hi < DEBOUNCE)
        {
            hi++;
        }
        if (lo > 0)
        {
            lo--;
        }
    }
    else
    {
        if (lo < DEBOUNCE)
        {
            lo++;
        }
        if (hi > 0)
        {
            hi--;
        }
    }

    if (hi == DEBOUNCE)
    {
        return 1;
    }
    else if (lo == DEBOUNCE)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
/**
 * @brief Detects the button state and starts a time to calculate pressing duration
 *
 * @param btn input button pin
 * @param PressTime Desired pressing duration to compare to
 * @return int returns 1 when PressTime is reached
 */
int PressNHold(int btn, int PressTime)
{
    int lastButtonState = 0, Startpressed = 0, endPressed = 0, holdTime = 0,
    buttonState = button_state(btn);
    if(buttonState != -1)
    {
        if (buttonState != lastButtonState)
        {
            if (buttonState == 1)
            {
                Startpressed = millis();
            }
            else
            {
                endPressed = millis();
                holdTime = endPressed - Startpressed;
                if (holdTime >= PressTime)
                {
                    Serial.printf("Button %d pressed for %ds or more\n", btn, holdTime);
                    holdTime = 0;
                    return 1;
                }
            }
        }
    }
    lastButtonState = buttonState;
}
.....

void loop {

if (PressNHold(buttonPin[1], 5 * 1000) == 1)
  {
   //launch your event
  }


texts: I get the following error while using esp32

texts:
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0,
  SPIWP:0xee
  clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
  mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044
  load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac

  [E][camera.c:1049] camera_probe(): Detected camera not supported.
  [E][camera.c:1249] esp_camera_init(): Camera probe failed with error
  0x20004

I tried all the troubleshooting methods found in other forums


texts:
I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.

I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?


texts: In UART, what mechanism sets the "new data received" flag back to 0?

texts:
I was reading documentation on UART on AVR and it looks simple: when a flag (bit RXC0 of register UCSR0A) is set to 1, it means the micro controller has new data for you, and you read this from register UDR0.

But something boggles my mind: How does the micro controller know that we have read the data? Or, in other words, after it received the first byte on UART, the flag is set to 1, but when is it set back to 0?


texts:
For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.

The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.

void loop() {
// Heartbeat sensor loop
  while (array is not full) {
    delay(30 minutes);
    heartbeatArray[index++] = readHeartbeat();
  }
  sendData_Bluetooth(heartbeatArray);
  emptyArray();
// End of heartbeat sensor loop

// Accelerometer loop
  while (true)
    if (readAccelerometerData > limit)
      sendAlert();
// End of accelerometer loop
}


texts: How can I have the user instantiate an object?

texts:
So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.

A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.

The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()

I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...

Is there a way I could only instantiate the selected program and still call its playNext() method easily?

Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.

Max


texts: Algorithms to reduce measurement error from analogue sensors

texts:
When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).

My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...

My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected.
Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.

Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?

Many thanks in anticipation

// Take mean of multiple sensor readings excluding outliers:

# define SAMPLES 100 // number of samples to take mean of
# define TOLERANCE 0.1 // % range of allowable deviation
                       //between current mean and new values, expressed as decimal

n = 1; // loop variable
total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
mean = total; // mean of all current data

while (n < SAMPLES) {
    new = analogRead(analogPin);
    if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
        total += new; // if new reading is within range, calculate new mean
        n += 1;
        mean = total / n;
        }
    // (else ignore new reading)
}
Serial.print mean;


texts:
Dears,

I have a problem that I could not solve for a while, I tried the code below but it did not work.
There will be 4 buttons controlling 4 relays but in a way that button one will turn relays 1&3 on, if button 2 is pressed only relay 2 turns on, if button 3 is pressed relays 1,2 and 3 will turn on, if button 4 is pressed it is supposed to toggle relays 1&4. one more thing: I need to be able to pass from any button to any of the others and the corresponding relays will be activated while the others will go off.

    #include <Bounce2.h>

    const int     BUTTON_COUNT = 4;
    const int16_t DEBOUNCE_DELAY = 50;
    const uint8_t buttonPins[BUTTON_COUNT] = {28, 29, 30, 31};
    const uint8_t ledPins[BUTTON_COUNT] = {34, 35, 36, 37};

    Bounce buttons[BUTTON_COUNT];
    uint8_t ledStates[BUTTON_COUNT];

    void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
    buttons[i].attach(buttonPins[i], INPUT);
    buttons[i].interval(DEBOUNCE_DELAY);
    pinMode(ledPins[i], OUTPUT);
    ledStates[i] = HIGH;
    digitalWrite(ledPins[i], ledStates[i]);
     }
    }

    void loop() {

// Update the debouncers.
for (int i = 0; i < BUTTON_COUNT; i++)
    buttons[i].update();

// When the first "laban" button is pressed:
if (buttons[0].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[2] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off relays.
    digitalWrite(ledPins[1], HIGH);
    digitalWrite(ledPins[3], HIGH);

}

// When the first "Soda" button is pressed:
if (buttons[1].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[2], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[1] = HIGH;
        ledStates[3] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[1].fell()) {

    // turn off the first LED.
   digitalWrite(ledPins[2], HIGH);

}

// When the first "labanUP" button is pressed:
if (buttons[2].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[2], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off the first LED.
     digitalWrite(ledPins[1], HIGH);
     digitalWrite(ledPins[2], HIGH);
     digitalWrite(ledPins[3], HIGH);
}

// When circulation button is pressed:
 if (buttons[3].rose()) {

    // Toggle its state.
    ledStates[3] = !ledStates[3];
    digitalWrite(ledPins[3], ledStates[3]);
    digitalWrite(ledPins[0], ledStates[0]);
     }
    }


texts:
I've got this quite basic code running on an Arduino Mega 2560, and the output is looking like I have the serial settings wrong, though I can't work out what to change.

void setup()
{
  Serial.begin(9600);
  Serial.println("test123");
}

void loop()
{
  Serial.println("test" + millis());
}

The output looks like this:

ð¦·Z©÷
×ï¾üÿ7ß^|ïüûÿVÏuØëo~ìÿÓûzëýÿ{ßþ©×xñ×¤¿ïßûÏûýoÏ¿îãõI
õfwi÷`p¬½Ïª»QáÀª»¦·ð¦·Z©÷
test123
D

4ñjü¯÷~µÞMz¹Ý~¼
Ûþ}iû}ÒÖ¦Ç¿÷ÿÂï½Õ¾;îö

I'm using the inbuilt "Serial Monitor" in the Arduino suite with settings 9600 baud and no line endings.

I see that the first println in setup() is sending the data as expected but all other comms are coming through as nonsense.

Any suggestions of what to do?


texts:
I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"

// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13

#include <SPI.h>
#include "mcp_can.h"

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

void setup() {
  Serial.begin(115200);
START_INIT:
  if(CAN_OK == CAN.begin(CAN_500KBPS)) {
  // init can bus : baudrate = 500k
    Serial.println("CAN BUS Shield init ok!");
  } else {
    Serial.println("CAN BUS Shield init fail");
    Serial.println("Init CAN BUS Shield again");
    delay(100);
    goto START_INIT;
  }
}

void loop(){
  unsigned char len = 0;
  unsigned char buf[8];
  if(CAN_MSGAVAIL == CAN.checkReceive()) {
    // check if data coming
    CAN.readMsgBuf(&len, buf);
    // read data,  len: data length, buf: data buf
    unsigned char canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.println("get data from ID: ");
    Serial.println(canId);
    for(int i = 0; i<len; i++) {
      // print the data
      Serial.print(buf[i]);
      Serial.print("\t");
    }
    Serial.println();
  }
}

So I get the initialize statement returned but I'm not receiving any data. It seems like the if(CAN_MSGAVAIL == CAN.checkReceive()) statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.


texts:
I am learning about pointers.

I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use Serial.print( (long) &ptr1, DEC); and Serial.print( (long) &ptr1, HEX);

 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10;
   float test2 = 3.14159;
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2;
 char *ptr3;
  ptr1 = &test1;
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");
  Serial.print( (long) &ptr1, HEX);

  }
 void loop() {

    }

My output is:

The integer value is stored in  2296

The integer value is stored in  8f8


texts: Using two ultrasonic sensors together, how can I enable one before the other?


texts: Can we generate 20kHz tone with normal buzzer in arduino?

texts:
Can normal buzzer be used for generating high frequency audio and if this is possible then can normal microphone module be able to detect the same frequency range(15 kHz - 20 kHz).
Here is the specifications of this buzzer:-
Rated Voltage : 6V DC
Operating Voltage : 4 to 8V DC
Rated Current* : ≤30mA
Sound Output at 10cm* : ≥85dB
Resonant Frequency : 2300 ±300Hz
Tone : Continuous
Operating Temperature : -25°C to +80°C
Storage Temperature : -30°C to +85°C
Weight : 2g
*Value applying at rated voltage (DC)


texts: How to explain the need/advantage for volatile in terms of microcontroller instruction flow

texts:
I know there are already many questions why volatile is used when it comes to interrupts.

But explanations like this doesn't help to picture what really happens:

  Specifically, it directs the compiler to load the variable from RAM
  and not from a storage register, which is a temporary memory location
  where program variables are stored and manipulated. Under certain
  conditions, the value for a variable stored in registers can be
  inaccurate.

Above is from the official Arduino website:

And below is the basic Atmega328 architecture:

Is it possible to explain the use/advantage of volatile by comparing it to the usual declaration way considering the above architecture?

I mean such way: If volatile int x is used, the CPU fetches this from this  by this way ect. And if instead int x is used the instruction flow works like this so forth and so on.

Unfortunately I have difficulty to understand from plain two sentence explanations.

As you see my question is about after the compilation what do we observe as a benefit inside the hardware during the instruction flow.


texts: What is this temperature sensor module? (LM358, 103)

texts:
I got this sensor some time ago because I wanted to play with measuring the temperature. I don't remember how I got it or if it has a name.

I've Googled around, and obviously is has the following

LM358 op amp
"103" thermistor

When googling for help I mostly find stuff about how to use the LM358 which is way above my skill level.

What is this and how do use it? :)


texts:
I have noticed that some atmel chips can do "self programming" and I'm doing a hobbyist project where I need to change the "setting" of my arduino without code-reuploading through Arduino IDE.

Is it possible to do that ?
If it's possible. Please give me some basic though about how to do it.

Thanks in advance !


texts: ESP8266 official library post request returns 400

texts:
Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h

if (http.begin(client, host)) {  // HTTP

  http.addHeader("Content-Type", "application/json");
  // Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  // int httpCode = http.GET();
  String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(request);


texts: Using PWM signal to decrease power of laser over time

texts: I'm trying to turn a laser on and off with an external button. When I press the button, the laser should turn on. When I release the button the laser should turn off. However, I don't want the laser to turn off immediately. I want it to turn off linearly over 500 ms. I'm using PWM to alter the strength of the laser over time. However, will my laser power increase and then decrease in the extremely short time segments due to PWM fluctuation? Will it even be able to execute this reduction of power?


texts: Is it possible to program an atmega32 via internet or remotely with Android app?

texts: There is a board with atmega32 microcontroller, sim card and Bluetooth modules. I used to program this microcontroller using a serial port cable. As long as the circuit is able to connect to internet, is it possible to program atmega32 via internet remotely?


texts: Using IMU for a small Arduino and bluetooth support

texts:
I'm gonna start a project with an IMU with a bluetooth support inside a small board (mini or lillypad) and send datas to the mobile phone. But I'm quite new to those kind of technologies.

I'm going to choose a module for handling both operate voltage restriction and memory capacity for both library (IMU and bluetooth).

Any advice obj which arduino / IMU breakout / bluetooth module / battery to use? Or some similar projects?


texts: Lighting LED with Arduino Uno from PC keyboard

texts:
I tried to turn on a LED with my PC keyboard and an Arduino Uno with the letter A.
I get the message

  exit status 1
  'keypressed' was not declared in this scope

My code:

int led1 = 10;

void setup()
{

pinMode(led1, OUTPUT);
}
void loop()
{

 if(keypressed == 'a'){
               digitalWrite(led1, HIGH);
               delay(500);
}
}

What is the problem?


texts: Would this substitute for an Interrupt timer?

texts:
class Pseudo_Interrupt {
  //only cummulative time is important, exact interval is not
  // Class Member Variables
  // These are initialized at startup
  long OffTime = 1000; // milliseconds of off-time
  // These maintain the current state
  unsigned long previousMillis; // will store last time updated

  void Update() {
    // check to see if it's time for an Interrupt
    unsigned long currentMillis = millis();
    if ((currentMillis - previousMillis >= OffTime) {
      //Time to execute the one second code
    }
  }
}


texts:
Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().

 // Pin 13 is the LED

 int led = 13;        // pin 13 on the board
 int ledOFF = 8;      //led off time delay
 int ledON = 5;            //led on time delay
 unsigned long Timer = 0;      // store time
 int runtime = 10000;      // run loop for 10s

 void setup() {
   pinMode(led, OUTPUT);

   Serial.begin(9600);
   delay(1000);
 }

 void loop() {
   Timer = millis();
   int state = 0;
   while(millis() - Timer <= runtime){
     Serial.println(Timer);
     if(state==0){
       digitalWrite(led,LOW);
       state = 1;
       delay(ledOFF);
     }
     else{
       digitalWrite(led,HIGH);
       state = 0;
       delay(ledON);
     }
    }
   }


texts: Programming heart rate monitor with keypad 3x4 input

texts:
i want to make a heart rate monitor with a bpm result classification to classify if the heart rate is normal or not(abnormal). also i want to make it able to input age with keypad 3x4 and classify the heart rate according to the age, because different age has different normal bpm.
anyone can help please?
thanks


texts: I have a uBlox NEO-6M GPS module and it is outputting longitude and latitude. It is also outputting time which is UTC. I want to use the GPS coordinates to calculate the timezone and then subtract and add hours based on that. Is it possible in any way? I know I can do this using WiFi but I want to use GPS to do it.


texts: Arduino IDE Visual Studio and compile problems blank project .ino hack

texts:
I'm new to Arduino and have little programming experience apart from my computer science degree.  I used C++ for some projects in my degree but am barely proficient.

My first project is relatively complex process control for an Arduino beginner and I've quickly become frustrated with the Arduino IDE which seems to be a common problem.  I've installed Visual Studio with the Visual Micro plugin (Win7) but I'm getting compile problems.  I have successfully built a data logging sensor array both in Arduino IDE and Visual Studio in Win7, but as I'm trying to add complexity I'm experiencing difficulties.

I found this recommendation on Gammon Forum for use with the Arduino IDE to achieve a standard C++ build environment but it's not working in the visual studio environment.

Files contained in "EmptySketch" project folder:

"EmptySketch.ino"

//beginning EmptySketch.ino
//end EmptySketch.ino

"TestSketch.cpp"

//beginning TestSketch.cpp

#include <Arduino.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  // put your main code here, to run repeatedly:
}
//end TestSketch.cpp

When I create a project in Arduino IDE this compiles, uploads and runs with the expected output, but when I open EmptySketch.ino in VS it builds, uploads but gives no output.

Can anyone help me with this approach or should I simply upload my real project using a conventional .ino which won't compile and ask for help with that?


texts:
This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.

https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png
^ So you don't have to look it up yourselves. previousMillis is initialized to 0.

However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.


texts: NodeMCU (ESP8266) with SPI TFT, I2C RTC, & 2 Buttons, correct GPIO to use?

texts:
From all my research it seems that the NodeMCU only has 11 available GPIO (6-11 are used to connect flash memory chip), i'm wondering if anybody can help me with these final connections I have left TBD below.

These are all the connections I came up with to the NodeMCU (which equals exactly 11)

TFT - LED pin (to turn on display with 3.3v)
TFT - SCLK - D5 (GPIO14)
TFT - MOSI - D7 (GPIO13)
TFT - CS - D8 (GPIO15)
TFT - DC - TBD
RTC - I2C_SDA - D1 (GPIO5)
RTC - I2C_SCL - D2 (GPIO4)
RTC - SQW/Interrupt - TBD
Switch/Button - TBD
Switch/Button - TBD
External Device (check FALLING) Interrupt - TBD

As you can see, GPIO13-15 are dedicated to SPI for the TFT, and GPIO4-5 for RTC (just bc it's default, could be changed in software if needed).

Because from my understanding this will max out the GPIO available, I want to make sure that the devices left TBD are connected to a GPIO that won't cause issues later on ... and I think trying to wrap my head around this for the past 8 hours, has just made me question what would be the correct GPIO to use, and hoping someone with more familiarity could help me out.


texts: Measure audio frequency through pulse duration

texts:
Hello dear StackExchange users,
i want to develop an Infrared blaster which i can plug into the headphone jack of a phone or console of choice. In order to communicate what frequency to modulate the diode with and how long to send pulses, i simply generate tones for the Arduino to read and interpret.
My problem is that i can't reliably measure the frequency with it. In order to measure the frequency i use an Analog Comparator Interrupt and trigger at falling edge, thus getting always the interrupt after a full pulse occured. I called micros() at every interrupt in order to get the pulse duration, but it was too imprecise. Then i tried using Timer0 with a prescaler of 8 to measure the frequency, but it only counts to 255.
Now i switched over to Timer1 because of it's bigger TCNT register. However for some reason it already overflows at 255 even though i didn't set the OCR1 registers.
This is my current code. Please note that the actual frequency calculation happens in the main loop to not mess with the measurements gained in the ISR.
const int setFrequencySound = 1000;
const int receiveDataSound = 2000;
const int receiveDataEndSound = 3000;

const int readyMode = 0;
const int setFrequencyMode = 1;
const int receiveDataMode = 2;
const int sendDataMode = 3;

volatile unsigned long timeBefore;
volatile unsigned long timeNow;
volatile unsigned long delta;
volatile float audioFrequencyBefore;
volatile float audioFrequency;

volatile float irFrequency;
volatile int irData[100];
volatile int irDataIndex;

volatile int mode = 0;

ISR (ANALOG_COMP_vect)
{
timeNow = TCNT1;
Serial.print (timeNow);
Serial.println (" TCNT1");
//TCNT1 = 0; //reset timer register
}

void setup ()
{
Serial.begin (115200);
Serial.println ("Started.");
ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
      | bit (ACIE)    // Analog Comparator Interrupt Enable
      | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 >> CS10); //Activate timer and set prescaler to 8
TCNT1 = 0; //Reset timer register
}  // end of setup

void loop ()
{
//Calculate frequency by using the period duration
//determined through the timestamps captured in
//ISR method.
//delta = timeNow - timeBefore;
audioFrequency = 1000000000.0 / (float(timeNow) * 2.0);

if (millis() % 1000 == 0)
{
  Serial.print (audioFrequency, 5);
  Serial.print (" Hz, ");
  Serial.print (timeNow);
  Serial.println (" TCNT0");
}

//Do not process the same frequency multiple times
if (audioFrequency != audioFrequencyBefore)
{
  switch (mode)
  {
    case readyMode:
      if (audioFrequency == setFrequencySound)
      {
        mode = 1;

        Serial.println ("Start setting IR frequency.");
      }
      else if (audioFrequency == receiveDataSound)
      {
        mode = 2;

        Serial.println ("Start receiving IR data.");
      }
      break;
    case setFrequencyMode:
      irFrequency = audioFrequency + 25000;

      Serial.print ("IR frequency set to ");
      Serial.print (irFrequency, 10);
      Serial.println (" Hz.");

      mode = readyMode;
      break;
    case receiveDataMode:
      if (audioFrequency == receiveDataEndSound)
      {
        Serial.println ("Stop receiving IR data.");

        mode = readyMode;
        irDataIndex = 0;
      }
      else
      {
        irData[irDataIndex] = audioFrequency;

        irDataIndex++;

        Serial.print ("IR pulse received: ");
        Serial.print (irData[irDataIndex]);
        Serial.println (" microsecs.");
      }
      break;
    case sendDataMode:
      Serial.println ("Sending IR data...");
      break;
  }
}

audioFrequencyBefore = audioFrequency;

}  // end of loop