body:
I have a smoke detector with a piezo buzzer. I want to operate the arduino in low power mode so that it will last on a 9V battery. I've attached an interrupt, and when the digital output of the MQ-2 sensor goes high, it switches to a monitor function.

In the while loop, I check to see if the analog sensor has reached the threshold value, and I output to serial to see if I am in the conditional. If I use:

    digitalWrite(buzzer, HIGH);
then the piezo sounds, however if I use

    tone(buzzer, 1000,200);
    delay(200);
it does not. I'm confused as to why this would be the case.

Full code as follows:

    #include "LowPower.h"

    int redLed = 12;
    int greenLed = 11;
    int buzzer = 10;
    int smokeA0 = A5;
    // Your threshold value
    int sensorThres = 50;
    int smokeD0 = 2;

    void setup() {
      pinMode(redLed, OUTPUT);
      digitalWrite(redLed, LOW);
      pinMode(greenLed, OUTPUT);
      digitalWrite(greenLed, HIGH);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      pinMode(smokeD0, INPUT);

    }
    void switchToMonitor() {
      Serial.begin(9600);
      int digitalSensor = digitalRead(smokeD0);
      if (digitalRead(smokeD0) == HIGH)
      {
        digitalWrite(redLed, HIGH);
        digitalWrite(greenLed, LOW);
      }
      else {
        digitalWrite(redLed, LOW);
        digitalWrite(greenLed, HIGH);
      }
      //This will be updated later to use the analog input
      //Using digital to make debugging easier
      while (digitalSensor == HIGH) {
        int analogSensor = analogRead(smokeA0);
        Serial.print("Pin A0: ");
        Serial.println(analogSensor);
        Serial.print("Pin D0: ");
        Serial.println(digitalSensor);
        // Checks if it has reached the threshold value
        if (analogSensor > sensorThres) {
          digitalWrite(buzzer, HIGH);
          //tone(buzzer, 1000,200);
          Serial.println("here");
          delay(1000);
        }
        else {
    //      digitalWrite(redLed, LOW);
    //      digitalWrite(greenLed, HIGH);
          noTone(buzzer);
          Serial.println("also here?");
        }
        //delay(100);
        digitalSensor = digitalRead(smokeD0);
      }
      noTone(buzzer);
    }

    void loop() {
      //delay(100);
      //LowPower.standby();
      attachInterrupt(0, switchToMonitor, CHANGE);
      LowPower.powerDown(SLEEP_FOREVER, ADC_ON, BOD_ON);
      detachInterrupt(0);
    }

title: Behaviour of tone() not as expected within while loop

Answers: 1

body: You can't use delay() or timer based tone() function in interrupt handler. Set a flag in interrupt and run the code  in loop() conditionally based on the flag state. Do not forget to have the flag variable volatile.


body:
I want to read a binary body datas from an HTTP POST request.

The context is that I'm making a LED strip controller and I'm currently using this code :
```cpp
#include <WebServer.h>
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, STRIP_PIN, NEO_GRB | NEO_KHZ800);
WebServer server(80);

void handleSimpleWrite()
{
    int r = 0, g = 0, b = 0;
    if (server.hasArg("red"))
        r = server.arg("red").toInt();
    if (server.hasArg("green"))
        g = server.arg("green").toInt();
    if (server.hasArg("blue"))
        b = server.arg("blue").toInt();
    strip.setPixelColor(id, r, g, b);
    strip.show()
    server.send(200,"Ok");
}
```

It works, but it's clearly innefficient. I want to make an API endpoint that get a binary buffer with RGB states along the request body and I can't figure out how to read this body.

Any ideas ?

title: How to get the body of an HTTP request?

Answers: 0


body:
I want to send some data to an IP Modem from Arduino Uno. That IP Modem has TTL levels TX and RX inputs.

I used this connection between Arduino to the IP Modem:

[![Schematics of connections][1]][1]

I am powering Arduino with 12 V plugged in the barrel.

This is the photo of the connections:

[![Actual photo][2]][2]

I connected the PC to the USB connector of Arduino and I uploaded the following sketch to send "AABB" to the Modem:

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

    void loop(void) {
     Serial.print("AABB");

     delay(5000); // Envía la temperatura cada 5 segundos
    }

When monitoring what is received by the modem, it is

0x5F 0x5F 0xAF 0x2F

If I send just "A", the character received each 5 seconds is 0x5F.

Of course, both ends are configured as 115,200bps, 8N1.

In order to discard Modem problem, I connected RX, TX and GND in Arduino to a DB9 female connector and then to a RS232 - USB converter and started monitoring with my PC.

My surprise was that the data received is exactly the same as the received by the modem when it was connected. As seen in the following picture:

[![Serial monitoring from PC][3]][3]

As you see in the picture, "_" twice was shown (ASCII 0x5F), {\xaf} and finally "/" (ASCII 0x2F).

Above test confirms Arduino is sending wrong data.

Something to note. When I monitor using USB cable connected to Arduino and using Monitor Serie in the Arduino IDE, I  see correctly "AABB". The problem is when using TX and RX pins (the same happened if I used other pin along with SoftwareSerial library)

What may be going on?

  [1]: https://i.stack.imgur.com/6XmzZ.png
  [2]: https://i.stack.imgur.com/WzvK8.jpg
  [3]: https://i.stack.imgur.com/HApKw.png

title: TX pin sends wrong data in Arduino Uno

Answers: 1

body:
Since you have already tried SoftwareSerial, also try inverting the serial protocol via SoftwareSerial.  Sometimes a device uses inverted serial protocol and you don't know it.

So initialize inverted add 1 to the end of the contructor like so :
```
SoftwareSerial mySerial(RXPIN, TXPIN,1); // RX, TX, inverted
```


body:
I would like to building a 8x64 RGB Matrix and connect it to my Arduino.
As this form factor does not really exist I would need to build one myself but now I am wondering if I should use addressable LEDs like WS2813 or APA107 and use FastLED or rather use 'dumb' LEDs and just multi-/charlieplex them using a MAX7221 or comparable chip.

What are some pros and cons I should consider with each one? I read that to many WS2813 can make problems but APA107 seem to fix that. But on the other hand most bigger matrices just use multiplexing........

title: Addressable LEDs vs Multiplexing for a Matrix

Answers: 1

body:
The smart RGB LEDs will be brighter. Each device has its own control chip that controls the 256 PWM level for each of the 3 LEDs. So for an 8x64 array, you send in 3 bytes/device, 8x64x3 = 1535 btyes, pause a few microseconds, and the array updates itself.

Going the multiplexing route, you would do something like have 64x3 = 192 anode drivers (or up to 192, if not all are LEDs are lit up) to enable the LEDs across the display, and then 8 common cathode drivers to turn on each row one at a time for 1/30 to 1/24 of a second for minimal flicker. So 192 LEDs, 20mA each, the common cathode needs to be able to sink 3.84A

On the otherhand, 8x64 LEDs, each needing up to 60mA at full on, = 30.72A.


body:
I'm using MPU 6050 and there's a thermometer onboard. However, I looked through [the chip set data sheets][1] but could not find the instruction for temperature sensing.

Could you tell me how to calibrate the data string from the two address started from 0x41?

  [1]: https://www.invensense.com/products/motion-tracking/6-axis/mpu-6050/

title: How to calibrate MPU 6050 thermometer?

Answers: 1

body:
The temperature sensor is likely included to keep the gyroscope and accelerometer better calibrated over the specified temperature range.  The temperature may not be the ambient temperature should the chip warm up.

The temperature sensor specifications are in section 6.3 on page 14 of the [specification sheet][1] indirectly pointed to in the question.

    TEMPERATURE SENSOR
    Range -40 to +85°C
    Sensitivity Untrimmed 340 LSB/ºC
    Temperature Offset 35ºC -521 LSB
    Linearity Best fit straight line (-40°C to +85°C) ±1°C

So, when the chip is at 35C the chip temperature register is supposed to read about -521.  To convert that into C you need to make a calculation:

> chip_temperature = ((value_read + 521) + (35 * 340)) / 340

Simplified:

> chip_temperature = (value_read + 12421) / 340

  [1]: https://43zrtwysvxb2gf29r5o0athu-wpengine.netdna-ssl.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf


body: I am trying to figure out how to use the WASD keys on my computer, to go through the USB cable and then spin the Arduino servos in real-time. So if I press the “a” key, it should start to move left with little time delay. How do I do this?

title: How to create real-time WASD control over an Arduino Uno?

Answers: 0


body:
I have some cheap KY66 (seems to be SG90 clone) servos.

When I turn them to 0°, the servo tries moving and moving, without actually getting to 0°. I read that they are reaching the endpoint but the built-in potentiometer does give a reading of 0.

By changing the code and fiddling with the angle, I find that the minimum for one particular servo is 25°.

I'm now trying to figure out how the Arduino could determine this value automatically. I have tried

    servo.write(0);
    delay(3000);
    int direction = servo.read();

and expected to get back a value near 25, but it was 0 instead. So the result of `read()` does not seem to be an actual reading, but more the "last known" setpoint.

I've also tried to relax the servo before reading:

    servo.write(0);
    delay(3000);
    int direction = servo.read();

with no better result.

I like to figure out the minimum and maximum angle of the servo

* because I don't like the servo to make much noise (it really doesn't sound healthy)
* without having the user to figure out by himself and the need of re-programming the Arduino.

I know that these cheap servos only have 3 pins. 2 pins are for power supply only, so there's only 1 pin left.

My questions:

* Is the data pin uni-directional (PWM output from Arduino to servo)?
* Will it ever be possible to implement what I want without additional hardware?
* How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?

title: How to determine minimum and maximum angle for cheap servos?

Answers: 2

body:
I think you have 2 choices: either measure and store for each one individually, or find the worst case for all of them and code around that.

Do you really need the full travel? If you're using the servo to push/pull, the servo-travel endpoints are pretty weak anyway.

> I wanted a robot look left and look right, which is 0° or 180°.

Maybe you can make up the limited angular travel of the servo in the linkage between the it and the camera platform.

body:
> Is the data pin uni-directional (PWM output from Arduino to servo)?

As you found out, standard servos have only three pins. And yes, two of them provide ground and power, and the third is a unidirectional signal.

This signal is commonly a pulse of 1 ms to 2 ms, repeated every 20 ms.

`servo.read()` can therefore only return the last value set by `servo.write()`.

> Will it ever be possible to implement what I want without additional hardware?

I don't think so.

You could insert a shunt into the power line and measure the current. If it stays high for extended periods, it means that the servo is still powering its motor. But this could be true also for other reasons than being at its own mechanical limit.

> How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?

Since servos are used as a closed (sub-)system, I don't think that they are opened to read their potentiometer. And even if you do this, you might affect the internal working of the servo.

Eventhough I built several model aircrafts since the late 70s and used different servos, I have no feeling about the calibration of cheap or expensive servos. IIRC some data sheet documented ranges of only +/- 45°.

So the values `0` to `180` for `servo.write()` is just a mapping for 1 ms to 2 ms.

To make a long story short, I have no idea how people solve this.

You might like to limit your range to some "healthy" values, or ask the user to help in calibration. The calibration results can be stored in EEPROM, there is no need to reprogram the Arduino.

If you need the robot's head to turn from 0° to 180°, consider using some gear so that the servo just needs to move between, let's say, 30° to 150°. This is the way modellers go.


body:
In the (official) file `wiring_shift.c` I found the following code for shiftOut:

    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)
       digitalWrite(dataPin, !!(val & (1 << i)));
      else
       digitalWrite(dataPin, !!(val & (1 << (7 - i))));

      digitalWrite(clockPin, HIGH);
      digitalWrite(clockPin, LOW);
     }
    }

However, the last two `digitalWrite` commands occur directly after each other. I wouldn't hope that `digitalWrite` depends on some time or delay, so how can it be assumed that the slave device sees the clockPin is HIGH if the Arduino immediately sets the clockPin to LOW again?

(My plan is to convert the shiftIn/shiftOut code to STM32 using HAL/CubeIDE).

title: Is the shiftOut code depending on the (low) speed of an Arduino?

Answers: 1

body:
Some time ago, I timed digitalWrite() and direct port write commands by looping over 10,000 executions of each and timing them with millis(). I made both tests on a 16MHz Atmega 328p at 16MHz.

For `digitalWrite(13, LOW)`, I got 2.7usec / call.

For `PORTB &= 0x20;`, I got 0.15usec / statement. (The direct port access was executed 10 times within the loop to further pad it out for the `millis()` result to have any significance.)

[In my notes I wrote that I timed `PORTB &= 0x20;`, but the correct equivalent to the `digitalWrite()` version is `PORTB &= ~0x20;`. That is probably what I actually did, but note that the bit-mask would be generated at compile time, so either way should have produced the same result.]

> how can it be assumed that the slave device sees the clockPin is HIGH

It would depend on the specifics of the slave, but it is quite likely triggered by a pulse, rather than polling its input until it finds a high-level.

Update:
To confirm my timing data, I redid my 2.5-years-ago experiment. I put 10 statements in each of 2 loops of 10,000 iterations, either:

    digitalWrite(13, LOW);

or

    PORTB &= ~0x20;

And got these total times in msec for the 100,000 executions:

digitalWrite(): 305  // digitalWrite(13, LOW);
PORTB (correct): 15  // PORTB &= ~0x20;

These translate to single execution times in 10s of nanoseconds:

3050 nsec == 3.05 usec for the function call,

150 nsec for direct port I/O, making port I/O about 20x faster.


body:
I just started two weeks ago with Arduino and I'm hooked!

I got off to a good start and went through some online tutorials quite easily. Then came the RGB LED, which I couldn't get to work all of a sudden (it required putting in a color through the serial monitor, which would then be given by the RGB).

And the strange thing is, I can't get anything to work anymore that requires input through the serial monitor, where I used to get it working immediately...

I presume it's something with the if-statement, because if I remove it and just say digitalwrite HIGH to a certain pin, it works fine....

Checks I did:

- Full re-install of Arduino (didn't solve it).
- Check the LEDs by hooking them up to 5V directly (they all work).
- Reconnecting the Arduino (didn't solve it).
- Use a multimeter to measure current (there isn't, although the if-statement matches...

Here's my code. Does anybody see it? Because I don't...

Regards,

nannev (using Mac and Arduino Uno)

```
int yellowPin=8;
int redPin=9;
int greenPin=10;
String myLED;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
}

void loop() {
  Serial.println("Your color?");
  while (Serial.available()==0) {
  }

  myLED=Serial.readString();
  Serial.print(myLED); //check if the input came through correctly, which it did
  delay(1000);
  if(myLED == "yellow"){ .    //nothing happens at yellow....
    digitalWrite(yellowPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "red"){             //nothing happens at red....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "green"){       //nothing happens at green....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
  }
}
```

title: If-statement matches but doesn't give a result

Answers: 1

body:
The Arduino IDE uses the C and C++ programming languages.

***Some string comparison basics using C:***

In the C programming language, a string can be thought of as an array of 8 bit values.  One way to compare two strings is to compare each 8 bit value and consider the strings different (not equal) upon finding the first not-matching 8 bit value.  [Here is an example from programmingsimplified.com][1]:

    int compare_strings(char a[], char b[])
    {
       int c = 0;

       while (a[c] == b[c]) {
          if (a[c] == '\0' || b[c] == '\0')
             break;
          c++;
       }

       if (a[c] == '\0' && b[c] == '\0')
          return 0;
       else
          return -1;
    }

There is a common function called strcmp() which can be used instead.  Here is another example from the same web page which uses strcmp():

    #include <stdio.h>
    #include <string.h>

    int main()
    {
       char a[100], b[100];

       printf("Enter a string\n");
       gets(a);

       printf("Enter a string\n");
       gets(b);

       if (strcmp(a,b) == 0)
          printf("The strings are equal.\n");
       else
          printf("The strings are not equal.\n");

       return 0;
    }

Note that in both cases the array of strings is assumed to end with a NULL or zero value byte.  If you do not wish to follow this format you can use an alternate version of the function called [strncmp()][2] where the number of characters to be compared is passed along with pointers to the 2 strings.

***Some string comparison options using C++:***

There are C++ ways to compare 2 strings which make coding Arduino Sketches easier.  But C++ string manipulation usually requires more RAM.  And RAM is usually in short supply on inexpensive embedded processors.

As the code in the question is written using type String we can explore that approach. And, as there is some concern the strings may have unexpected trailing characters, we will continue to check only the necessary number of characters. In this slightly modified [code example from geeksforgeeks.org][3] string s1 is compared with string s2.  But only the first 6 characters are compared:

    void compareOperation(string s1, string s2)
    {
        // Compares 5 characters from index number 3 of s2 with s1
        if((s2.compare(0, 6, s1)) == 0)
            cout << "Here, "<< s1 << " are " << s2;

        else
            cout << "Strings didn't match ";
    }

The number 6 was chosen because "yellow" contains 6 printable characters.  In this way, we can avoid the uncertainty of what character(s) follow the characters that make up "yellow" as received from the serial port.

  [1]: https://www.programmingsimplified.com/c-program-compare-two-strings
  [2]: https://www.tutorialspoint.com/c_standard_library/c_function_strncmp.htm
  [3]: https://www.geeksforgeeks.org/stdstringcompare-in-c/


body:
I am a NOOB!  Trying to use the ZS-042 RTC module to retrieve the current time and send it back to the RPi over I2C.  I can call the function and spool it to Serial but when I try to call the function to update the global variables from within the call back function for onRequest() the Ardiuno (Micro) crashes.

```ino
#include <Wire.h>

// LED on pin 13
const int TEMP_PIN1 = A0;
const int RELAY_PIN1 = 4;
const int SAMPLE_TIME = 100;
const byte RPI_I2C_ADDRESS = 0x08;
const int DS3231_I2C_ADDRESS = 0x68;

byte number = 0;
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

/*
 * RTC Setup
 */
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val) );
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
      dayOfMonth, byte month, byte year)
{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (0=Sunday, 6=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

/*
void readDS3231time(byte *second,
    byte *minute,
    byte *hour,
    byte *dayOfWeek,
    byte *dayOfMonth,
    byte *month,
    byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
*/

void readDS3231time()
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  second = bcdToDec(Wire.read() & 0x7f);
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read() & 0x3f);
  dayOfWeek = bcdToDec(Wire.read());
  dayOfMonth = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

void displayTime()
{
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  // send it to the serial monitor
  Serial.print(hour, DEC);
  // convert the byte variable to a decimal number when displayed
  Serial.print(":");
  if (minute<10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second<10)
  {
    Serial.print("0");
  }
  Serial.print(second, DEC);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/");
  Serial.print(year, DEC);
  Serial.print(" Day of week: ");
  switch(dayOfWeek){
  case 0:
    Serial.println("Sunday");
    break;
  case 1:
    Serial.println("Monday");
    break;
  case 2:
    Serial.println("Tuesday");
    break;
  case 3:
    Serial.println("Wednesday");
    break;
  case 4:
    Serial.println("Thursday");
    break;
  case 5:
    Serial.println("Friday");
    break;
  case 6:
    Serial.println("Saturday");
    break;
  }
}

void flash_data(int loops)
{
   for (int i = 0; i < loops; i++)
   {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED Pin HIGH: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED Pin LOW: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
   }
}

// callback for received data
void receiveData(int byteCount)
{
  Serial.println("Receiving Data... ");
  if ( Wire.available() ) {
    number = Wire.read();
  }
  Serial.println("Data Received: "+String(number));
}

void sendData() {
  Serial.println("Sending Data on Request");
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  //char buf1[20];
  //sprintf(buf1, "d:d:d d/d/d",  hour, minute, second, dayOfMonth, month, year);
  //Serial.print(buf1);
  Wire.write("Hello");
}

void setup() {
  Serial.begin(57600);
  do {
    delay(500);
  } while (!Serial);

  delay(500);
  Serial.println("Initializing Wire I2C on "+RPI_I2C_ADDRESS);
  // Join I@c bus as slave with RPI_I2C_ADDRESS 8
  Wire.begin(RPI_I2C_ADDRESS);

  Serial.println("Setting call back for Wire.onReceive");
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);

  //Setup pin 13 as output and turn LED off
  Serial.println("Setting LED Pin up for Output");
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(RELAY_PIN1, OUTPUT);
  pinMode(TEMP_PIN1, INPUT);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);
}

float getVoltage(int pin)
{
  // This function has one input parameter, the analog pin number
  // to read. You might notice that this function does not have
  // "void" in front of it; this is because it returns a floating-
  // point value, which is the true voltage on that pin (0 to 5V).
  return (analogRead(pin) * 0.004882814);
  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
  // being read at that pin.
}

/*
 * MAIN LOOP
 */
void loop() {

  if ( number > 0 ) {
    //Serial.println("Flash Data: "+String(number));
    flash_data(number);
    float voltage, avgVoltage, degreesC, degreesF;
    if (number == 1) {
      digitalWrite(RELAY_PIN1, HIGH);
    } else if (number == 2) {
      digitalWrite(RELAY_PIN1, LOW);
    } else if ( number == 3 ) {
      voltage = getVoltage(TEMP_PIN1);
      //gets and prints the raw data from the lm35
      Serial.print("Voltage: ");
      Serial.print (voltage);
      Serial.println(" ");
      // Now we'll convert the voltage to degrees Celsius.
      // This formula comes from the temperature sensor datasheet:
      degreesC = (voltage - 0.48) * 100.0;
      Serial.print("CELSIUS: ");
      Serial.print(degreesC);
      Serial.println("*C ");
      //converts celsius into fahrenheit
      degreesF = degreesC * (9.0/5.0) + 32.0;
      Serial.print("FAHRENHEIT: ");
      Serial.print(degreesF);
      Serial.println("*F");
    } else if ( number == 4 ) {
       displayTime();
    }
    number = 0;
  } else {
    byte pinValue = bitRead(LED_BUILTIN, 3);
    if ( digitalRead(LED_BUILTIN) == HIGH ) {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
  delay(SAMPLE_TIME);
}
```
Any guidance would be appreciated!
THanks

title: Cannot call function in call back for onRequest()

Answers: 1

body:
The onRequest and onReceive callback functions are called from inside an ISR. Thus you cannot use any code in there, that relies on interrupts to work. Serial writes or prints for example will only work, as longs as the buffer is not full (since the actual communication is handled by interrupts). If the buffer is full, the serial code will either block or loose data (depending on the version of the Arduino core. Not blocking in an ISR is a relatively new change). Such things also hapoen with other interrupt driven functions.

Let's take your codes logic particular in the onRequest callcack function. As written above, this is called from an ISR. The Wire library was contacted by the master to send data to it. With this callback the library uis asking you, what to answer the master. During that time, the current transmission (master read, slave send) is already active, but the slave is stalling the transaction, until the data is ready, meaning until you exit the onRequest callback. Now inside the callback you try to initiate another transaxtion on the same I2C bus, now as a master. The same I2C bus, where there is already a transaction going on. That cannot work. The former slave cannot take the control over the bus, since the first master haven't released it yet (as you tried this in the middle of it's transaction. So you are not only using interrupt driven functions in an ISR, you are also trying to reconfigure hardware, that you just got an interrupt from (which is a bad idea, unless you really know, what you are doing). The library has configured the hardware as slave and in the middle of the transaction you try to configure it as master.

I don't know, why you even try to do this. Since you already have the RTC on the same bus as the Pi, why not making the Pi the only master and let it directly poll the RTC? Why do you need the Arduino between them?

If you really really need the multi master setup for whatever reason (though I cannot think of one), you have to do the transactions independent of one another. The Arduino could poll the RTC regularly, when the bus is free, and buffer the results. Then it could send these results to the Pi, when it requests the Arduino to do that.

---

Note: I'm currently not up to date, how good the multi master support in the Wire library is these days. It incorporated the possibility for multi master since a long time, but when I checked last time, the bus arbitration was not implemented (meaning that if 2 masters try to send at the same time, the bus gets stalled). If it is still this way, you shouldn't use multi master with the Wire library.


body:
I read a comment form [here][1]:

"Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds."

According to the [latest webpage][2],

"Serial functions that use the timeout value set via Serial.setTimeout():

    Serial.find()

    Serial.findUntil()

    Serial.parseInt()

    Serial.parseFloat()

    Serial.readBytes()

    Serial.readBytesUntil()

    Serial.readString()

    Serial.readStringUntil()

"

So apparently, there's no direct indication to set a timeout option for Serial.read().

How to set a time out like Serial.setTimeout() for Serial.read()?

  [1]: https://forum.arduino.cc/index.php?topic=439572.0
  [2]: https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/

Answers: 1

body:
You can't set timeout for read(), but you can use readBytes() to read one byte.

    byte b;
    int count = Serial.readBytes(&b, 1); // read one byte with timeout
    if (count) { // 0 or 1
      Serial.write(b); //echo
    }


body: Suppose one connected two of the Arduino Uno boards through Rx and Tx pins. Then, if one or both of the Arduino boards were connected to computer, and possibly opened up Serial Monitors, will Tx and Rx pin still be working? i.e. will Arduino still communicate through Rx and Tx pin when it's communicating to computer? If not how to make them working while connect to computer?

title: If Arduino connected to computer and opened up Serial Monitor, will Tx and Rx pin still be working?

Answers: 4

body:
You should't connect two TX Pins together. The Arduino has some protection resistors but even it is not recommended to connect two output pins.

The only save way to use the RX / TX pins directly is to remove the protection resistors (RN4A and RN4B in the reference design) or at least the RN4A  and use only one connection at a time. It doesn't help if you do not use the PC connection or doesn't open the Serial Monitor since the pins is still an output.

(Multiple RX Pins are no problem since they are inputs)

(And of course I know it could work with multiple TX pins together most of the time, but I would recommend it)

body:
> Suppose one connected two of the Arduino Uno boards through Rx and Tx
> pins.

I assume you will connect the TX of one Arduino to the RX of the other
one and vice versa, which is the right way to connect them. As
theSealion explained in his answer, you shouldn't connect two TX Pins
together.

> if one or both of the Arduino boards were connected to computer, and
> possibly opened up Serial Monitors

If you do that, the Arduino won't even notice.

Well, to be more accurate... there is a small chip on the Uno, near the
USB connector, labeled “MEGA16U2”. This chip is used as a USB/serial
converter, and it _will_ notice when you connect the USB link and when
you open the port. However, the main chip (the big PDIP28), which is the
microcontroller that runs your sketch, will neither know nor care.

> will Tx and Rx pin still be working?

Absolutely.

> will Arduino still communicate through Rx and Tx pin when it's
> communicating to computer?

The RX will not communicate with the computer. What will happen is:

* Whatever your Arduino writes to its serial port will be received by
  both the other Arduino and the serial monitor.
* Whatever you send through the serial monitor will be lost.
* When you `Serial.read()`, you will get whatever was set by the other
  Arduino.

The reason of this behavior is a 1 kΩ resistor that sits between
the Mega16U2's TX and the main microcontroller's RX. When you connect
this RX to the other Arduino's TX, which is low impedance (≈ 25 Ω),
that TX will “win”: a low impedance output overwhelms a high impedance
one.

body:
> how to make [two Arduinos communicating with each other] working while connect to computer?

There are a variety of ways for 2 Arduinos to directly communicate with each other while one or both are communicating with the Serial Monitor of a laptop computer over USB.

* Use a UART for the Arduinos to communicate that is independent of the USB connection. (See https://www.arduino.cc/reference/en/language/functions/communication/serial/ )
    * Several Arduino-compatible boards such as the Arduino Mega 2560, Arduino Due, Arduino Uno Wifi Rev.2, etc. have 4 hardware UARTs; the pins of Serial1 (note the "1") could be used to communicate with another Arduino without interfering with the Serial (without a "1") UART communication over USB to a laptop. (Alas, the Arduino Uno has only 1 hardware UART).
    * The ATmega32u4-based Arduino Micro and Arduino Leonardo and ATmega32u4-based Arduino derivatives such as [FLORA](https://www.adafruit.com/index.php?main_page=category&cPath=92) and many of the ARM-based Arduino derivatives such as the [Teensy series](https://www.pjrc.com/teensy/td_uart.html) have a USB interface that doesn't use *any* of the UART pins; so the pins of Serial1 (note the "1") could be used to communicate with another Arduino without interfering with the Serial (without a "1") non-UART communication over USB to a laptop. (Alas, the Arduino Uno has a USB interface that *does* use its only hardware UART pins).
    * Even the Arduino Uno, which has only 1 hardware UART whose pins are hard-wired to the USB interface chip, can bit-bang a slow simulation of a UART on other pins. See https://arduino.stackexchange.com/questions/34126/whats-the-difference-between-all-the-software-serial-libraries-which-one-is-ar .

* Rather than try to simulate a UART in software (the timing is kind of tricky), it may be easier/faster to use some other less time-sensitive ways of communicating between Arduino Unos or other Arduinos, such as
    * SPI between 2 Arduinos [(a)](https://forum.arduino.cc/index.php?topic=120049.0); [(b)](https://circuitdigest.com/microcontroller-projects/arduino-spi-communication-tutorial)
    * I2C between 2 Arduinos [(a)](https://www.instructables.com/id/Communication-Between-Two-Arduinos-I2C/) [(b)](https://dronebotworkshop.com/i2c-arduino-arduino/)
    * [PJON between 2 Arduinos][1]
    * a few [asynchronous communication](https://en.wikipedia.org/wiki/asynchronous_circuit#Communication) protocols have no timing dependencies at all
    * etc.

  [1]: https://hackaday.com/2016/03/31/pjon-fancy-one-wire-arduino-communications-protocol-for-home-automation/

body:
I got exactly the same problem! I was using the Arduino Uno board with an Jtag ICE mkii for debugging which was working nice. As I begann to use the UART it was a heavy mess. The transmitting from Arduino to an external TTL-USB adapter was working but not in the other direction. I played hours before I saw this thread and that gave me the idea for looking into the shematic -> Bang! I saw the two resistors.
Lesson learned: Do not use the Arduino hardware without the rest of the tools! Thought it was a good idea to use the hardware for rapid development. Now it costs me more time that I thought...


body:
I have this code:

[![enter image description here][1]][1]

-----------------------------------------------

The output looks like this:

[![output][2]][2]

Why are there non-periodically some extremely large values?

Thanks

  [1]: https://i.stack.imgur.com/p0XtM.png
  [2]: https://i.stack.imgur.com/mGbnf.png

title: Unconsistent time in arduino loop

Answers: 3

body:
There are be several "tasks" and interrupts that run in the background and they influence how often the loop() function is called.

For example timer, usart ...

They all need some attention from time to time. If the need some really fixed execution time you must use something like a hardware timer.

and by the way: a maximum of ~1.1ms is not bad for such a small controller. :-)

And as a addition to your question in your comments: I don't think there is a way to make the loop faster. As long as you need the other tasks, you have do give them some time.

body:
As explained by theSealion in his answer, this may be due to the
different background tasks performed by the microcontroller. However, I
personally find that 1 ms looks excessive. My guess is that the
main culprit is the USB stack pushing all those bytes down the wire.

In order to check this, I wrote the following program. It measures a
histogram of the loop execution times and then prints it through the
serial port. Since the data is only printed _after_ the measurements are
done, the serial port does not do any work while the timings are being
measured.

```c++
const int HISTOGRAM_LENGTH = 512;

uint16_t histogram[HISTOGRAM_LENGTH];

void print_histogram() {
    Serial.println(F("t (us)  count"));
    Serial.println(F("-------------"));
    for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
        if (histogram[i] == 0) continue;  // skip zeros
        Serial.print(i * 4);
        Serial.print('\t');
        Serial.println(histogram[i]);
    }
    Serial.println(F("-------------"));
    Serial.flush();
}

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

void loop() {
    static uint32_t last_time;
    uint32_t now = micros();
    uint32_t dt = now - last_time;
    uint32_t bin = dt / 4;  // resolution of micros() is 4 us
    if (bin >= HISTOGRAM_LENGTH)
        bin = HISTOGRAM_LENGTH - 1;
    if (++histogram[bin] == UINT16_MAX) {
        print_histogram();
        exit(0);
    }
    last_time = now;
}
```

These are the results when run on an Arduino Uno:

```text
t (us)  count
-------------
8       21888
12      65535
16      632
20      323
56      1
-------------
```

This shows that most loop iterations take 8–12 µs. Those iterations
that were interrupted took 16–20 µs. The outlier at 56 µs is
most likely the time between the program starting and the very first
iteration of `loop()`.

Here, the only interrupt source that affects the measurements is the
timer interrupt. It fired exactly 955 times during the measurement
period, which is consistent with the number of samples recorded at
16–20 µs. We can see from this data that the timer interrupt takes
roughly 8 µs to run, which is quite reasonable. Again, I would not
consider a 1 ms delay as reasonable.

body:
> In addition, the original problem for this question was that I am
> driving a stepper motor and I need to communicate with Raspberry Pi
> using UART. The problem is that when I send some data about the motor
> to RPi and the motor is already spinning very fast, I often loose a
> step

Your stepper code has to run very consistently to maintain 3000 steps/sec without jitter or dropping steps. It must not have to wait for communication or any other task but be able to issue the next step command on-time. Some possible techniques to accomplish this:

- Don't post an entire message to the Pi but send only a few characters at a time, between steps.
- Talk to the Pi in shorter, tightly coded messages, and let the Pi expand them if it needs to.
- Use the highest baud rate the Uno & Pi can reliably use.
- Issue step commands in a timer-driven interrupt routine, with any stepper housekeeping done in the background, between step-commands.
- Use a faster processor.


body: I am trying to make a small project using Nodemcu. My project is WiFi controlled LED, 2 LED's will blink at the same time. I have successfully uploaded the code and it works fine using USB connection. But I want to power the Nodemcu using 12 volts 1.5 amps AC to DC adapter. I have checked it in web search but I have not found an understanding circuit. please help me out guys.

title: How to power Nodemcu using 12 volt AC to DC adapter?

Answers: 1

body:
You connect the + side of the adapter to VIN pin and the - side to GND.

You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.

See this link: [Power Related ESP-12E Development Board Pins][1], fragment 'Using a Wall Wart':

[![enter image description here][2]][2]

Examples: [Wall-Mount-AC-Adapters][3]

The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
  [2]: https://i.stack.imgur.com/7PQpq.png
  [3]: https://nl.mouser.com/Power/Power-Supplies/Plug-In-AC-Adapters/Wall-Mount-AC-Adapters/_/N-brwlv?P=1yxt7f5


body:
i am trying to make a get request, read that request and make another request with that read value. i havent shown it in this code but i want to make a request inside in a request. is it possible to make a request without ending one, if its, how do i do that?

here is the code :
```
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "pw"

void conn();
void getreq();
void anothergetreq();

void setup() {
  conn();
  getreq();
}

void loop() {
}

void getreq() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/users/1");

  int httpCode = http.GET();
  String payaload = http.getString();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  //here i presume got the value from payload, and making another request with it
  anothergetreq("posts/1");
  http.end();

}
void anothergetreq(String p) {

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/"+p);

  int httpCode = http.GET();
  String payaload = http.getString();

  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  http.end();
}

void conn() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

```
here is the output:
```
Connected with IP: 192.168.1.100

HTTP CODE: 200
PAYLOAD: {
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
HTTP CODE: -1
PAYLOAD:

```

title: esp8266 cant make more than one request at time

Answers: 1

body:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

> Secure clients and servers require siginificant amounts of additional
> memory and processing to enable their cryptographic algorithms. In
> general, only a single secure client or server connection at a time
> can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.


body:
I am using the Arduino Mega schematic found [here][1] and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

[![enter image description here][2]][2]

Does anyone know what these are and where they go?

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf
  [2]: https://i.stack.imgur.com/4IuP4.png

title: What are these stray resistors on the Arduino Mega schematic?

Answers: 1

body:
Those are unused resistors in resistor arrays.  The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

[![enter image description here][1]][1]

* Elements A and D of Resistor Network 1 (RN1)
* Elements B and C of Resistor Network 2 (RN2)
* Element C of Resistor Network 3 (RN3)

  [1]: https://i.stack.imgur.com/3ffBJ.jpg


body:
I have an Arduino UNO (clone, not original) that was working fine until a couple of days ago. Now, it does not show up when I connect it to my laptop.

Things that I've troubleshouted:

1. USB cable is fine (tried with another Arduino).
2. USB ports are fine (tried with another Arduino).

3. Followed all the fixes and checks listed
    [here](https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board?newreg=3f52658e2bbc4b77969435f443c1bccf)
    and everything is successful.

4. I can upload sketches trough ICSP using a working Arduino.

5. I've tailed `syslog` while connecting and disconnecting the failing
    Arduino and nothing shows up (it does when using the "good one").

6. I've tried on a Windows 10 machine and it doesn't show up.

What else can I try?

title: Arduino UNO not showing up in USB devices on Ubuntu 18.04

Answers: 1

body:
I can't comment yet but have you updated your board manger for UNO on unbunto?

tools > Board > Board Manger > Search UNO

Kind of dumb to have to do that but it happen to me before and this was the solution I did.


body:
I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.

I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.

What could possibly be the reason for this problem?

title: Piezo buzzer not sounding well with ATmega328

Answers: 2

body:
Some buzzers are active buzzers and will self oscillate when powered.
Other buzzers requires an oscillating signal on their pins in order to make a sound.  If the buzzer works on 5v then its an active buzzer and you only need to feed it a HIGH signal to make it work. Don't try to feed it a 100hz square wave.

body:
If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.

Here is an example how to drive a buzzer using a transistor:
https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial


body:
When I started connecting my Arduino Uno for first project: LED to pin 13, resistor, breadboard, USB connected to Windows Laptop, the orange on-board LED flashes every second and the LED on the breadboard did the same.
What program is driving this?
I had NOT uploaded any program.
Please explain.

title: First Start Arduino Uno

Answers: 1

body:
It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.

Typically it's the Arduino Blink sketch which can be found here:

https://www.arduino.cc/en/Tutorial/Blink

Which has the following (functional) content:

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }


body:
Please help with this error.
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

Sketch uses 882 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM4": Access is denied.

Windows 10 Pro
Arduino UNO ATmeg 328P-PU
Have never been able to Upload a sketch.
Pin 13 and Orange LED blink at 1 second

title: Arduino Uno First Program

Answers: 1

body:
Welcome to the Stack Exchange and on the Arduino World.

Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).

When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.

To program it, you need to know which COM port is created for your Arduino module:

 - Press WIN-'R' (execute application)
 - Write `devmgmt.msc`

Check the COM port to see wich COM port was used for your Arduino.

This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.


body:
I am currently facing a problem with Serial communication with my arduino MEGA 2560.

My project is to collect data from an encoder. There are 2 signals : ACP and ARP. For 1 rotation, there are 16 384 ACPs (counter) and 1 ARP (reference).
I have to store the high level and length of EACH ACP and if there is an ARP. To receive these signals I created a little PCB with a dual line receiver (because At the output of the encoder I revceive differential signals).

To store these data, I use a buffer of bytes. I need 3 bytes to store both ACP length and high and 1 ARP (I store the data in an ISR, see code below) :

<!-- language-all: lang-c++ -->

    buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
    i++;
    buff1[i] = char(acpHigh);
    i++;
    buff1[i] = char(acpPeriod);
    i++;

I use 2 circular buffers (when 1 is filled, I start wrinting into the other). As there are different speed rotation, the fastest one is 15 RPM (rotation per minute) so 1 ACP signal (1 period) last for 244 us and 4 s are needed for 1 rotation.

To collect the data, I directly use :

`Serial.write(buff1, sizeof(buff1));`

Here is the code I am using :

    #include <eRCaGuy_Timer2_Counter.h> //To use timer in ISRs

    //Constants
    #define NO_DEFAULT_LED_PIN            40
    #define DEFAULT_LED_PIN               42
    #define WRITE_LED_PIN                 44
    #define REC_IN_PROGRESS_LED_PIN       50
    #define ACP_LED                       46
    #define ARP_LED                       48
    #define ACP_PIN                       20
    #define ARP_PIN                       21
    #define STOP_REC_BUTTON_PIN           28

    #define SIZE                          800
    #define BAUDSPEED                     230400

    //Variables
    boolean recordingEnded = false;
    volatile boolean writing = false;
    volatile unsigned short arpNbr = 0;
    volatile unsigned short acpHigh = 0;
    volatile unsigned short acpPeriod = 0;
    volatile int i = 0;
    volatile bool change_buffer = 0;

    char buff1[3 * SIZE];
    char buff2[3 * SIZE];

    //Variables for interruption routines
    volatile unsigned long acpHighUs = 0UL; volatile unsigned long acpPeriodUs0 = 0UL; volatile unsigned long acpPeriodUs1 = 0UL;

    /**************************************************************************************/
    /* Initialization                                                                     */
    /**************************************************************************************/
    void setup()
    {
      Serial.begin(BAUDSPEED);

      //Setup LED pins
      pinMode(DEFAULT_LED_PIN, OUTPUT);
      pinMode(NO_DEFAULT_LED_PIN, OUTPUT);
      pinMode(SD_WRITE_LED_PIN, OUTPUT);
      pinMode(REC_IN_PROGRESS_LED_PIN, OUTPUT);
      pinMode(ACP_LED, OUTPUT);
      pinMode(ARP_LED, OUTPUT);

      //Setup ACP and ARP inputs
      pinMode(ACP_PIN, INPUT_PULLUP);
      pinMode(ARP_PIN, INPUT_PULLUP);

      //Setup the button
      pinMode(STOP_REC_BUTTON_PIN, INPUT_PULLUP);

      //Light ALL LEDs during initialisation
      digitalWrite(DEFAULT_LED_PIN, HIGH);
      digitalWrite(NO_DEFAULT_LED_PIN, HIGH);
      digitalWrite(SD_WRITE_LED_PIN, HIGH);
      digitalWrite(REC_IN_PROGRESS_LED_PIN, HIGH);
      digitalWrite(ACP_LED, HIGH);
      digitalWrite(ARP_LED, HIGH);
      delay(500);

      //Setup the timer
      timer2.setup();

      //Setup is done
      digitalWrite(NO_DEFAULT_LED_PIN, LOW);
      digitalWrite(SD_WRITE_LED_PIN, LOW);
      digitalWrite(ACP_LED, LOW);
      digitalWrite(ARP_LED, LOW);

      //Attach interruption at the end of the initialisation (recording starts...)
      attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
      attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
    }

    /**************************************************************************************/
    /* Main loop                                                                          */
    /**************************************************************************************/
    void loop()
    {
      //Check if the user stops the recording
      if (digitalRead(STOP_REC_BUTTON_PIN) == LOW && !recordingEnded )
      {
        noInterrupts();
        delay(500);

        //Switch off the recording LED
        digitalWrite(SD_WRITE_LED_PIN, LOW);
        digitalWrite(REC_IN_PROGRESS_LED_PIN, LOW);
        digitalWrite(ACP_LED, LOW);
        digitalWrite(ARP_LED, LOW);

        return;
      }

      //Check if the writing should be done
      if (writing && !recordingEnded)
      {
        digitalWrite(WRITE_LED_PIN, HIGH);

        if (change_buffer) {
           Serial.write(buff1, sizeof(buff1));
        }
        else {
           Serial.write(buff2, sizeof(buff2));
        }

        digitalWrite(WRITE_LED_PIN, LOW);
        writing = false;
      }
    }

    /**************************************************************************************/
    /* This method is called at the beginning of each ACP.                                */
    /**************************************************************************************/
    void acpRising()
    {
      digitalWrite(ACP_LED, HIGH);
      acpHighUs = timer2.get_count();
      acpPeriodUs1 = timer2.get_count() / 2 - acpPeriodUs0;
      acpPeriodUs0 = timer2.get_count() / 2;

      acpPeriod = acpPeriodUs1;

      attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpFalling, FALLING);
    }

    /**************************************************************************************/
    /* This method is called at the end of each ACP.                                      */
    /**************************************************************************************/
    void acpFalling()
    {
      digitalWrite(ACP_LED, LOW);
      acpHighUs = (timer2.get_count() - acpHighUs) / 2;
      acpHigh = (unsigned short)acpHighUs;

      if (change_buffer) {
        buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
        i++;
        buff1[i] = char(acpHigh & 0xFF);
        i++;
        buff1[i] = char(acpPeriod & 0xFF);
        i++;

      }
      else  {
        buff2[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
        i++;
        buff2[i] = char(acpHigh & 0xFF);
        i++;
        buff2[i] = char(acpPeriod & 0xFF);
        i++;
      }

      arpNbr = 0;

      if (i == 3 * SIZE) {
        i = 0;
        change_buffer = !change_buffer;
        writing = true;
      }

      attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
    }

    /**************************************************************************************/
    /* This method is called at the beginning of each ARP.                                */
    /**************************************************************************************/
    void arpRising()
    {
      digitalWrite(ARP_LED, HIGH);
      arpNbr = 1;

      attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpFalling, FALLING);
    }

    /**************************************************************************************/
    /* This method is called at the end of each ARP.                                */
    /**************************************************************************************/
    void arpFalling() {
      digitalWrite(ARP_LED, LOW);
      attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
    }

#Problem :

I use CoolTerm software to collect my data into a .txt file and analyse it with Hexed.it.

It seems like after a certain period, like 6-10 minutes, I loose a part of 1 buffer. I checked this beacause as I wrote above, I need 3 bytes for information and in Hexed.it, I saw that I had only 2 bytes at once, and after, data was correct.

After analysing in depth, I saw that there was a part of a buffer and a few more (1-2) which were missing. I managed to see this because there was not 16384x3 bytes between 2 ARP (reference signal of the encoder).

I checked all timings to see if I sent the buffer before it was filled but everything is fine...

I also tried other methods like :

- Writing on a SD card;

- Changing buffer size;

- Changing baudrate;

- Using polling method instead of ISRs.

But nothing concluant ...

#EDIT:
It seems like my problem came from CoolTerm software after correcting my code. I now use RealTerm and I made a 1 night recording duration and every seems to be perfect. I don't have any data lost.

title: Missing buffers with serial communication

Answers: 1

body:
Not a direct answer to your questions, but after reading your code I
would like to give some comments:

1. You are not using “circular buffers”, you are [double-buffering][].
   If you used a [circular buffer][], you would not need two of them.
2. `recordingEnded` is always `false` and thus serves no purpose.
3. When `writing` and `change_buffer` are both true, you should transmit
   `buff2`, not `buff1`, as the ISR is now filling `buff1`.
4. There are too many globals. Variables that are used in a single
   function should be local to the function. If you need the value to be
   preserved between calls, qualify the variable as `static`.
5. The code that fills the buffers would be clearer, IMO, if you avoided
   the repetition. E.g.
   ```c++
   char *buff = change_buffer ? buff1 : buff2;
   buff[i++] = (arpNbr << 7) | (acpPeriod >> 8);
   buff[i++] = acpHigh & 0xFF;
   buff[i++] = acpPeriod & 0xFF;
   ```
   Note that `buf[i++]` is idiomatic C/C++.

Now, regarding your specific question, you mentioned in a comment that
“_there were not 3x16384 bytes between 2 ARP_”. This may well be a
consequence of issue 3: you are not sending the bytes in the correct
order, as at times (when `Serial.write()` runs ahead of the ISR) you may
be sending old data.

----

**Edit**: to answer the comment

> `char *buff = change_buffer ? buff1 : buff2;` won't take useless time?

Not really. Testing `change_buffer` is something you have to do either
way. Assigning the buffer address to a local pointer is also done, under
the hood, by the compiler. In the _best case_, it optimizes your code to
something like:

```c++
register char *Z;
if (change_buffer)
  Z = buff1 + i;
else
  Z = buff2 + i;
Z[0] = (arpNbr << 7) | (acpPeriod >> 8);
Z[1] = acpHigh & 0xFF;
Z[2] = acpPeriod & 0xFF;
i += 3;
```

Using an explicit `buff` pointer gives a similar result, as the compiler
will allocate this to the CPU's Z register. Actually, you may get
shorter code, as the compiler may not entirely factor out the
repetition.

[double-buffering]: https://en.wikipedia.org/wiki/Multiple_buffering
[circular buffer]: https://en.wikipedia.org/wiki/Circular_buffer


body:
So I work for a department that uses arduino to move a stepper motor for a wave machine and I am encountering a issue.  They gave me the code that they used to use but it doesn't move the motor and just makes this intermittent beeping noise.

My code is as follows:

    int pulse_delay = 20;
    int wave_period = 1000;

    void setup() {
    pinMode(8,OUTPUT);
    pinMode(9,OUTPUT);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    }

    void loop() {
    digitalWrite(9,HIGH);
    delay(10000);
    for (int i=0;i<wave_period;i++)
    {
      digitalWrite(8,HIGH);
      delayMicroseconds(pulse_delay);
      digitalWrite(8,LOW);
      delayMicroseconds(pulse_delay);
    }
    digitalWrite(9,LOW);
    for (int i=0;i<wave_period;i++)
    {
      digitalWrite(8,HIGH);
      delayMicroseconds(pulse_delay);
      digitalWrite(8,LOW);
      delayMicroseconds(pulse_delay);
      }
    }

I do not receive any error messages and the IDE just says upload complete.  We use a Arduino Mega board. I am pretty new to Arduino.

Edit:
Someone asked for pictures about how it was connected.  Sorry for the late response, had a family emergency.

[![The cable coming in from the bottom is the stepper motor cable][1]][1]

[![picture of whole board][2]][2]

The cable coming in from the bottom of first picture is from the stepper motor, as is the cable I'm holding but that is what I was told isn't necessary.

  [1]: https://i.stack.imgur.com/B74oD.jpg
  [2]: https://i.stack.imgur.com/QI4c2.jpg

title: stepper motor doesn't work but get no error message

Answers: 2

body:
What are 8 and 9 plugged into on your stepper?
also define your baud rate based on the motor requirements.

```

void setup() {
pinMode(8,OUTPUT); < should be PUL
pinMode(9,OUTPUT); < should be ENA(maybe dir)
digitalWrite(8,LOW);
digitalWrite(9,LOW);
Serial.begin(115200);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
}
digitalWrite(9,LOW);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
  }
}
```

body:
[Here](https://www.orientalmotor.com/products/pdfs/opmanuals/HM-60128-8E.pdf) you can find the manual of your stepper driver.

Look at page in the section "CN3 (I/O signals)". Beside the pulse and directions, that you already set in your code, there are 2 more input signals defined: AWO will turn off the motor completely, if you provide a signal, CS changes the source of the step angle setting. As you don't configure any pins, other than pulse and direction, the other pins on the Arduino are set as input/high impedance. The state of these pins can float wildly depending on what noise is comming by. I don't know, if this really matters for this driver, but you should try to provide a valid state on all the input pins of the driver. For example a floating AWO pin might randomly disable and enable your motor very fast (which would at least fit with the described behavior). Set the corresponding pin on the Arduino as output (via `pinMode()`) and give them the state, that you want via `digitalWrite()` (I suggest LOW for AWO to enable the motors and HIGH for CS to get the basic step angle).

I cannot see on your images, if everything is connected to the driver, as it should (here a wiring diagram or a schematic would help). For now I assume, that the signal pins on the Arduino side are connected correctly.

The input signals of the driver are meant to be provided by a pair of twisted wires. This is done to minimize noise on the line. Thus all input signals have 2 pins: "+" and "-". Connect all "-" pins to ground and the "+" pins to the appropriate digital output pin on the Arduino.

If a have a oscilloscope or a logic analyzer, you can also monitor the ALM and TIM outputs of the driver. Maybe they are showing, what is going wrong.

Let us know, if this helps.


body:
Does somebody know which is the maximum serial speed one can achieve by using the Microchip SAM3X8E microprocessor with Serial Communication between other uC with a RS485 module?

The Arduino Due seems to be limited up to 115kbps, the USB (UOTGHS) should reach 1.5Mbps (low speed) without trouble, but I am not sure about the UART

From [Microchip SAM3X8E Datasheet][1] section 34.5.1 Baud Rate Generator, the UART baud rate should be the Master Clock MCK divided by 16, the maximum value given by setting the clock divisor UART_BRGR to 1, the minimum value after 0 (UART disabled).

Hence the Master Clock MCK should be around 84MHz (its Maximum Possible Clock?), and then the Maximum Baud Rate should be 5.25Mbps?

Is this right?

Thanks in advance

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

title: SAM3X8E Maximum Serial Speed

Answers: 0


body:
Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).

My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.

So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.

example:

    int sensor = 26;
    int PUL = 23; //define Pulse pin
    int DIR = 25; //define Direction pin

    void setup() {
      pinMode(sensor, INPUT);
      Serial.begin(115200);
      pinMode (PUL, OUTPUT);
      pinMode (DIR, OUTPUT);
    }

    void loop() {
      int sen = digitalRead(sensor);
      if (sen == HIGH) {
        Serial.println("HIGH");
        delay(1000);
         for (int i=0; i<500; i++)
      {
          for( int x=0; x<255; x++){

        digitalWrite(DIR,LOW);
        digitalWrite(PUL,HIGH);
        Serial.print("i = ");
        Serial.println(i);
        Serial.print("x = ");
        Serial.println(x);
        delayMicroseconds(x);
        digitalWrite(PUL,LOW);
        delayMicroseconds(x);
      }}
      } else if (sen == LOW) {
        Serial.println("LOW");
        delay(1000);
        } else {
        Serial.println("ERROR");
      }
    }

**EDIT**

I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255

    for (int i=0; i<500; i++) {
      for( int x=0; x<255; x++){
      digitalWrite(DIR,LOW);
      digitalWrite(PUL,HIGH);
      Serial.print("i = ");
      Serial.println(i);
      Serial.print("x = ");
      Serial.println(x);
      delayMicroseconds(x);
      digitalWrite(PUL,LOW);
      delayMicroseconds(x); }
    }

title: Servo Program Questions

Answers: 1

body:
Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?

this should do what you want. i and x increase together until x reaches 255 then it wont increment.

```C
int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}
```


body: Can an Arduino power a USB device like a tablet from one of it's pins or do I need a relay? I want to essentially have the Arduino turn on and off a USB charger. Thanks

title: USB Power switch

Answers: 1

body:
If you already have a 5V source then you can use a MOSFET as a switch to turn on/off the power to the tablet like this:
[![enter image description here][1]][1]

But if you want to turn on/off a USB charger that goes to an AC outlet, then you will need to control a relay to turn on/off the AC supply to the USB charger. You can use a relay module like this: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/hPrtH.png

  [2]: https://i.stack.imgur.com/FEgKt.png


body:
Suppose that one defined a data structure and wanted to send it through serial.

     struct Gyro_data_structure {
        char command_name[5];
        float gyro_X;
        float gyro_Y;
        float gyro_Z;
    };

    Gyro_data_structure Gyro_data;

    int size_gyro=sizeof(struct Gyro_data_structure);

    void setup() {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      Gyro_data.command_name[0]='H';
      Gyro_data.gyro_X++;
      Serial.println(size_gyro);
      delay(500);
      Serial.write(Gyro_data,size_gyro);
    }

However, it returned an error saying "no matching function for call to 'HardwareSerial:write(Gyro_data_structure&,int&)'". I googled and found Michaël Roy's answer [here][1]. However, it's not working: "can not convert ..."

How to send a structure through UART?

  [1]: https://stackoverflow.com/questions/45600202/arduino-how-to-feed-a-struct-from-a-serial-read

title: Send structure through Serial

Answers: 2

body:
I tried the code from the link you posted and it worked:

    struct Gyro_data_structure
    {
        char command_name[6];
        int gyro_X;
        int gyro_Y;
        int gyro_Z;
    };

    struct Gyro_data_structure Gyro_data = {"Hello", 48, 49 , 50};

    int size_gyro = sizeof(struct Gyro_data_structure);

    void setup()
    {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
    }

    void loop()
    {
      send(&Gyro_data);
      Serial.println();
      delay(1000);
    }

    void send (const Gyro_data_structure* table)
    {
      Serial.write((const char*)table, size_gyro);  // 2 bytes.
    }

    bool receive(Gyro_data_structure* table)
    {
      return (Serial.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
    }

I changed the **float** type to **int** for easy representation. When you run the code the serial window will show: **Hello012**

Because Arduino IDE serial window shows ASCII characters. 0's ASCII value is 48 and so on.

Update

It depends on what you want from the read function. Let's break down what Michaël Roy's implementation is doing. First, he reads **sizeof(Gyro_data_structure)** number of serial bytes and put it in the variable that table points to:

    Serial.readBytes((char*)table, sizeof(Gyro_data_structure))
The 2nd argument of readBytes() takes how many bytes you want to read. Also readBytes() return how many bytes it read. Let's say we stored that number in **return_bytes**. In the next part he did:

    return (return_bytes == sizeof(Gyro_data_structure))

He is checking if the number of bytes readBytes() read is the same as the size of  **Gyro_data_structure**. If it is not, then return **false**.

This just tells you if you read more or less than what you are supposed to read. Regardless of true or false, the actual bytes that were read will be in the variable that you passed to the receive() function.

If you don't want the function to not return anything this is how it should be:

    void receive(Gyro_data_structure* table)
    {
      Serial.readBytes((char*)table, sizeof(Gyro_data_structure));
    }

body:
First of all, you have to decide whether you want to send the data as
raw bytes (“binary data”) or as an ASCII text representation. Binary
tends to be more efficient: you can send a `float` with _full precision_
in only four bytes, whereas you would typically need 8 to 9 significant
digits to recover the full precision from an ASCII representation.
Binary is, however, harder to handle: some types have different binary
representations on your Arduino and your PC, and you may need to define
a protocol of sorts in order to get the framing right. ASCII is easier,
and you can usually use end-of-lines as a simple framing device. I
generally recommend using ASCII unless you _really_ need the extra
efficiency of a binary protocol.

## Sending as binary

You can easily send arbitrary binary data using the method
`write(const uint8_t *buffer, size_t size)` from the `Serial` object:

```c++
Gyro_data_structure Gyro_data = {"Gyro", 0.0, 4.0, 5.0};

void loop() {
    Gyro_data.gyro_X++;
    Serial.write((uint8_t *) &Gyro_data, sizeof Gyro_data);
    delay(200);
}
```

Here is an hex dump of the output:

```text
0000  47 79 72 6f 00 00 00 80  3f 00 00 80 40 00 00 a0  |Gyro....?...@...|
0010  40 47 79 72 6f 00 00 00  00 40 00 00 80 40 00 00  |@Gyro....@...@..|
[...]
```

which can be parsed as follows:

```text
47 79 72 6f 00 = {'G', 'y', 'r', 'o', '\0'}
00 00 80 3f    = 0x3f800000 = 1.0f
00 00 80 40    = 0x40800000 = 4.0f
00 00 a0 40    = 0x40a00000 = 5.0f
```

Note that the floats are sent in little-endian order: lest significant
byte first. The 32-bit hex numbers above are the binary representations
of the floats.

## Sending as text

`Serial.print()` is intended to print a text representation of the data
you give it. But since it does not know how to represent a
`Gyro_data_structure`, you have to `Serial.print()` each data member in
turn, and then add some formatting around all that:

```c++
void print_gyro(const Gyro_data_structure &gyro) {
    Serial.print(F("Gyro{command = \""));
    Serial.print(gyro.command_name);
    Serial.print(F("\", X = "));
    Serial.print(gyro.gyro_X);
    Serial.print(F(", Y = "));
    Serial.print(gyro.gyro_Y);
    Serial.print(F(", Z = "));
    Serial.print(gyro.gyro_Z);
    Serial.print(F("}"));
}

void loop() {
    Gyro_data.gyro_X++;
    print_gyro(Gyro_data);
    Serial.println();
    delay(200);
}
```

The output is

```text
Gyro{command = "Gyro", X = 1.00, Y = 4.00, Z = 5.00}
Gyro{command = "Gyro", X = 2.00, Y = 4.00, Z = 5.00}
[...]
```

## Making your data printable

This is a variation on the previous technique. You can `Serial.print()`
your object directly, if you tell the Arduino core how to print this
type of objects. This is done by letting your class inherit from
`Printable` and implementing the virtual method `printTo()`. But then
the class is not an “aggregate” anymore, and thus needs an explicit
constructor:

```c++
struct Gyro_data_structure : Printable
{
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
    Gyro_data_structure(const char *name, float x, float y, float z)
    : gyro_X(x), gyro_Y(y), gyro_Z(z) {
        strncpy(command_name, name, 4);
        command_name[4] = '\0';
    }
    size_t printTo(Print& p) const {
        size_t count = 0;
        count += p.print(F("Gyro{command = \""));
        count += p.print(command_name);
        count += p.print(F("\", X = "));
        count += p.print(gyro_X);
        count += p.print(F(", Y = "));
        count += p.print(gyro_Y);
        count += p.print(F(", Z = "));
        count += p.print(gyro_Z);
        count += p.print(F("}"));
        return count;
    }
};

Gyro_data_structure Gyro_data("Gyro", 0.0, 5.0, 5.0);

void loop() {
    Gyro_data.gyro_X++;
    Serial.println(Gyro_data);
    delay(200);
}
```

The output is identical as before. The definition of the class gets a
little bit clumsier, but then you can very easily print to any serial
port (be it an UART or a software implementation), to an LCD... or
whatever understands `print()`.


body:
I have a servo motor That I am trying to determine the delay speed in between pulses with a nested for loop. This issue is instead of running together like 0,0 1,1 2,2 its actually going up like 0,0 0,1 0,2. SO the first for loop i will only go up once all of the x for loop goes to its max 255.

What I want it to do is go up together until x reaches 255 and then it will stabilize there as I will countering to climb.

If any know anything about nested for loop I would appreciated (please only add valuable comment or help to this. I don't need pointless or dumb comments (talking about  jsotola and all he did was criticized my question)

```
 for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
```

title: Nested For Loop Controlling speed

Answers: 1

body:
These are nested loops:

```c++
for (int i = 0; i < 500; i++) {
    for (int x = 0; x < 255; x++) {
        do_something_with(i, x);
    }
}
```

“Nested loops” means you have a loop within a loop: within each
iteration of the outer loop you get a full run of the inner loop. The
sequence of (i, x) pairs is:

```text
(0, 0), (0, 1), (0, 2), ... (0, 254)
(1, 0), (1, 1), (1, 2), ... (1, 254)
...
(499, 0), (499, 1), ...     (499, 254)
```

> What I want it to do is go up together until x reaches 255 and then it
> will stabilize there as I will countering to climb.

This sentence is not very clear. I assume you mean that you want the
following sequence of (i, x) pairs:

```text
(0, 0), (1, 1), (2, 2), ... (255, 255),
(256, 255), (257, 255), ... (499, 255)
```

If this is what you want, you can more easily achieve it with a single
loop:

```c++
for (int i = 0; i < 500; i++) {
    int x = min(i, 255);
    do_something_with(i, x);
}
```


body:
Hello I am currently doing a project at my university which requires me to order and program 4 motors using an arduino. I will be using an arduino uno and an adafruit motor shield. 2 of the dc motors will have an encoder for better motor control. While connecting the linear and one of the dc motors shouldn't be difficult, I am wondering how can I connect the two motors with encoders.
I was thinking to connect 1 dc motor and the stepper onto one shield and the encoder motors onto another since the shields can stack. Is this option possible or should I use some other method? I am fairly new to arduino and only had a little bit of experience with coding so any help and suggestions are welcome.

title: Using arduino uno and an adafruit shield to control 3 dc motors and a linear stepper motor

Answers: 0


body:
I have a piece of code as shown, and I wish to print the value I send using serial monitor along with a message: "Writing data to slave...".

![enter image description here](https://i.stack.imgur.com/dfiXB.jpg)

But everytime I enter a character/number in the serial monitor(like 'a' as shown), the loop runs two times instead of just once. It seems like an extra character(somewhat invisible or null) is being sent along with the typed character.

![enter image description here](https://i.stack.imgur.com/QdYLC.jpg)

If I use the condition (Serial.available()>1)  then the loop runs just once on sending one character.

Why is this so?

title: Problem with Input from Serial Monitor

Answers: 1

body:
I suspect an end of line character is send (probably \n or \r, see comment of Edgar Bonet), or an end of string (0 character).

You can easily find it out by printing the integer value of the character:

    char c = serial.read();
    Serial.print((int) c);


body: My project is to receive data from Bluetooth (HC-05) sensor and storing it in the database. I have successfully received data from Bluetooth sensor and stored it in a String variable. Now i have to store this data to the database. I want to use the sensors as standalone (not connecting to the PC - operated on battery). Can I store the data to the database using ESP8266.

title: Send Arduino data to Database using ESP8266

Answers: 1

body:
Since you mention you operate on a battery (standalone), what exactly do you mean by "the database"? Do you have online connectivity? Do you have any peripherals like an sdcard or other storage?

In case you don't have a permanent online connection, you would need to use some writable memory (like [EEPROM](https://en.wikipedia.org/wiki/EEPROM)) to store your data in some [organized form](https://en.wikipedia.org/wiki/Database). Since the ESP8266 doesn't seem to have any EEPROM built in, you would need to use its flash memory, like described in [those answers](https://arduino.stackexchange.com/a/33503/37604).

A database could be as simple as a `fixed length string list` (essentially how [string arrays](https://stackoverflow.com/a/41552922) look in memory). For example if the string data you want to save always has 32 bytes, you could just divide your available storage (e.g. 4096 bytes) to have a "database" wich can store 128 entries (4096/32). Your "database entries" will then be addressable in multiples of 32, you would find the 1st entry at byte 0, the 2nd at byte 32 and so on.

Once you are online, you could send the data out for further processing. Getting the data [into a database](https://www.instructables.com/id/Firebase-Integrate-With-ESP8266/) can be as simple as a [https request](https://firebase.google.com/docs/reference/rest/database).


body: I mistakenly connected a 7.4V battery backwards to an Arduino Nano via the Vin pin. The Arduino still works (I can upload code) connecting it to the PC using the USB cable. Here's my question: will the Arduino deteriorate using this method or can I continue using it (I'm soon going to buy a new voltage regulator)?

title: Does the Arduino deteriorate after shorting the voltage regulator?

Answers: 1

body:
Of course, if you can upload the code, you can continue to use it ;)

Even if the Arduino is cheap, it is really reliable. There are always some short circuit protections.

The Voltage Regulator (I think it is a simple LM1117) has a overcurrent protection too (see: http://www.ti.com/lit/ds/symlink/lm1117.pdf)

So, don't worry. You can continue, continue and continue to use it...

Edit: just a note: never drain more than 50mA on an output. This will destroy the pin on your Arduino.


body:
I am working on a small piece of code as shown:
[![enter image description here][1]][1]

When I enter character 'a' in the Serial Monitor and use a delay in between successive reads then the monitor gives out acceptable results(i.e 97 for character 'a' and 10 for new line) as shown:
[![enter image description here][2]][2]

Whereas if I do not include the delay, it seems like the microcontroller is not able to read the next value(i.e 10 for new line) immediately and just gives out a -1. And it is only after the loop is run again that we get to see the value 10 for new line(again with -1).

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/ZxfJs.jpg
  [2]: https://i.stack.imgur.com/FQChX.jpg
  [3]: https://i.stack.imgur.com/trOpK.jpg

Is my observation correct? If yes, what causes this to occur?

EDIT: I am sorry for the improper format of displaying the code. I am adding the code as below:

~~~
#include <Wire.h>

void setup() {

  // Initialize I2C communications as Master
  Wire.begin();
  // Setup serial monitor
  Serial.begin(9600);
  Serial.println("I2C Master Demonstration");
}

void loop() {

  if(Serial.available()>0)
  {
    char c = Serial.read();
    Serial.print((int)c);
    delay(10);
    char d=Serial.read();
    Serial.print((int)d);
    Serial.println("Writing data to slave...");
}
}
~~~

title: Serial monitor read value depending on delay

Answers: 1

body:
Yes, UART is much slower then the CPU and you run it on extremely slow baud rate. The CPU runs many loops before Serial.available() is again more then 0.

From [reference of read() function][1]:
> Returns the first byte of incoming serial data available (or -1 if no data is available).

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/


body:
i have a sketch that is using very memory RAM of my Atmega2560 (is a giant project), and i need use various "println" because i have a TFT screen and i need to show data on the screen to user see. So, i'm using macro F() to use less RAM memory (example: Serial.println("Hi Naruto-kun") to Serial.println(**F(**"Hi Naruto-kun"**)**). But, it only work if the data entered in F() were to Const String, when i need, by example, show a array of integers, nothing work.

Example:

``` c++
tft.print(F(mediaTotPg[1]));

```

This do not work because mediaTotPg is a Integer Array and the errors returned are:

" **#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))** "

Finally, is possible show integers not const with Macro F()?

title: Is possible use Macro F() with Integer and Other types of variable?

Answers: 2

body:
For a constant array of integers you need to use PROGMEM and the various `pgm_read_*()` functions.

You can read more, and find examples, on the [Arduino PROGMEM](https://www.arduino.cc/reference/tr/language/variables/utilities/progmem/) manual page.

body:
`F()` puts the constant string literal in the flash part of your device. This way it does not use the RAM space otherwise needed.

But your `mediaTotPg` array is most probably (you didn't say anything about it) a non-`const` variable, and can't be put in flash memory.

If the values to be shown are in fact `const`, you need to put them in the flash memory. As [Majenko's answer][1] points out in short, you need to use the PROGMEM section for the values, as described on the [Arduino PROGMEM page][2].

The answer to your question is: **No, it is not possible to use the macro `F()` with *any type* of variable that is not `const`, and it is not possible to use it for *any other type* than a string literal.**

  [1]: https://arduino.stackexchange.com/a/72159/60431
  [2]: https://www.arduino.cc/reference/tr/language/variables/utilities/progmem/


body:
The issue that I have is in INT0 service in which it doesn't perform properly when MCU is set in PowerDown mode. I declared a global variable as "*counter*" and put it inside INT0 ISR but its value doesn't change.

To make sure that the issue is coming from the Sleeping of the MCU, I commented-out "*sleepNow();*" inside *Loop()*, at line 156, and un-commented the following 3 lines and everything was working as expected and variable "*counter*" was changing correctly. I think I haven't constructed the sleeping part properly, which has caused this issue. I tried to play with the code and searched Google, but I couldn't find that much help. I also looked at the following topics, but those didn't help me either:

https://arduino.stackexchange.com/questions/31582/waking-up-async-the-arduino-while-its-sleeping-periodically/31589#31589

https://arduino.stackexchange.com/questions/54846/send-out-a-short-signal-every-10-seconds-to-an-arduino/54848#54848

https://arduino.stackexchange.com/questions/54830/use-lowpower-libary-and-still-use-serial-connection-and-other-things/54831#54831

https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969

My simplified code is here:

    #include <SoftwareSerial.h>
    #include <avr/sleep.h>
    #include <avr/wdt.h>
    #include <avr/power.h>

    #define Voltage A7                 // Analog Pin A7 | ADC7 - QFN pin 22
    #define En_V A0                  // Analog Pin A0 - PC0 -QFN pin 23 | Trigger pin to turn on MOSFETs
    #define En_Sensors 9             // Digital Pin D9 - PB1 -QFN pin 13 | Trigger pin to turn on sensor
    #define En_I2C2 3
    #define En_Sigfox A1       // GPIO9 On Sigfox - It is Set to PULL UP by default in Sigfox module. Set to LOW for waking up

    #define SF_rxPin 5     //Sigfox
    #define SF_txPin 6     //Sigfox

    boolean debug =  true;
    SoftwareSerial Sigfox (SF_rxPin, SF_txPin);

    ///////////////////////Interrupt changes////
    const int interruptPin = 2; // INT0 - PD2 | INT1 - PD3
    const uint8_t LED = A2;
    volatile uint8_t counter = 0;
    volatile bool IntFlag = false;
    volatile bool WdtFlag = false;
    ////////////////////////////////////////////
    uint8_t MCU_Sleep_Cycle = 4;

    void wakeUp()
    {
        sleep_disable();
        detachInterrupt(0);// INT0 - PD2 | INT1 - PD3
        counter++;
        IntFlag = true;
    }

    ISR (WDT_vect)
    {
      // WDIE & WDIF is cleared in hardware upon entering this ISR
      wdt_disable();
      WdtFlag = true;
    }

    void Sleep_Sigfox() {
      digitalWrite(En_Sigfox, HIGH);     // to go into DeepSleep mode
      setPowerMode(2);
    }

    void setup() {
      pinMode(Voltage, INPUT);
      pinMode(En_V, OUTPUT);
      pinMode(En_Sensors, OUTPUT);
      pinMode(En_I2C2, OUTPUT);
      pinMode(SF_rxPin, INPUT);
      pinMode(SF_txPin, OUTPUT);
      pinMode(En_Sigfox, OUTPUT);

      pinMode(interruptPin, INPUT_PULLUP);

      if (debug) {
        Serial.begin(9600);
      }
      Sigfox.begin(9600);
      delay(3 * 500);
      analogReference(EXTERNAL);
      digitalWrite(En_I2C2, LOW);
      if (debug) {
        Serial.println(F("Hello"));
      }

      digitalWrite(En_Sensors, LOW);
      Sleep_Sigfox();
      delay(2 * 1000);

      attachInterrupt(0, wakeUp, LOW);
    }

    uint8_t volt() {
      uint16_t tmp = 0;
      float v1, tmp2, tmp3;
      uint8_t v;
      delay(2 * 100);
      tmp = analogRead(Voltage); //A7
      if (tmp > 0) {
        v1 = tmp * 3.3 / 1023;
        tmp2 = v1 * 840 / 33; //10*(51+33)/33;  to represent in 10*V, (51+33)/33 is a HW Voltage divider.
        tmp3 = round(tmp2);
        v = tmp3;
      }
      else {
        v = 0;
      }
      return (v);
    }

    void loop() {
      //delay(2 * 500);

      if (WdtFlag) {
        wdt_reset();

        if (debug) {
          Serial.println(F("\nI woke up"));
          //Serial.print("IntFlag: ");
          //Serial.println(IntFlag);
          Serial.print(F("WdtFlag: "));
          Serial.println(WdtFlag);
          Serial.print(F("counter: "));
          Serial.println(counter);
          delay(500);
        }

        uint8_t rs = 0;
        uint8_t v = 0;
        char to_be_sent[12];
        memset(to_be_sent, 0, sizeof(to_be_sent));
        digitalWrite(En_V, HIGH);

        delay(300);

        v = volt();
        rs = counter;
        sprintf(to_be_sent,  "%2XX", v, rs);
        digitalWrite(En_V, LOW);

        if (debug) {
          Serial.print(F("Volt*10: "));
          Serial.println(v);
          Serial.print(F("RS-count: "));
          Serial.print(rs);
          Serial.println(F("\n"));
          delay(1000);
        }

        ///////////////////////////////// Send Values here
        delay(1 * 50);
        if (debug) {
          Serial.print(F("Sending Message: "));
          Serial.println(to_be_sent);
          delay(20);
        }
        counter = 0;
      }

      if (debug) {

        Serial.print(F("MCU is going into DeepSleep for "));
        Serial.print(MCU_Sleep_Cycle);
        Serial.println(F(" cycles."));
        delay(40);
      }
      for (uint8_t i = 0; i < MCU_Sleep_Cycle ; i++) { //15 cycles = 2min | 6 cycles = 48sec
        if (debug) {
          Serial.print(F("."));
          delay(10);
        }
        sleepNow();
        //WdtFlag=true;
        //attachInterrupt(0, wakeUp, LOW);
        //delay(2*1000);
      }

    }

    String setPowerMode(uint8_t mode) {
      //0: Software reset
      //1: sleep, send a break to wake up
      //2: deep_sleep, toggle GPIO0 or Reset_N to wake up

      if (debug) {
        Serial.print("Sigfox Power mode: " + String(mode) + "\t");
        //Serial.print(res);
        switch (mode) {
          case 0: Serial.println(F("Soft reset is done.\n")); break;
          case 1: Serial.println(F("Module is in sleep mode. zZzZ\n")); break;
          case 2: Serial.println(F("Module is in DeepSleep mode. zZzZ\n")); break;
        }
        delay(500);
      }

      Sigfox.print("AT$P=");
      Sigfox.print(mode);
      Sigfox.print("\r");
      //String res = getData();
      //return res;
    }

    void sleepNow() {
      //cli();   //disable interrupts
      EIFR |= (1 << INTF0); // Clearing INTF0 by setting this bit up. Int0 flag cleared.
      EIMSK |= (1 << INT0); //enable INT0

      byte adcsra_save = ADCSRA; //ADC backup
      byte WDTCSR_save = WDTCSR; //WDT backup

      WdtFlag = false;
      IntFlag = false;

      sleep_enable();          // enables the sleep bit in the mcucr register. so sleep is possible. just a safety pin
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
      ADCSRA &= ~(1 << 7); //clear bit 7 of register ADCSRA and disable ADC
      sleep_bod_disable();
      //power_all_disable ();   // turn off all modules
      sei();//enable interrupts
      attachInterrupt(0, wakeUp, LOW); //when pin 2 gets LOW, run function wakeUp() // INT0 - PD2 | INT1 - PD3
      wdt_enable(WDTO_8S);
      WDTCSR |= (1 << WDIE);
      //sleep_mode();// here the device is actually put to sleep. THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
      sleep_cpu ();

      sleep_disable();
      //power_all_enable ();   // turn on all modules
      sei();
      ADCSRA |= (1 << 7); //Set bit 7 and Enable ADC
      ADCSRA = adcsra_save;  // Config ADC again as before
    }

**What MCU is used?**

The MCU is an ATMEGA328P running on 3.3V at 8MHz

**What I want to do?**

I would like to put the MCU into deep sleep mode for a fixed period (e.g. 15 minutes, though in the code above I have reduced time to less than a minute), but monitor the number of times the external interrupt is happening. At the end of 15 minutes, when the MCU wakes up, I would like to get the interrupt count total from variable "*counter*", which should have been incremented by the INT0 ISR, once per external interrupt.

**What is the issue?**

The issue is that the variable "*counter*" is not increasing when the MCU is in sleep mode. When the MCU sleeps, the power consumption goes down. The WDT is also working. The interrupt INT0 wakes up the MCU, but value of the counter is not incrementing. I suspect that after the INT0 ISR executes, an MCU reset is happening, reinitializing the "*counter*" variable -- so that might be the reason why *counter* keeps staying at zero.

**What did I do?**

I tried to run the code while the MCU is not sleeping and in that case, variable "*counter*" works well. So, I suspect my sleeping instructions may not be correct. To do this, I commented line 156, *sleepNow();*, and un-commented lines 157-159 at the end of main *void Loop(){}*. Please see attached picture.

**What do I expect?**

I expect that, while MCU is in sleep mode, it can count the number of external interrupts.

**What IDE, compiler and platform am I using?**

Arduino IDE adjusted for board Arduino pro mini 3.3V - Windows 8 64bit

But the board that I have is not a genuine Arduino board. I just use the Arduino IDE adjusted for Arduino pro mini since it has the same settings and compilation is easier for me.

Thanks

title: Problem with counting inside INT0 ISR while in PowerDown

Answers: 0


body:
I want to battery-power my NodeMCU. It will be mostly deep sleeping and waking up every 1-2 minutes.

I've seen the best way to power it with the least wasting of power is through a lithium battery.

So I've bought a 18650 rechargable battery and a MCP1700 LDO which will give me a constant 3.3 V, that will connect straight to the 3.3 V pin and bypass the NodeMCU's regulators, as I understand from [here][1].

My question is: if all of the previous is correct, what will happen when the 18650 battery power fall below the 3.5 V (3.3 V + 0.2 V from MCP1700 dropout)? Will it stop automatically giving power at all? Will it provide less than 3.3 V and will it harm the NodeMCU?

  [1]: https://raw.githubusercontent.com/nodemcu/nodemcu-devkit/master/Documents/NODEMCU_DEVKIT_SCH.png

title: Powering NodeMCU with battery and LDO; what if battery is empty?

Answers: 1

body:
As with any electronics, once you get outside of normal operating parameters, behaviour becomes undefined. It's up to you to avoid that.

The smartest thing to do is to employ a battery protection circuit or some means to shut down the system (or prevent it from waking up from deep sleep) before the voltage drops too low. This will also prevent your battery from damage by overdischarging it.

The ESP's minimum operating voltage according to its datasheet is 3.0V. Below that, behaviour is undefined but you can expect unreliable operation, crashes or even permanent damage. If you're writing to Flash memory when below the minimum voltage, the Flash might become corrupted (including the program the ESP is running).