message:
Why is Toolchain Not Updated with Arduino IDE Install on Mac

I have not been doing any Arduino work for about a year.  The last time I ran the Arduino IDE was in the previous version of MacOS.  Now that I have updated to the latest MacOS Version Catalina (10.15.2) I discovered that the IDE will not compile because the avr-g++ compiler is 32 bit and will not execute on the *now* 64-bit required MacOS.

So I did the obvious thing.  I went to the arduino.cc web site and downloaded the latest version of Arduino IDE thinking that this should solve the problem.  I updated to version 1.8.11 of the IDE but the 32-bit problem persisted.

I finally decided that the IDE was updating (new Arduino IDE app) but that the avr toolchain was not being updated.  To force this update, I deleted the entire avr toolchain from my ~/Library folder.  Now, re-running the IDE is all it took:  It discovered the toolchain missing and re-installed and installed with the correct 64 bit binaries (which were part of the new Arduino App all the time).

Perplexing -- why was the toolchain not updated with the install?  Is it a requirement to delete the existing toolchain before doing a new install of the Arduino App?

body:
The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.

To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.

The content of .arduino15 folder is not changed with IDE update.


sender: user

message:
Powering Arduino and transistors with one power supply > 12V

So say you want to use transistors with your Arduino Nano to power components, which require greater than 12V. If your power supply is more than 12V, is there a way to safely use the same power supply to power the Arduino?

sender: assistant

body:
The voltage regulator (on the Vin pin) is supposed to be provided with 12V at max, since it is not cooled (it is a linear regulator, that dissipates the excess voltage as heat). If you have significantly more, you should at best buy a little switching regulator, to directly get a regulated 5V to feed to the 5V pin of the Arduino (that's what I suggest). Be sure to use a regulator, that can provide the needed current (which also depends on what else you provide over the Arduino).

If you really don't want to use an extra regulator and you don't have much more than 12V (maybe like 15V), you might get away by cooling the voltage regulator on the Arduino. The voltage regulator on a genuine Arduino will go into emergency shutdown, if it overheats, but it will not be damaged easily. Here you could try a bit. But be careful to not stress it too much. The clones from china often have different/cheaper regulators, that will mostly be fried if you overheat them. But they are very cheap.


body:
The recommended input voltage for the Arduino Nano is 7-12 V, the max. 20 V.

So you could use upto 20 V, but this is indeed not advisable.

What you can do, is to use a so-called step down/boost down converter which converts the voltage back to a voltage that your Arduino Nano can (easily) handle. The voltage drop will be changed into heat, but I guess considering you are using a higher voltage power supply, you are not using battery power.

Note: this is only true for some (cheap?) converters, see the comment of DataFiddler below.


body:
If I understand your question you have external devices say lamp, motor, etc. There are several ways of doing it. My preferred way is to use a N-Channel MOSFET where the drain is the output, the source is ground (both the logic and power grounds need to be connected together) and the gate Is connected to the port pin that also has a 10K pull down resistor. You can use the 12V to power the Arduino via Vin as you suggested. Be sure the MOSFET is avalanche rated and will turn on at about 3V or less.

You can do the same thing with an NPN Transistor where the port pin connects to the base with a 300 Ohm resistor (you need to calculate this based on the load), emitter to the connected grounds and the collector is your  output.


message:
Where are the traces connected to RESET-EN leading?

Once again, I am following [this schematic][1], and I am confused as to where RESET-EN connects:

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

This is how I have it mocked up it Fritzing, but I feel like this is incorrect:
[![enter image description here][3]][3]

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

body:
This is the DTR output of the ATmega16u2 which is connected to RESET pin of the ATmega2560 for reset by avrdude over DTR signal before upload of the sketch. There is a trace by default. Cutting the trace disables the auto-reset. Soldering a bridge on  RESET-EN pads re-enables the auto-reset.

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

the schematics part you quoted in question misses the long unconnected line for the RESET label. It leads here:

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

  [1]: https://i.stack.imgur.com/OBgzO.png
  [2]: https://i.stack.imgur.com/pyzDc.png


message:
Is there an Adafruit function to invert the colors of my screen for Arduino language?

I am trying to invert the color of my OLED display screen once a button is pushed. I have the button situation figured out but I can not find a function that inverts the color. I am using these two libraries to handle my screen on the Arduino IDE.

Adafruit_GFX.h, Adafruit_SSD1306.h

Any help would be much appreciated.

body:
There is a function that invert the colors of your screen, you can pick either black on white or white on black, I have tried it and I have quite experience with your display, I think you should try this piece of code.

At the beginning of your Arduino code be sure that you declared the object using the same name.

    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

To invert the display

    display.invertDisplay(true);

To return the display again

    display.invertDisplay(false);

As you said that you want a button to invert the display you might use this code I made

    if(digitalRead(BUTTON_PIN)){
        display.invertDisplay(true);
    }
    else{
        display.invertDisplay(false);
    }

Or you might use **Interrupts** for better performance depending on your code.

As you couldn't find on the internet, I am student and I learn alot from the internet, to for example search for such a function in an Arduino library, try searching it's documentation or it's page on GitHub then afterwards see the function you want through the pages, but don't just search the function directly it will **sometimes** won't work as they are not that popular.

As a last thing [Here][1] is the documents where I got the function with it's parameters from.

I hope I've helped you out. any edits in the answer is well appreciated, as I am a student.

  [1]: https://adafruit.github.io/Adafruit_SSD1306/html/class_adafruit___s_s_d1306.html


message:
Which board has the highest max current via 3.3v pin?

Is there any arduino board which can deliver 600-800ma via 3.3v pin? Maybe the Arduino due or the nano 33 ble?

body:
Your USB will output only 500mA or max to max 1A in some cases. Even if your board is rated for higher output you will be restricted by your source. First step is to increase your source. Secondly check which 3.3V regulator is present on which board and check the datasheet of the regulator to get information about it.
Either ways you can externally add a high current 3.3V regulator and connect it to your 3.3V pin on the arduino. As voltages are equal no current will flow between them.
But remember your source needs to output the higher current first


message:
make servo stay at the current position when attach() is called

I use a small *SG90* servo with arduino.
When I call `attach()` servo moves to its default position or whatever I set with `write()` before it.

I’d like to make servo stay at the current position when I call `attach()` in `setup()`.

How can I achieve it?

I believe I can simply store last position in `EEPROM`. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

body:
You can't read the servo's position, so your sketch has no chance to know the *real current* position.

And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.

So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"

You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.

Some ideas how to "get better":

- Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
- Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
- Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
- Add a circuit that detects the power loss *before the CPU stops*. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.


message:
ESP32 - NTP inaccuracy after deep sleep

I'm trying to create a sensor sampling project using ESP32 ( battery, solar panel and temperature affects are not part of test right now to reduce external effects that may cause/ increase such behaviour ).

In current phase, I'm only testing the sleep & waking up process.

A short description: System wakes up after deep sleep cycle, connects to Wifi, MQTT, NTP - and checks if wake up time ( wake up value is stored in ׳RTC_DATA_ATTR long calc_waketime׳ variable from previous cycle ), posting IFTTT, goes to deep sleep for another 10 min. cycle.

The phenomena I wish to share is: The longer deep sleep is the **NTP has few seconds drift which gets longer (again - NTP sync has a drift and not RTC clock)**.

I'm aware that wake time/ RTC drifts during deep sleep ( especially in ESP8266 chips that wake up can be not accurate in terms of minute - I'm using ESP32). Since ESP32 uses RTC, waking up is very accurate ( matter of seconds ). In order to wake up in exact time ( 18:00, 18:10, 18:20... every hour ) code connects to Wifi& NTP, and verify that wake time was as intended (comparing the epoch value that was stored during the end of previous cycle and current epoch time ) if it woke up earlier, it will got to sleep for that missing time.

But - What puzzles me is why updated NTP time ( which is not related what so ever to RTC drifts ), is drifted the longer to sleep is ( for comparison : when less than a minute - almost no drift, when sleeping for 10 minutes, 3 seconds drift, 20 minutes get up to 5 seconds drifts ).

Please see **NOTE(1)** to witness the drift in 10 min sleep.

Posting terminal output:
some explantions: NOTE (1) displays the 3 seconds drift , NOTE(2) calculated time that was stored at previous wake cycle, NOTE (3) shows that that **drift get synced** during the code run - 594 sec for next wake 18:50:00.

    18:39:58.032 -> 09B⸮⸮L⸮1U1V(⸮⸮⸮1m1m1F⸮Connecting to Xiaomi_D6C8 .... // WAKING UP
    18:39:58.595 -> 192.168.3.186
    18:39:59.013 -> now is: 1580575203               **// NOTE (1)**
    18:39:59.013 -> sleep time was: 1580574611
    18:39:59.048 -> expected wake time: 1580575200   // NOTE (2)
    18:39:59.085 -> total time delta: 3
    18:39:59.122 -> OK - WOKE UP after due time:
    18:39:59.419 -> Attempting MQTT connection...connected
    18:40:04.544 -> Connecting to maker.ifttt.com
    18:40:04.855 -> Request resource: /trigger/send_reading/with/key/cFLymB4JT9tlODsKLFn9TA
    18:40:05.376 -> HTTP/1.1 200 OK
    18:40:05.376 -> Date: Sat, 01 Feb 2020 16:40:05 GMT
    18:40:05.414 -> Content-Type: text/html; charset=utf-8
    18:40:05.447 -> Content-Length: 52
    18:40:05.480 -> Connection: close
    18:40:05.515 -> X-Top-SecreTTT: VG9vIGVhc3k/IElmIHlvdSBjYW4gcmVhZCB0aGlzLCBFbWFpbCB1cyBhdCBqb2JzK3NlY3JldEBpZnR0dC5jb20uIFdlIHdhbnQgTWFrZXJzLg==
    18:40:05.619 -> Server: web_server
    18:40:05.619 ->
    18:40:05.619 -> Congratulations! You've fired the send_reading event
    18:40:05.689 -> closing connection
    18:40:07.007 -> Last Sleep: 1580574611
    18:40:07.007 -> Time left: 594                 // NOTE (3)
    18:40:07.041 -> Going to DeepSleep for [594] sec

Relevant code:

    void sleepNOW(int sec2sleep = 2700)
    {
      char tmsg[30];
      sprintf(tmsg, "Going to DeepSleep for [%d] sec", sec2sleep);
      Serial.println(tmsg);
      // mqtt_pubmsg(tmsg);
      Serial.flush();
      esp_sleep_enable_timer_wakeup(sec2sleep * uS_TO_S_FACTOR);
      esp_deep_sleep_start();
    }
    bool getTime()
    {
      delay(200);
      if (getLocalTime(&timeinfo))
      {
        time(&now1);
        delay(200);
        return 1;
      }
      else
      {
        return 0;
      }
    }

    bool check_awake_ontime()
    {
      getTime();
      if (timeinfo.tm_year >= 120) // year 2020
      {
        if (lastsleeptime != 0)
        { // not first boot
          long current_boottime = now1;
          int t_delta = now1 - calc_waketime;
          // int t_delta1 = TIME_TO_SLEEP * 60 - (t_delta + TIME_AWAKE);
          Serial.print("now is: ");
          Serial.println(now1);
          Serial.print("sleep time was: ");
          Serial.println(lastsleeptime);
          Serial.print("expected wake time: ");
          Serial.println(calc_waketime);

          Serial.print("total time delta: ");
          Serial.println(t_delta);
          if (t_delta >= 0)
          {
            Serial.println("OK - WOKE UP after due time: ");
            return 1;
          }
          else
          {
            Serial.println("FAIL- woke up before time: ");
            sleepNOW(-1 * t_delta);
            return 0;
          }
        }
        else
        {
          return 1;
        }
      }
      else
      {
        return 0;
      }
    }

inside `setup()`

    #if USE_WIFI
      if (startWifi())
      {
        mqttConnect();
        startNTP();
    #if USE_SLEEP
        check_awake_ontime();   // PLEASE PAY ATTN ONLY THIS LINE
    #endif
      }

inside `loop()`

    #if USE_SLEEP
      if (millis() >= TIME_AWAKE * 1000)
      {
        getTime();

        Serial.print("Last Sleep: ");
        Serial.println(lastsleeptime);

        long clockCount = TIME_TO_SLEEP * 60 - (timeinfo.tm_min * 60 + timeinfo.tm_sec) % (TIME_TO_SLEEP * 60);
        // Serial.print(timeinfo.tm_hour);
        // Serial.print(":");
        // Serial.print(timeinfo.tm_min);
        // Serial.print(":");
        // Serial.print(timeinfo.tm_sec);
        // Serial.println("");
        Serial.print("Time left: ");
        Serial.println(clockCount);

        lastsleeptime = now1;
        calc_waketime = now1 + clockCount;

        sleepNOW(clockCount);
      }

I'm not posting entire code, but only relevant parts.
Appreciate any help,

body: As Juraj commented, a 2.5 [sec] delay, solved it, and NTP update was correct.


message:
Blank output in serial monitor

So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about _mySerial()_ in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.

```c++
#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

void loop() {
  // put your main code here, to run repeatedly:
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}
```

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

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

body:
Step 1) Check RX TX connections
Step 2) Change your baud rate to 115200. Turn off your arduino. Turn off gsm. Start your gsm first and then your arduino.

or
Step 3) Upload Software Serial code and just send "AT" without quotes using serial monitor. If your connections are correct you should get reply as AT.
Also make sure to set the baud rates to 115200.
Most of the GSM modules have default baud rate at 115200 or have auto baud adjustment enabled but need to be power cycled.


message:
ATmega328P-PU blink example not working

I moved from an Arduino to a bare ATmega328P-PU (to save energy). First I wanted to start a blink-script to verify that it's all working. For this I flashed the bootloader and uploaded the blink-script on the microprocessor. On the arduino the internal pin was successfully blinking. Then I unmounted the ATmega and put it into a breadboard.

I wired everything up. The LED to GND and pin 13, on the other side I put in 5V from a battery, and GND of course. Between the LED and GND I added 220 Ohm and surprisingly if I power it over battery inside the Arduino the internal LED blinks but my own LED (the one with 220 ohms) does not. If I power the arduino over USB both of them blink.

Do you have any ideas on how I can fix this?

body:
[This might help you alot][1]

The ATMega328 is 8bit AVR microcontroller with a wide variety of things, in order for this IC to work it's essential to have a "Clock Source".as default of Arduino UNO it uses a 16MHz Crystal oscillator with two 22pF capacitors in order to generate the clock signal so, if you took the ATMega328 from the Arduino and put it in a breadboard you should connect these components in order it to work as well as pulling up RESET pin to VCC.

The Atmega328 has a lot of internal calibrated oscillators, from them are 8MHz and 1MHz and alot more, but in order to them to work you need to configure them first by setting up things called "high fuses and low fuses" these control alot of things in the microcontroller from them they determine the clock source.

As how to burn the bootloader to set fuses is not the topic of the question, I won't come to details about it.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
  [2]: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQr29kQ2qAeW-uulZv2FWVGlUXX-0bNHvpvtbL3C8VfSCxRzAb


message:
Clock frequency VS cycle time

I am considering switching from Arduino Pro Mini 5V 16MHz to Arduino Pro Mini 3.3V 8Mhz for some project because I would like to run it with a 4.5V input power.

Will the switch from 16 to 8Mhz double the cycle time of my loop() function ?

Edit -- adding precision:
My loop function is simple: it's reading a couple of sensors with analogRead and setting a few pins to HIGH or LOW. It does not use delay().

Thanks.

body:
It depends.

The `loop` function is handled like a while loop. This means, when the `loop` function finishes, some framework code  is executed (very small) and the `loop` function is called again etc.

However, there are some calls that do not depend on the clock speed, the best example is the `delay` function, but also if you made your own check using e.g. `millis` this will not depend high likely on the clock speed.

Beyond that, there can be peripheral calls which are not related to the clock speed (although internally in libraries timing functions as above are used to manage this), but you don't see them when used from a library.


body:
The execution time of your `loop()` will be slightly longer when the CPU
runs at 8 MHz v.s. 16 MHz, but I don't expect the difference
to be significant. CPU-bound functions, such as `digitalWrite()`, will
run at half the speed. These functions, however, are quite fast. In
contrast, `analogRead()` is slow, as it takes roughly 110 µs to
execute, so this is likely where your `loop()` spends most of its time.

The execution time of `analogRead()` does not depend significantly on
the CPU speed. This function spends most of its time waiting from the
analog-to-digital converter to do its conversion. When the CPU is
clocked at either 1, 2, 4, 8 or 16 MHz, the Arduino core [sets the
ADC prescaler so that the ADC is clocked at 125 kHz][adc-freq].
This means the conversion time will be the same irrespective of the CPU
frequency.

**Note**: You may just use your Arduino Pro Mini 5V 16MHz. This board is
based on the ATmega328P microcontroller, which is rated for frequencies
up to 20 MHz when the supply voltage is between 4.5 and 5.5 V.
According to the [datasheet][] (see freq-Vcc graph), it should safely
run at 16 MHz for any supply voltage between 3.78 and 5.5 V.

[adc-freq]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.2/cores/arduino/wiring.c#L353-L382

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf#G3.2085279


message:
How to print stack trace and register dumps on arduino serial monitor?

I want to debug my ESP32 module which is giving an exception using ESP32 exception decoder, but for that, I would need to have access to my stack trace to paste it. But currently, my arduino serial monitor does not print the stack trace. (as shown below)
[![enter image description here][1]][1]

But I would need stack trace to be printed, like in the below image to debug my exception. How can I print it on the serial monitor?
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/xJmOZ.jpg
  [2]: https://i.stack.imgur.com/g6NNk.jpg

body:
Got the required trace logs at the output. All I had to do was enable PSRAM in tools.
[![enter image description here][1]][1]

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


message:
Arduino Firebase ESP8266 Connection

I am working on a project that needs data to be stored in cloud db so that I can access the data in a mobile application. For database I have considered Firebase. I am following the following [link](https://create.arduino.cc/projecthub/electropeak/connecting-arduino-to-firebase-to-send-receive-data-cd8805). But when i try to install the libraries i am getting ```No such file or directory found``` errors for ```memory```, ```queue```, ```Firebase.h```, ```vector```, ```functional```, ```utilities``` (not all but different packages shows different errors). I tried downloading different packages from github. But still had the errors. Where can I find the correct working program? Thanks in advance.

body:
The usual Firebase library for esp8266 is https://github.com/FirebaseExtended/firebase-arduino.

And there is some new Firebase library in Library Manager in IDE. The "More info" link leads to https://github.com/mobizt/Firebase-ESP8266

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

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


message:
how to get serial data to wait until a certain length is reached

I have a code that loops through 2 different serial inputs on the arduino mega, and sends them to serial constantly:
```arduino
int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  boolean reading2 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.println(String("Reader 7: ") + tagString1); //the tag itself

delay(1);
  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
  //////////////////////////////////////////////////
  // This bit reads from serial2, located on pin 17
  /////////////////////////////////////////////////
  while (Serial2.available() > 0) {

    int readByte2 = Serial2.read();

    if (readByte2 == 2) reading2 = true;
    if (readByte2 == 3) reading2 = false;

    if (reading2 && readByte2 != 2 && readByte2 != 10 && readByte2 != 13) {
      tagString1[index] = readByte2;
      index++;
    }
  }
  Serial.println(String("Reader 8: ") + tagString1);

  clearTag(tagString1);
  resetReader();
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}
```
when not scanning anything, the serial monitor outputs this:
```arduino
Reader 1:
Reader 2:
Reader 1:
Reader 2:
```
When I scan a tag, lets say on reader 1, I get this:
```
Reader 1: 000004f5
Reader 2:
Reader 1: 000004f5
Reader 2:
```
it is not possible to scan more than a single scanner at a time. Is it possible to get the first line to wait until a certain number of characters have been scanned (indicating a tag has been scanned), and then output to the serial monitor?After that initial run, the code will loop as I showed above. any help is appreciated.

body: I would use a programming concept called a state machine. For example an integer variable called State could be used to track the current status which could for example be WAITING_FOR_DATA or RECEIVING_DATA or DATA_COMPLETE and only print when DATA_COMPLETE. I'm sure there are plenty of examples you could find with an appropriate search.


body:
1.prefer using Serial.readStringUntil(); OR Serial.readString() that way its much easy to manipulate.

2.use a static variable in loop function which stores the string or use a global variable to save char array tagString1 before going in println function same goes with the second reader that way the println will show the previous scan until a new scan is not done.

3.print both the tagstrings in the end of the code one after another


message:
Grbl on Arduino Uno (Elegoo) with DM542 + nema24 stepper motor not working

i've already searched and tried for a quite depressing amount of hours, but am not able to solve this problem:

The parts are the following:
 - Elegoo Arduino Uno, on wich i flashed GRBL
 - 24v Power Supply (wich powers the stepper motor(s)
 - Nema24 3nm stepper motor
 - A DM542 Driver
 - bCNC (exe-build on win7 and win10)

Now, i connected one stepper-driver and stepper-motor as x-axis to the arduino.
The wiring is as following:
 - 5v from arduino to the three + Pins (ENA, DIR and PUL)
 - Pin 2 to PUL, Pin 5 to DIR, Pin 8 to ENA
 - 24V go to + and ground port of the driver, the 4 motor-wires are wired accordingly to the driver

I downloaded GRBL from Github and flashed it to the Arduino (i can run grbl-commands from the serial monitor inside the arduino ide, grbl is unlocked), connected everything and opened up bCNC, searched for the arduino on com-port, wich is shown correctly, and connected wich works fine (in the main screen "connected" shows up).
However when i try to move the x-axis under the control-panel in bcnc, nothing moves, on the screen the numbers change correctly and i get an ok in the logs, but the motor does not move a bit.
I double checked the wiring and tried to write a little program in arduino ide to move the stepper motor without grbl (deleted grbl, wrote a little program wich manually set the intervals ecc), without changing the wiring, that worked...
How can i debug this? Any suggestions?

Thanks in advance!

body:
As you wrote, that you connected the positive pins of ENA, DIR and PUL to 5V, I guess you use the common anode connection scheme from the DM542's [datasheet][1] (the driver seems to have optocouplers for the inputs). That would mean the inputs are active low (a Pulse would be a transition from HIGH to LOW and then back to HIGH).

GRBL v1.1 has by default an active high pulse signal:

> By default, a step signal starts at normal-low and goes high upon a step pulse event. After a step pulse time set by $0, the pin resets to low, until the next step pulse event.

(from the [GRBL github wiki][2]). I guess, this is the problem. Please try to set GRBL for inverting the pulse signal with `$2` (you may well find a corresponding setting inside bCNC.

Be sure, that GRBL is outputting the signals, that your driver is expecting in your connection scheme.

  [1]: http://www.sah.co.rs/media/sah/techdocs/dm542_manual.pdf
  [2]: https://github.com/gnea/grbl/wiki/Grbl-v1.1-Configuration


message:
Arduino Uno lag in simple loop

I have a simple Arduino sketch which I have been playing with on my Uno.

The idea is simple, the user turns a potentiate (pin A2), when they pass a certain threshold a LED is turned on (pin 7).

Here is the code:
```
// Digital pins
const byte ledPin = 7;

// Analog pins
const byte userInputPotPin = A2;

// Potentiometer constants
const int userInputPotMinimumValue = 0;
const int userInputPotMaximumValue = 1023;
const int userInputMinimumValue = 1;
const int userInputMaximumValue = 100;

// Variables
const int threshold = 90;

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

 // Digital pins
 pinMode(ledPin, OUTPUT);

 // Analog pins
 pinMode(userInputPotPin, INPUT);
}

void loop()
{
 int rawValue = analogRead(userInputPotPin);
    int mappedValue = map(rawValue, userInputPotMinimumValue, userInputPotMaximumValue, userInputMinimumValue, userInputMaximumValue);

    String messageText;
 messageText += "Raw:   " + String(rawValue) + "\t";
    messageText += "Mapped:" + String(mappedValue);

    if(mappedValue > threshold)
    {
        messageText += "\tThreshold exceeded!";
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }

    Serial.println(messageText);

    delay(100);
}
```

The problem is that when it is run the hardware is very unresponsive - I can turn the pot, but I don't see the light change for several minutes. The log messages in the serial monitor also seem to be lagging behind.

I have tried:

* Removing the Serial statements (so there is no serial communication when the sketch is running), and just observing the LED. This makes no difference.

* Increasing the value in the delay up to 1000. This makes no difference in the responsiveness.

However, when I run the sketch on my Mega2560 the problem goes away and the circuit is as responsive as I expect.

Is there something wrong with my Uno board?

body:
The String+ operator is very expensive. High likely what it does is:

- Create a new block of memory to accommodate the old string content and the to-be-concatenated text.
- Copy the current String to a new string location
- Concatenate the string
- Free the old memory

Besides creating memory gaps which can be disastrous for the just 2 KB SRAM of the Arduino Uno, it takes a lot of time.

Some tips:

- Do not use Strings
- Do not concatenate strings if not needed
- To save more time, use short strings instead

If you really need to debug a time critical part, copy numbers you want to print to an array, and AFTER you do all 'real' code, start printing the numbers.


body:
It turns out the problem was the A2 pin on the board.

When I used the A0 pin (or a different board) the problem goes away.

I realised something was wrong when I noticed the values from the pot were strange (I expected values in the range 0 - 1023, but was receiving values from 170-250 ish).


message:
Reduce Sketch Size Help!

I dont know what to do?

Sketch uses 3712 bytes (12%) of program storage space. Maximum is 30720 bytes.

Global variables use 210 bytes (10%) of dynamic memory, leaving 1838 bytes for local variables. Maximum is 2048 bytes.

Program:

    String texto;
    int flag;
    void setup() {
    Serial.begin(9600);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(7, OUTPUT);//luz stop
    pinMode(8, OUTPUT);//faros
    }
    void loop() {
    while (Serial.available())//
    {
    delay (10);
    if (Serial.available() > 0) //verifica que este disponible el puerto serie y verifica que haya algun
    caracter
    {
    char c = Serial.read(); //guara cualquier caracter que haya llegado por el puerto serie
    texto += c; //concatenamos
    }
    } ///Sentencias de control///
    if (texto == "1") //compara el contenido de la avariable "texto" con el numero 1
    {
    digitalWrite(7,LOW); //Apaga la luz stop
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, LOW);
    }
    if (texto == "3") //compara el contenido de la avariable "texto" con el numero 3
    {
    digitalWrite(7,LOW); //Apaga la luz stop
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, HIGH);
    }
    if (texto == "2") //compara el contenido de la avariable "texto" con el numero 2
    {
    digitalWrite(7,LOW); //Apaga la luz stop
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
    digitalWrite(10, LOW);
    digitalWrite(9, HIGH);
    }
    if (texto == "4") //compara el contenido de la avariable "texto" con el numero 4
    {
    digitalWrite(7,LOW); //Apaga la luz stop
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(10, HIGH);
    digitalWrite(9, LOW);
    }
    if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
    {
    digitalWrite(7,HIGH); //Enciende la luz stop
    digitalWrite(11, LOW);
    digitalWrite(12, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    }
    if (texto == "6") //Compara el contenido de la avariable "texto" con el numero 6
    {
    if (flag==1)
    {digitalWrite(8, LOW);
    flag=0;
    }
    else if (flag==0)
    {digitalWrite(8, HIGH);
    flag=1;
    }
    }
    texto = "";
    }

body:
Next time, select your code and press ctrl-K... Also align your code (indent it well).

However, you don't need help actually as you have plenty of memory left. As as written:

- You only use 12% of program storage space. This might seem a lot having such a small sketch, but most of it is because of library usage/framework (such as the `digitalWrite` call(s).
- 210 bytes of dynamic memory is also not something to worry. Btw, this is unrelated to the sketch size, but to your use of (global and other) variables.

So unless you know beforehand your sketch will be much bigger, don't change it because of that reason (too less space).

However, there is another reason, to shorten the sketch, and that is because of duplicated code. As you can see, there is in the entire sketch a lot of repetition (or almost repetition), as in:

    if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
    {
      digitalWrite(7,HIGH); //Enciende la luz stop
      digitalWrite(11, LOW);
      digitalWrite(12, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
    }

What you can do to improve it is:

- Either use a `switch` statement instead of the `if`/`else` statements
- Or create a function that incorporates this condition, together with the following item. This solution is in your case the most clear.

What you do is creating a new function:

    void setPins(bool condition, int pin7, int pin11, int pin12, int pin10, int pin9)
    {
      if (condition)
      {
        digitalWrite(7, pin7);
        digitalWrite(11, pin11);
        digitalWrite(12, pin12);
        digitalWrite(10, pin10);
        digitalWrite(9, pin9);
      }
    }

And you call your function with:

    setPins(texto == "5", HIGH, LOW, LOW, LOW, LOW);

And the same for all other conditions. I only used 5 as example.


message:
Simultaneous Serial reading and writing

I am trying to read long strings from the Serial, using arduino.
In order to spare some RAM I don’t use Serial.readString().
I use Serial.read() instead.

During the reading, I also print some debug info to the same Serial port.

Let's say I send 90 characters to the Serial from the PC. I read them with Serial.read(). If I call a few times Serial.println() between two calls of Serial.read(), I get only 67 character of 90 (`Serial.available()>0` is false).

I read all the 90 character when I don’t call Serial.println() at all.

Why? I was sure that it is possible to write to the serial and read from it simultaneously, that these are independent processes.

Am I wrong?

body:
You can indeed simultaneously read and write through the serial port. At
the hardware level, the serial port (the UART) is a transmitter and a
receiver, which are almost independent. At the software level, they are
both handled through interrupts that read from / write to a software
buffer.

There is, however, a limitation you should be aware of: the software
buffers are not large, typically 64 bytes on AVR-based boards. If
you try to write too much too often, the output buffer will fill out,
and then all subsequent writes become _blocking_, and run as slow as the
serial port itself. If you receive lots of data and do not read it soon
enough, the input buffer will overflow, and you loose some data.

From your description of your issue, it would seem you are hitting the
limits of both buffers. You `Serial.println()` too much, too often. Then
these write operations take too long and, in the meanwhile, you do not
`Serial.read()`. Since your PC is not waiting for you to
`Serial.read()`, your input buffer eventually overflows, and you only
get slightly more than a buffer worth of characters.


message:
How to add calibration to a humidity contoller using UNO and DHT22 sensor?

I am using a setup that helps controlling humidity in an enclosure used to store a humidity sensitive product.   My original posting is [here][1].

I'm using a NANO and a DHT22 temperature/humidity sensor to acquire information on the actual condition in the enclosure; I am also using a 75% RH calibration kit to check the accuracy oh the humidity reading by the UNO and I found the value 9 percentage points higher than the kit's calibration value.   Right now, until I find a solution to calibrate the unit, I have set my setpoint 9 points higher to compensate for the error.
Any ideas on how to tackle this issue would be highly appreciated.

At the moment I can read the DHT sensor and show the humidity value on the LCD like this:

    [...]
      int chk = DHT.read22(DHT22_PIN);
      lastcheck = millis();

      lcd.setCursor(0, 0);
      lcd.print("Humidity: ");
      lcd.setCursor(13, 0);
      lcd.print(DHT.humidity);
    [...]

  [1]: https://arduino.stackexchange.com/questions/72003/help-with-debugging-code

---

@Thomas_Weller,
I'm running tests with your calibration routine and other code changes; I'm using your arbitrary values for testing purposes only; the compensation algorithm works, as sampled below, however the LCD output is the actual DHT22 reading, not compensated.
I am testing with a different sensor, whose output is 9% below the actual RH value.
Here's a sample of the serial output:

    DHT value: 58
    Compensated to: 55
    DHT value: 59
    Compensated to: 56
    DHT value: 60
    Compensated to: 57
    DHT value: 61
    Compensated to: 58
    DHT value: 62
    Compensated to: 59
    DHT value: 63
    Compensated to: 60
    DHT value: 64
    Compensated to: 60

    setpoint = 72
    DHT read = 66.80%
    displ + backlights off
    humidifier ON, fan OFF
    setpoint = 72
    displ + backlights off
    humidifier ON, fan OFF
    setpoint = 72
    displ + backlights off
    humidifier ON, fan OFF
    setpoint = 72
    DHT read = 66.80%
    displ + backlights off
    humidifier ON, fan OFF
    setpoint = 72
    displ + backlights off
    humidifier ON, fan OFF
    setpoint = 72
    displ + backlights off
    humidifier ON, fan OFF

body:
To get better calibration, you need more calibration points. In the example below, I use 8 measurement points.

Given 8 humidity calibration bags for 20, 30, 40, 50, 60, 70, 75 and 80%.

    int calvalues[] = {20, 30, 40, 50, 60, 70, 75, 80};

You would take several samples with the DHT sensor and build a table using the averages:

    int dhtvalues[] = {15, 28, 39, 51, 63, 75, 84, 89};

As you can see, the DHT is below the real values in the lower range and above the real values in the upper range. But it could also be the opposite way.

You can then write this function:

    #define COMPENSATION_POINTS 8

    int compensate(int sensor_value)
    {
      for(int index=1; index<COMPENSATION_POINTS; index++)
      {
        if (dhtvalues[index]>sensor_value)
        {
          int dhtLow = dhtvalues[index-1];
          int dhtHigh = dhtvalues[index];
          int calLow = calvalues[index-1];
          int calHigh = calvalues[index];

          return map(sensor_value, dhtLow, dhtHigh, calLow, calHigh);
        }
      }
    }

which does linear interpolation for all the values that fall somewhere in between.

Here's some test code, which goes through the values in the expected range.

    void setup() {
      Serial.begin(9600);
      for(int hum=15; hum<=89; hum++)
      {
        Serial.print("DHT value: ");
        Serial.println(hum);
        Serial.print("Compensated to: ");
        Serial.println(compensate(hum));
      }
    }

    void loop() {
      delay(1000);
    }

Output:

    DHT value: 15
    Compensated to: 20
    DHT value: 16
    Compensated to: 20
    DHT value: 17
    Compensated to: 21
    DHT value: 18
    Compensated to: 22
    ...
    DHT value: 87
    Compensated to: 78
    DHT value: 88
    Compensated to: 79
    DHT value: 89
    Compensated to: 79

Applied to your case:

    [...]
      int chk = DHT.read22(DHT22_PIN);
      lastcheck = millis();

      lcd.setCursor(0, 0);
      lcd.print("Humidity: ");
      lcd.setCursor(13, 0);
      int compensated = compensate(DHT.humidity);   // <- new line
      lcd.print(compensated);                       // <- changed line
    [...]


message:
How to Read ADC value without Common GND ? (Possible or not !)

I want to Read external signal with the microcontroller.

 **But** the problem is that **ADC does not work** because the signal GND and the microcontroller are not Common,

My question is, have you encountered such a problem? Is there a way to do it?

body:
The solution is to always use at least 2 electrodes. You need 1 electrode, that you connect to ground. You can put this electrode to somewhere neutral ([this instructable][1] suggest connecting it to your leg, but I don't know, if that position is really good).

An ADC measures voltage and voltage is the difference in potential between 2 points, so to measure voltage you by definition need 2 points/connections.

---

Note: The voltages from the EEG electrodes are normally very low, so that they completely vanish in the noise. To really get something useful, you need to amplify the signal. I think there are many tutorials out there, that explain how to do this.

  [1]: https://www.instructables.com/id/DIY-EEG-and-ECG-Circuit/


message:
Accessing softwareserial.available in the arduino loop function always return 0 but in the setup function returns the available byte

I am working on an accident detection system using arduino, what i want to do is to store the recipient phonenumber received as an SMS in the arduino EEPROM, using ``` Serial1.available() ``` to check for bytes in the software serial within the loop() function always return 0, but using it in the setup() function work fine, i have tried my best to debug but am not getting, where could i be getting it wrong. the entire code is bellow:
```
#include<SoftwareSerial.h>
#include <EEPROM.h>
SoftwareSerial Serial1(2, 3); //make RX arduino line is pin 2, make TX arduino line is pin 3.
SoftwareSerial gps(10, 11);
#include<LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

#define x A1
#define y A2
#define z A3

int xsample = 0;
int ysample = 0;
int zsample = 0;

#define samples 10

#define minVal -50
#define MaxVal 50

int i = 0, k = 0;
int  gps_status = 0;
float latitude = 0;
float logitude = 0;
String Speed = "";
String phoneNumber = "";
String gpsString = "";
char *test = "$GNRMC";

void initModule(String cmd, char *res, int t)
{
  while (1)
  {
    Serial.println(cmd);
    Serial1.println(cmd);
    delay(100);
    while (Serial1.available() > 0)
    {
      if (Serial1.find(res))
      {
        Serial.println(res);
        delay(t);
        return;
      }

      else
      {
        Serial.println("Error");
      }
    }
    delay(t);
  }
}

void writeString(char add, String data)
{
  int _size = data.length();
  int i;
  for (i = 0; i < _size; i++)
  {
    EEPROM.write(add + i, data[i]);
  }
  EEPROM.write(add + _size, '\0'); //Add termination null character for String Data

}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len = 0;
  unsigned char k;
  k = EEPROM.read(add);
  while (k != '\0' && len < 500) //Read until null character
  {
    k = EEPROM.read(add + len);
    data[len] = k;
    len++;
  }
  data[len] = '\0';
  delay(2000);
  return String(data);
}

void receive_store_phoneNumber() {
  String msg = Serial1.readString();
  Serial.println(msg);
  phoneNumber = msg.substring((msg.indexOf("***")) + 3);
  writeString(10, phoneNumber);
  lcd.clear();
  lcd.print("Phone num stored");
  delay(2000);
}

void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Accident Alert  ");
  lcd.setCursor(0, 1);
  lcd.print("     System     ");
  delay(2000);
  lcd.clear();
  lcd.print("Initializing");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait...");
  delay(1000);

  Serial.println("Initializing....");
  initModule("AT", "OK", 1000);
  initModule("ATE1", "OK", 1000);
  initModule("AT+CPIN?", "READY", 1000);
  initModule("AT+CMGF=1", "OK", 1000);
  initModule("AT+CNMI=1,2,0,0,0", "OK", 1000);
  initModule("AT+CMGDA=\"DEL ALL\"", "OK", 1000);
  delay(200);
  Serial.println("Initialized Successfully");
  lcd.clear();
  lcd.print("Initialized");
  lcd.setCursor(0, 1);
  lcd.print("Successfully");
  delay(2000);
  lcd.clear();
  lcd.print("Callibrating ");
  lcd.setCursor(0, 1);
  lcd.print("Acceleromiter");
  for (int i = 0; i < samples; i++)
  {
    xsample += analogRead(x);
    ysample += analogRead(y);
    zsample += analogRead(z);
  }

  xsample /= samples;
  ysample /= samples;
  zsample /= samples;

  Serial.println(xsample);
  Serial.println(ysample);
  Serial.println(zsample);
  delay(1000);

  lcd.clear();
  lcd.print("Waiting For GPS");
  lcd.setCursor(0, 1);
  lcd.print("     Signal    ");
  delay(2000);
  gps.begin(9600);
  get_gps();
  show_coordinate();
  delay(2000);
  lcd.clear();
  lcd.print("GPS is Ready");
  delay(1000);
  //  writeString(10, "+2348132450841");
  lcd.clear();
  lcd.print("System Ready");
  Serial.println("System Ready..");

}

void loop()
{
  if (Serial1.available() > 0) {
    receive_store_phoneNumber();
  }

  int value1 = analogRead(x);
  int value2 = analogRead(y);
  int value3 = analogRead(z);

  int xValue = xsample - value1;
  int yValue = ysample - value2;
  int zValue = zsample - value3;

  Serial.print("x=");
  Serial.println(xValue);
  Serial.print("y=");
  Serial.println(yValue);
  Serial.print("z=");
  Serial.println(zValue);

  if (xValue < minVal || xValue > MaxVal  || yValue < minVal || yValue > MaxVal  || zValue < minVal || zValue > MaxVal)
  {
    get_gps();
    show_coordinate();
    lcd.clear();
    lcd.print("Sending SMS ");
    Serial.println("Sending SMS");
    delay(1000);
    lcd.clear();
    lcd.print(read_String(10));
    Send();
    Serial.println("SMS Sent");
    delay(2000);
    lcd.clear();
    lcd.print("System Ready");
  }
}

void gpsEvent()
{
  gpsString = "";
  while (1)
  {
    while (gps.available() > 0)          //Serial incoming data from GPS
    {
      char inChar = (char)gps.read();
      gpsString += inChar;                   //store incoming data from GPS to temparary string str[]
      i++;
      //     Serial.println("88888888888888888888888888888888888888888888");
      //     Serial.println(inChar);

      if (i < 7)
      {
        if (gpsString[i - 1] != test[i - 1])    //check for right string
        {
          i = 0;
          gpsString = "";
        }
      }
      if (inChar == '\r')
      {
        if (i > 60)
        {
          gps_status = 1;
          break;
        }
        else
        {
          i = 0;
        }
      }
    }
    if (gps_status)
      break;
  }
}

void get_gps()
{
  lcd.clear();
  lcd.print("Getting GPS Data");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait.....");
  gps_status = 0;
  int x = 0;
  while (gps_status == 0)
  {
    gpsEvent();
    int str_lenth = i;
    coordinate2dec();
    i = 0; x = 0;
    str_lenth = 0;
  }
}

void show_coordinate()
{
  lcd.clear();
  lcd.print("Lat:");
  lcd.print(latitude);
  lcd.setCursor(0, 1);
  lcd.print("Log:");
  lcd.print(logitude);
  Serial.print("Latitude:");
  Serial.println(latitude);
  Serial.print("Longitude:");
  Serial.println(logitude);
  Serial.print("Speed(in knots)=");
  Serial.println(Speed);
  delay(2000);
  lcd.clear();
  lcd.print("Speed(Knots):");
  lcd.setCursor(0, 1);
  lcd.print(Speed);
}

void coordinate2dec()
{
  String lat_degree = "";
  for (i = 20; i <= 21; i++)
    lat_degree += gpsString[i];

  String lat_minut = "";
  for (i = 22; i <= 28; i++)
    lat_minut += gpsString[i];

  String log_degree = "";
  for (i = 32; i <= 34; i++)
    log_degree += gpsString[i];

  String log_minut = "";
  for (i = 35; i <= 41; i++)
    log_minut += gpsString[i];

  Speed = "";
  for (i = 45; i < 48; i++)   //extract longitude from string
    Speed += gpsString[i];

  float minut = lat_minut.toFloat();
  minut = minut / 60;
  float degree = lat_degree.toFloat();
  latitude = degree + minut;

  minut = log_minut.toFloat();
  minut = minut / 60;
  degree = log_degree.toFloat();
  logitude = degree + minut;
}

void Send()
{
  Serial1.println("AT");
  delay(500);
  serialPrint();
  Serial1.println("AT+CMGF=1");
  delay(500);
  serialPrint();
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print(read_String(10));    //mobile no. for SMS alert
  Serial1.println('"');
  delay(500);
  serialPrint();
  Serial1.print("Latitude:");
  Serial1.println(latitude);
  delay(500);
  serialPrint();
  Serial1.print(" longitude:");
  Serial1.println(logitude);
  delay(500);
  serialPrint();
  Serial1.print(" Speed:");
  Serial1.print(Speed);
  Serial1.println("Knots");
  delay(500);
  serialPrint();
  Serial1.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
  Serial1.print(latitude, 6);
  Serial1.print("+");              //28.612953, 77.231545   //28.612953,77.2293563
  Serial1.print(logitude, 6);
  Serial1.write(26);
  delay(2000);
  serialPrint();
}

void serialPrint()
{
  while (Serial1.available() > 0)
  {
    Serial.print(Serial1.read());
  }
}
```

body:
As Juraj stated in the comments, you have 2 instances of `SoftwareSerial`, but only one of them can listen to it's receive pin at the same time (this is because they rely on the same interrupts to sample the pin). When you call `gps.listen()`, you set the `gps` interface to listen on it's receive pin. `Serial1` (the second `SoftwareSerial` instance) will then no longer listen and thus will not receive anything. When you call `Serial1.listen()` it will be vice versa.

So you need to decide, on which interface you want to listen. For example you could try listening to the GPS all the time, and only switch to the other interface, if you want to send or receive an SMS (since the SIM module seems to be only controlled via AT commands, it will not send data spontaneously).

Or, as an alternative, you could switch to a bigger Arduino, which has more hardware serial interfaces, like the Arduino Mega. It has 4 hardware Serial interfaces and all of them are listening at the same time, since it is implemented in hardware, not in software.


message:
Is Arduino Mega useing one buffer or multiple buffers?

So Arduino Mega has Serial, Serial1, Serial2, Serial3.

However, does those Serial lines use the same buffer? or four independent ones? i.e. are they truly receive single independently, or actually some sort of software sharing? How will that affect the coding?

body:
Every instance of class HardwareSerial has own buffers. [Here][1] you can see it in source code. The instances are declared/definded at the end of the HardwareSerial.h/.cpp.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.h


body:
Actually there are 2 buffers per Serial hardware interface: The hardware buffer, that is 1 byte (per direction of data transfer). The Serial library then transfers this byte in an extra buffer (64 bytes big) from an ISR. Every hardware Serial interface (`Serial` and `Serial1` to 3 on the Mega) has it's own hardware buffer.

Then the `Serial` library is implemented as a class. Every hardware Serial interface get's it's own instance of this class, including the 64 byte buffer.

So the hardware and the memory is completely seperated. The only thing, what they share, is the CPU time for servicing the interrupts, which is no problem, until you are doing somehting very wrong with interrupts.


message:
HTTP Post data from Arduino uno using WiFi

[![All commands are shows as success but there is no response from the webpage to that data is posting.][1]][1]Please help me to post data from arduino uno to a webpage using wifi(ESP-01) module. I try with AT commands it didn't give the response from my webpage

```

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#define DEBUG true

#define RX 10
#define TX 11
String WIFI_SSID = "*****";       // Your WiFi ssid
String PASSWORD = "*****";         // Password
//String DEVICE_SECRET_KEY  = "**";

//String PATH = "/v1/events";
//String PORT = "8000";
//String HOST = "http://10.**.***.66:8000/data";

String HOST = "10.**.240.**";
String PATH = "/data";
String PORT = "8000";

String response;
int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
   sendCommandToESP8266("AT+CWMODE=3", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop()
{
  root["key"] =  "sdfsdfsd";
  String key;
  root.printTo(key);
  String postRequest =   "POST " + PATH  + " HTTP/1.1\r\n" +
                         "Host: " + HOST + "\r\n" +
                         "Accept: *" + "/" + "*\r\n" +
                         "Content-Length: " + key.length() + "\r\n" +
                         "Content-Type: application/json\r\n"
                         "\r\n" + key;
  Serial.print("pst:" + postRequest);
  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());//GET /test.php?Data=2\r\nHost:192.168.1.13\r\n\r\n
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);

  while (esp8266.available())
  {
    if (esp8266.find("+IPD,"))
    {
//      String msg;
      esp8266.find("?");
//      msg = esp8266.readStringUntil(' ');
      response = esp8266.readStringUntil(' ');
      Serial.print(response);
      Serial.println();
    }
  }
  printResponse;

  //  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  Serial.println();
  esp8266.println(postRequest);
  delay(15000);
  countTrueCommand++;
}

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

```
Please help me to get the response from the webpage using this code.

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

body:
Step 1) Upload software serial from example and send AT, you should get reply as AT OK if your connections are correct.
Step 2) Once your connections are correct and if you are uploading the given code then make sure you put your SSID, password, and Server IP which would be the three Strings: HOST, PATH and PORT.

You could alternatively check your server first by sending it a GET or POST using your browser or another software for testing API's(I personally use POSTMAN).

Proceed further once you perform these checks.


message:
Upload already compiled code on Linux CLI without arduino-cli

I have a sketch for an Arduino Nano. I'm compiling it on my build server and get these 3 files:

- `project.bin.elf`
- `project.bin.hex`
- `project.bin.with_bootloader.hex`

Now I need to be able to upload/flash them onto the board (connected via a serial interface) without ``arduino-cli``. Mainly because I can't install it via ``apt-get`` which means I'd have to start jumping through loops to be able to use it (stuff like keeping it up to date, installing, etc. on hundreds of devices).
So I was wondering if there are any tools in the debian repositories I can use to upload the compiled sketch and if so how.

I've been looking for a solution and came across several answers and topic but strangely enough all either use ``arduino-cli``, other specialized tools or link to dead pages or pages that no longer contain the answer.

Examples:

- https://arduino.stackexchange.com/q/15893/62872
- https://arduino.stackexchange.com/q/31160/62872

body:
Use `avrdude`.

The command format is simple, assuming you have installed it from the Linux repositories:

    avrdude -carduino -patmega328p -P/dev/ttyUSB0 -b115200 -Uflash:w:/path/to/project.bin.hex:i

Depending on what bootloader is installed in your nano you may need to change the  baud rate (`-b115200`) to 57600. Also, of course, the USB device should be set to what your board actually identifies as.

The breakdown of the command is:

    -c<programmer type>
    -p<part name>
    -P<port>
    -b<baud rate>
    -U<instruction>

The programmer type, part name and baud rate can all be gleaned from the `boards.txt` file in the AVR core files.  For example, for the Nano:

    nano.upload.protocol=arduino
    nano.menu.cpu.atmega328.upload.speed=115200
    nano.menu.cpu.atmega328.build.mcu=atmega328p

relate to -c -b and -p respectively.  The instruction will always be the same, and means "Write to flash the following file in IHEX8 format".  "flash" is the destination memory, "w" is the write command, and ":i" at the end defines the expected file format.

On a Linux computer with `avrdude` installed you can find much more information with `man avrdude`.


message:
It is any DS2482 I2C to 1-Wire bridge functional library?

Please let me know if you know any good library for DS2482 I2C to 1-Wire bridge.
I tried to use https://github.com/cybergibbons/DS2482_OneWire library  but I got errors when I'm trying to run the library examples (**Read_temp_sensors** and **Scan_1Wire_Bus**):

Error for Read_temp_sensors:
**Read_temp_sensors:2:10: fatal error: DallasTemperature.h: No such file or directory**

Error for Scan_1Wire_Bus:
**Scan_1Wire_Bus C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp: In member function 'uint8_t OneWire::waitOnBusy()':
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp:121:3: error: 'delayMicroseconds' was not declared in this scope
delayMicroseconds(20);
^~~~~~~~~~~~~~~~~
exit status 1 Error compiling for board Arduino Nano.**

Thank you

body:
I guess to solve the first error, you also need [this library][1], which contains the DallasTemperature.h file. The file get's included, but is not contained in the DS2482 library. Unfortunately there is no clue for that in the readme of the library. The author didn't commit anything since 2014, so the development of the library can be considered dead from that side. Though some people have forked the library to make little changes.

And the solution to the second error is described in [this issue][2] of the DS2482 library (just adding an include of "Arduino.h" in the OneWire.cpp file).

  [1]: https://github.com/milesburton/Arduino-Temperature-Control-Library
  [2]: https://github.com/cybergibbons/DS2482_OneWire/issues/3


message:
Error compiling for Arduino Nano 33 BLE with LiquidCrystal library

I recently started coding in the Arduino IDE for the Arduino Nano 33 BLE I bought.
When I choose the Nano 33 BLE as my board, I get the following Error:

    Arduino: 1.8.11 (Windows 10), Board: "Arduino Nano 33 BLE"

    In file included from C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

    C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token

     class LiquidCrystal : public Print {

                                        ^

    C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared

       using Print::write;

             ^~~~~

    exit status 1
    Error compiling for board Arduino Nano 33 BLE.

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

I do not get this error when compiling for a normal Arduino nano board.
This is my code:

    #include <Arduino_LSM9DS1.h>
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12,11,5,4,3,2);

    //pins:
    const int measurePin = 13, calibratePin = 14, xHighPin = 15, xLowPin = 16, yHighPin = 17, yLowPin = 18;

    //constants:
    const int interval = 10;
    const float delta = 10;

    //variables:
    boolean measureSts = LOW, calibrateSts = LOW, xyOK = true;
    int count = 0, timer = 0;
    float measurements[100], current, x, y, z, xZero, yZero, zZero;

    //programm:
    void setup() {
      lcd.begin(16,2);

      pinMode(measurePin, INPUT);
      pinMode(calibratePin, INPUT);
      pinMode(xHighPin, OUTPUT);
      pinMode(xLowPin, OUTPUT);
      pinMode(yHighPin, OUTPUT);
      pinMode(yLowPin, OUTPUT);
    }

    void loop() {
      if ( IMU.accelerationAvailable() ) {
        IMU.readAcceleration(x, y, z);
        calibrate();
        checkXY();
        measure();
        current = z - zZero;
        printValues();
      }
      else lcd.print("--geen  sensor--");
    }

    void checkXY() {
      xyOK = true;
      if ( x < xZero - delta ) {
        xyOK = false;
        digitalWrite(xLowPin, HIGH);
        digitalWrite(xHighPin, LOW);
      }
      else if ( x > xZero + delta ) {
        xyOK = false;
        digitalWrite(xLowPin, LOW);
        digitalWrite(xHighPin, HIGH);
      }
      if ( y < yZero - delta ) {
        xyOK = false;
        digitalWrite(yLowPin, HIGH);
        digitalWrite(yHighPin, LOW);
      }
      else if ( y > yZero + delta ) {
        xyOK = false;
        digitalWrite(yLowPin, LOW);
        digitalWrite(yHighPin, HIGH);
      }
    }

    void measure(){
      if ( digitalRead(measurePin) == LOW && measureSts == HIGH && xyOK ) {
        measurements[count] = z - zZero;
        zZero = z;
        timer = interval;
        count++;
      }
      measureSts = digitalRead(measurePin);
    }

    void printValues() {
      if ( timer >= interval ) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Meting: " + String(measurements[count]) + (char)223);
        lcd.setCursor(0,1);
        lcd.print("Huidig: " + String(current) + (char)223);
        timer = 0;
      }
      timer++;
    }

    void calibrate() {
      if ( digitalRead(calibratePin) == LOW && calibrateSts == true ) {
        xZero = x;
        yZero = y;
        lcd.setCursor(0,3);
        lcd.print("kalibreren");
        lcd.setCursor(1,4);
        lcd.print("voltooid");
        digitalWrite(xHighPin, HIGH);
        digitalWrite(xLowPin, HIGH);
        digitalWrite(yHighPin, HIGH);
        digitalWrite(yLowPin, HIGH);
        delay(100);
        lcd.clear();
        digitalWrite(xHighPin, LOW);
        digitalWrite(xLowPin, LOW);
        digitalWrite(yHighPin, LOW);
        digitalWrite(yLowPin, LOW);
      }
      calibrateSts = digitalRead(calibratePin);
    }

For context: I am trying to create an angle-measuring device using the built-in accelerometer and a 2x16 LCD.

I hope someone can help me fixing this.
Thanks in advance.

-Niels

body:
The Arduino core for Nano 33 BLE is based on Mbed and can be used in [Mbed][1] as library. To achieve this, the Arduino API classes in this core are put in a namespace `arduino::`. This causes problems for libraries which include individual includes of Arduino API historically copied into cores for different MCU architecture platforms. The Arduino.h file includes the API files in the right way so in this case replacing `#include"Print.h"` with `#include <Arduino.h>` in LiquidCrystal.h solves the compilation problem.

  [1]: https://www.mbed.com/en/


message:
LCD screen stops displaying after DC motor starts

I have 3 main components: LCD, thermal resistor, and a DC motor running a fan. The LCD displays the temperature reading from the thermal resistor and then after it hits a certain temperature the motor turns on.

A few seconds after the motor has been turned on the LCD will go blank (but still powered on). I tried connecting a 100uF electrolytic capacitor across between the logic supply pins on the LCD and a 0.47 µF ceramic between the motor terminals.

I did this because i'm assuming since the motor in operation (its commutator) produces voltage/ current "spikes" they can be coupled back through the common power supply. This could provide some immunity against them actually getting to the display driver and interfering with its operation.

What I did kind of helped, but I feel like I am missing something. Any suggestions?

(the link is to the picture of my circuit I quickly made online)

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

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

body:
A [brush DC electric motor][1] and many other similar devices will produce random noise as well as uneven power demands and should be powered independently of logic circuits such as processors and LCDs.  It is very difficult to mediate noise sources and almost always better to remove them from where they are causing harm or unexpected results.

It is also important to power a project with a supply capable of providing more than the expected [amperage][2] during highest demand.  Many will calculate the highest amperage demand and select a power supply which is rated at double the amperage.

If you are using batteries, note that a [9 volt battery][3] (which usually contains 6 cells) on average supplies about 500mAh.  Not much and likely not enough to run a motor with out momentarily dropping the voltage.  Where as a [D-size battery][4] supplies about 15000mAh.  Different battery chemistries change the mAh rating drastically.  500mAh and 15000mAh are about what one may expect from [Alkaline batteries][5].

If using a USB power source, note that older USB ports are only obliged to supply 500mA at any given time.  If this current limit is exceeded, the voltage may drop under 5 volts.

There are many designs on the internet where the motor is powered from the Arduino.  This may be possible for smaller motors however you are having unexpected behavior.  Consider using one or more of the following suggestions to mitigate your problems:

1. Avoid low mAh batteries such as common 9 volt batteries.  Instead use a battery that can provide higher mAh like D Size cells.
2. Avoid powering noisy or current demanding devices directly from the Arduino.  Consider an independent power supply and use a common ground.
3. It may be possible to use a single power supply with good results if the power supply is rated at higher amperage than the peak total maximum amperage.

  [1]: https://en.wikipedia.org/wiki/Brushed_DC_electric_motor
  [2]: https://en.wikipedia.org/wiki/Electric_current
  [3]: https://en.wikipedia.org/wiki/Nine-volt_battery
  [4]: https://en.wikipedia.org/wiki/D_battery
  [5]: https://en.wikipedia.org/wiki/Alkaline_battery


message:
i want to make Node Mcu a bride for other devices but its self connected with home wifi not providing internet to others

i there!
i have Node Mcu which i want to connected with my home wifi
after it it made it own station mode then i want to make it access point for other
but now problem is that it is now in both mode mean (AP+Station ).
when i want to connect any other phone or Pc  it connected successfully
but not providing internet to other devices.
Question?

 1. is problem in wifi configuration of acess point?
 2. which ip,gate way and subnet mask i would assign to the access point?

body:
The NodeMCU under the Arduino framework cannot do what you want.  There are basically three methods for what you want:

1. Configure the IP stack to enable routing - not possible in Arduino, and also requires configuration of your upstream router to work.
2. Configure the IP stack to enable routing and Network Address Translation - not possible in Arduino, and I am not sure if the stack even supports NAT.
3. Write a sketch to act as a proxy server - only works for certain types of traffic (HTTP) and requires a lot of coding. May be possible, but not an easy task.

1) and 2) certainly can't be don in Arduino. There are rumours on the internet that it is possible to configure and compile your own lwIP stack version with routing enabled, but that is so far outside the scope of this website.

Option 3 is the more realistic, but certainly not something even I would consider doing. Creating a sketch that works like [squid](http://www.squid-cache.org/), for example, would be a mammoth task, and may even hit the limitations of the ESP8266.

It would be more beneficial to perhaps get an old wireless router that is supported by OpenWRT and learn how to hack that to act as you want.


message:
AutoConnect module does not broadcast SSID on ESP32 Dev Board

This is my first post so I apologize if I'm missing all required info about my Arduino setup.  I'm a little new to this type of development.

Arduino 1.8.9

ESP32 Dev Module on /dev/cu.SLAB_USBtoUART

Mac OSX High Sierra 10.13.

I'm using the [AutoConnect by Hieromon Ikasama v1.1.3][1] library to create an access point (AP), but the SSID (network name) is not being broadcasted even with the simplest code example.

Why isn't "ESP-78e9" showing up in my network list on my MAC or iPhone?

```
⸮⸮⸮8Y8⸮
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[E][Preferences.cpp:38] begin(): nvs_open failed: NOT_FOUND
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.192, MASK: 255.255.255.0, GW: 192.168.1.1
WiFi connected: 192.168.1.192 on ESP-78e9

```
Full code sample below, written with the Arduino IDE
```
#include <WiFi.h>
#include <WebServer.h>
#include <AutoConnect.h>

WebServer         Server;
AutoConnect       Portal(Server);
AutoConnectConfig Config;

void rootPage() {
  char content[] = "Hello, world";
  Server.send(200, "text/plain", content);
}

void setup() {

  Config.apid = "ESP-" + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX);
  Config.psk = "Password1";
  Portal.config(Config);

  delay(5000);
  Serial.begin(9600);
  Serial.println();

  Server.on("/", rootPage);
  if (Portal.begin()) {
    // Serial.println("WiFi connected: " + WiFi.localIP().toString());
    Serial.println("WiFi connected: " + WiFi.localIP().toString() + " on " + Config.apid);
  }
}

void loop() {
    Portal.handleClient();
}
```

I've tried looking into why "nvs_open failed: NOT_FOUND" is occurring as that feels like the next step, but can't find any information on how to fix it.

I've also tried this on two boards of the same model.

Any ideas?

** Update **
I've modified the code to include the following, but still no AP and captive portal.

https://hieromon.github.io/AutoConnect/advancedusage.html#on-demand-start-the-captive-portal

According to the link above, that SHOULD start a captive portal before attempting to connect to WiFi.

```
  Config.autoRise = false;
  Config.immediateStart = true;
```
Instead I get the debug text here:

```
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START

```

*Update 2*

There may be a bug in the documentation.  I changed "autoRise" to true and the SSID was broadcasted.

```
  Config.autoRise = true;
  Config.immediateStart = true;
```

  [1]: https://hieromon.github.io/AutoConnect/gettingstarted.html

body:
It looks like your ESP32 is already successfully connecting to an access point as a STA (station) and does not start its own Access Point (AP). You probably have already previously configured an SSID and password and the ESP32 is successfully reusing those, so it will not start the Captive Portal (as its own AP).

You should force AutoConnect to start up the Captive Portal or to forget its pre-programmed SSID and password. This can be achieved by On-demand starting of the Captive Portal like described on [this page][1]. According to the documentation you should put the following lines in your code (I have not tested this myself):

    Config.autoRise = true;
    Config.immediateStart = true;
    Portal.config(Config);
    ....
    Portal.begin();

NOTE: The documentation actually states Config.autoRise = false but it seems this does not have the desired effect.

  [1]: https://hieromon.github.io/AutoConnect/advancedusage.html


message:
I think i worn out all of my Arduino Uno memory

Hi my Arduino Uno stacked with a motor driver shield was working perfectly however I am using the same board for a while now and suddenly my board stopped working.
When I upload a code no matter what code is the LED's on the board respond however the code is not executed it does nothing , the board doesn t even beep anymore.
Is there a way to clean the memory or something?
Please help.

body:
To check if you really cannot upload anymore (assuming it's not a software error), try the following sketch

https://www.arduino.cc/en/tutorial/blink

This will blink the BUILTIN led.

There is very low chance to wore out your memory, you can write lots of times to it (like 10,000 times guaranteed, in practice mostly more).

But there can be another hardware problem, but first check if this simple sketch works.

Also (based on jsotola's comment), remove shields/wires.

Especially wires/shields using RX/TX since these pins are (somehow) used for loading a sketch.


message:
How do i send data from a Master to another Master?

I am using an ESP32 to receive data from web.
However in an I2C communication, the EPS32 does not work as a Slave and i already have an Atmega as the Master.

i have seen sites saying Master-Master I2C Connection is possible however, how do i do this? or are there other solutions to have the ESP32 communicate to the ATMega?

body:
Both your master devices must support Multimaster mode, i.e. Arbitration and Synchronization. See I2C Spec [here][1] for a description of the arbitration process.

It's up to you to handle a lost arbitration in your software.

> or are there other solutions to have the ESP32 communicate to the
> ATMega?

Of course. As you considered I2C to be sufficient, UART and [SPI][2] are feasible alternatives supported by almost all microcontrollers.

  [1]: https://www.nxp.com/docs/en/user-guide/UM10204.pdf
  [2]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface


message:
Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom?

Hi I'm a newbie and working on a project with Arduino Due(Atmel3X8E).I want to try and save the important variables to the eeprom during a power outage,using the brown out detector.Is it possible to do this?
Thank you.

body:
Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.

The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

[![Scheme][1]][1]

When external power goes off, you well get enough time and power to store your bytes safely.

**How it works**

When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER_GOOD signal is `LOW`.

When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER_GOOD signal goes to `HIGH` level and your program may start save data to EEPROM.

**Why the optocoupler?**

We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:
[![AVR internals][2]][2]

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.

  [1]: https://i.stack.imgur.com/gvnHB.png
  [2]: https://i.stack.imgur.com/ciCSQ.png


body:
An alternative solution to this is to use an "EERAM". This is an EEPROM with an SRAM buffer in front of it. A large capacitor is used to provide power while the contents of the SRAM are stored in the EEPROM.

It sounds complex, but it's simple since they are made as a dedicated chip. One good example is the [47C16](https://www.microchip.com/wwwproducts/en/47C16) from Microchip. The EEPROM backup is completely transparent to the user, and you can use it just like an I2C connected SRAM chip (so no worries about wearing out the EEPROM by writing too often).

It's a chip I love so much that I made [a breakout of the 3.3V version 47L16](https://majenko.co.uk/product/47l16-eeram-breakout) (since I work mainly with 3.3V devices), and [a library to support it](https://github.com/MajenkoLibraries/EERAM).


body:
I think the gbg's circuit will fail in many situations. It will cause interrupt only when the power source voltage is quite low. If there is no considerable load before the diode filtering caps of the power source will likely hold enough charge and the "5V" will be falling slowly. Arduino will drain the the backup capacitor before it gets "power bad" interrupt.

Since OP is using 12V power supply a simple brownout detector giving warning when this source drops under some reasonable value (i.e. 9V) is the best way. A Zener diode and transistor (or the optocoupler) should be enough because the value of the threshold is not critical.


body: I use FRAM for this. It's always write a byte if it was received, much faster and safety. Additionally you can use chain like approach to save data blocks in EEPROM for controlling of the data integrity. Try to use mosfet instead of diode and optocoupler when it powered from battery.


message:
Is it possible to measure analog output?

I'm using PWM to control LED brightness using MOSFET, using `analogWrite(pwmPin,val)`, while `val` is a 12 bit bit value.

`pwmPin` is defined as- `pinMode(pwmPin, OUTPUT);`

Since `val` changes in time due to external lightning, I wish to measure PWM value, for later use in code. Using `analogRead(pwnPin)` yielded a changing value ranges 7-14.

Is there a way to measure PWM value defined as an output ?

**EDIT 1:**

Saving `val`'s value won't save the problem I'm looking for, since code reaches a `deepSeleep` phase, which `val` can be stored, but I want an actual incidication of its value, and if it actually on.

body:
First: Why would you need to measure the PWM value. You already know it; it's saved in the `val` variable. Why not just use this variable for later use in code?

Second: Doing the analogRead on the same pin as the PWM output is not going to work. Internally there are 2 different hardware peripherals, that are responsible for these functions: The ADC is responsible for measuring analog voltages, while one of the Timers is responsible for generating the PWM output. Only one of them can connect to the pin at any time. Thus you are not measuring the PWM signal, when you do an `analogRead(pwmPin)`. This function set's the pin for measuring analog voltages (means it connect it to the ADC and configures the ADC) and thus disconnects the Timer hardware.

Third: Doing an `analogRead()` directly on a PWM signal is not going to work. PWM is still a digital signal, so measuring it's analog voltage would yield only values around 0 and 1023. This signal is transformed to a real analog voltage through a low pass filter, either electrically or mechanically (here I mean because mechanical elements often cannot follow the relatively fast PWM signal - like a motor or a speaker - which results effectively in a low pass filter).

**How to measure a PWM signal then?** First you definitely need to use a different pin, than the PWM output pin. Then you have 2 ways of measuring the current PWM value:

1. You can connect the PWM output to a low pass filter (combination of resistor and capacitor; you can google this and get very detailed descriptions), and the output of the low pass filter to an analog input pin of the Arduino. Then you can do `analogRead()`s to measure the current value.

2. You can measure the PWM signal directly, meaning measuring the actual pulse width of the signal. There are multiple ways of doing this, one being the `pulseIn()` function, which wait's for a pulse to complete and returns the length of the pulse.


message:
Please help me read this Schematic Diagram

So, i'm trying to build an Obstacle Avoiding Robot by refering this site "[Robot Obstacle Avoiding Car][1]
On the website they have provided with very poor Circuit Diagram.
Please help me read the positions of capacitors.
I have completed connection of all other components.

[![Schematic Diagram][2]][2]
[![Scematic][3]][3]
[![Arduino Close][4]][4]
[![Capacitors Placed][5]][5]

Help would be appreciated

  [1]: https://www.instructables.com/id/How-to-Build-Arduino-Self-Driving-Car/
  [2]: https://i.stack.imgur.com/EJc8o.png
  [3]: https://i.stack.imgur.com/6FDzE.png
  [4]: https://i.stack.imgur.com/28aAq.png
  [5]: https://i.stack.imgur.com/EK6k7.png

body:
They are not poorly described.

All capacitors need to be put from the VCC to GND directly (this will not cause a shortcut).

The left 3 are related to the motor; as it uses a lot of current, it can take the current from the capacitors instead of flowing all the way to the power supply, causing problems of a voltage reduction that can cause other components to fail (temporarily).

The middle two are for the ultrasonic sensor as it also uses some current.
0.1 uF capacitors (the one for the ultrasonic sensor) is typically used for ICs and are called bypass capacitors. These needs to be placed as close as the VCC of the IC (in this case ultrasonic as possible).

And the right two for the power supply itself to remove noise/ripple.

For all capacitors, place them close to where the power is needed (for the motor/ultrasonic) and for the power supply close to the VCC input.

**EDIT**

Below I added the capacitors for the motor, sorry for using MS paint, having no better option right now. I assume the two red wires from the L293D other than going to the breadboard are the 9V lines (VDD).

Also don't put the capacitors in the same pin as the L293D IC pins, but I didn't want to obfuscate the picture. This might destroy your breadboard or IC pins as there is too less space for both.

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

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


message:
VSCode Platformio Schedule.h: No such file or directory

I suppose this might be more an environment question regarding Platform.io and VSCode, as my code works great in the Arduino IDE, however the lack of syntax highlighting is driving me mad.

I've setup a Platform.io project in VSCode, copied my code across and setup my board (Wemos D1 Mini)

My `platformio.ini` file looks like:

    [env:wemos_d1_mini32]
    platform = espressif32
    board = wemos_d1_mini32
    framework = arduino

There are a couple of headers that are highlighted as having errors:

    #include "FirebaseESP8266.h"
    #include <ESP8266WiFi.h>

I've installed FirebaseESP8266 to my project from the PlatformIO libraries, however it still says:

> include errors detected. Please update your includePath. Squiggles are disabled for this translation unit
> (C:\Users\Greg\Documents\PlatformIO\Projects\Lovebox\src\main.cpp).C/C++(1696)

If I try to build it errors with `src\main.cpp:1:22: fatal error: Schedule.h: No such file or directory`

As for the ESP8266WiFi library, it simply says `cannot open source file "ESP8266WiFi.h"`

Anyone know where I'm going wrong?

body:
Did you install the libraries you need / use?

You could do it either via the platformio screen or add the names directly to the
`platformio.ini`

    lib_deps =
        Firebase ESP8266 Client@>=2.7.8

And additionally `ESP8266WiFi.h` is an ESP8266 library
for the ESP32 you should use the lib `#include <WiFi.h>`

EDIT: To update the project libraries, select 'Update Project Libraries' from the project tasks.


message:
How can I power an ESP8266 using a 9V 1A barrel connector power supply?

I have a Huzzah Feather ESP8266 ([pinout][1]) and due to the requirements of my project, I need to supply it with a 9V power adapter with a barrel connector, such as [this one][2].  I'm _REALLY_ new to all of this, so I am trying to figure out how to do this and understand reading dev board specs.

It looks like this development board has a regulator that will adjust a power source down to the appropriate voltage...  but how do I know what parameters it allows?

If I'm understanding correctly, on the pinout sheet above it looks like I would connect a power supply to the "VBUS" and "GND" (right?) pins.  It also says "500mA Max", so does that mean a 1A power supply won't work?  Also, why wouldn't it specify a maximum voltage?

If just connecting a barrel connector to those pins will not work, what am I missing that would get me there?

  [1]: https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts
  [2]: https://www.amazon.com/Arduino-Power-Supply-Adapter-110V/dp/B018OLREG4/

body:
If you read the docs on that Feather board, the barrel connector is meant for a LiPo battery.

It's a 3V unit, not meant for an external power supply, and 9V is too much for it. You would need to run your 9V supply through a buck converter (or a linear regulator) and drop it down to 5V, which you could feed into the USB connector. That does mean that when you want to connect it to USB to power it it will lose power, unless you also plug a LiPo battery into the barrel connector.


body:
You cannot. If you look at the datasheet:

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-feather-huzzah-esp8266.pdf

you can read all details on page 25/26:

> **Alternative Power Options**
>
> The two primary ways for powering a feather are a 3.7/4.2V LiPo
> battery plugged into the JST portor a USB power cable.
>
> If you need other ways to power the Feather, here's what we recommend:
>
> - For permanent installations, a 5V 1A USB wall adapter (https://adafru.it/duP) will let you plug in a USB cable for reliable
> power
> - For mobile use, where you don't want a LiPoly, use a USB battery pack! (https://adafru.it/e2q)
> - If you have a higher voltage power supply, use a 5V buck converter (https://adafru.it/DHs) and wire it to a USB cable's 5V and GND input
> (https://adafru.it/DHu)
>
> Here's what you cannot do:
>
> - Do not use alkaline or NiMH batteries and connect to the battery port - this will destroy the LiPoly charger and there's no way to
> disable the charger
> - Do not use 7.4V RC batteries on the battery port - this will destroy the board
>
> The Feather is not designed for external power supplies - this is a
> design decision to make the board compact and low cost. It is not
> recommended, but technically possible:
>
> - Connect an external 3.3V power supply to the 3V and GND pins. Not recommended, this may cause unexpected behavior and the EN pin will no
> longer. Also this doesn't provide power on BAT or USB and some
> Feathers/Wings use those pins for high current usages. You may end up
> damaging your Feather.
> - Connect an external 5V power supply to the USB and GND pins. Not recommended, this may cause unexpected behavior when plugging in the
> USB port because you will be back-powering the USB port, which could
> confuse or damage your computer.


message:
Bootloader vs. Programmer

I have just started using Arduino boards and I am not sure what the programmers are. I read that you can use a bootloader or a programmer to run your code on an Arduino board. I also read that running with a programmer does not take up any memory space for the bootloader and does not take any time to go through the bootloader.

My question is then, why should I not upload my code during development using a programmer?

body:
The bootloader is a 'program' that resides inside the Atmel IC and makes that IC an 'Arduino'. The bootloader takes care that a sketch can be retrieved by UART (via the USB) and stored inside the Arduino.

The programmer is an external hardware device that can upload a sketch without using the bootloader. Another Arduino can also be used as programmer.

In both cases, when a sketch is loaded, it can be run by the Arduino. The programmer does not need a bootloader, so the memory that normally is taken by the bootloader can be saved.

You could use a programmer, but normally there's plenty space for a sketch. Note, it's not the SRAM memory that is saved, only the Flash memory. And if you are reaching the limit of the Flash memory, you should either optimize it, or move to an Arduino with more Flash memory.

Also, the bootloader is much more easy to use, since you can upload the sketch (to the boatloader) with the Arduino IDE. Programming can be done too by the IDE but is less trivial.