body:
I'm trying to use an existing Arduino library on the Raspberry Pi Pico.  The library is here:

https://github.com/j-bellavance/EdgeDebounce/tree/master

It's based on some interesting insight at Jack Ganssel's blog:
http://www.ganssle.com/debouncing.htm

The library works great on an ATMega 328, but I got two errors when changing to the Raspberry Pi Pico.

The first one was resolved by editing the last line of EdgeDebounce.h like this:

    //#endif;  // Arduino ATMega version
    #endif   // Pico version, also works on ATMega

The second is a bit more complex.  Here's the relevant section of code, these are lines 78 - 102 in EdgeDebounce.cpp :

      byte EdgeDebounce::debounce(byte pin) {
      unsigned long pinStatus;
      do {
        pinStatus = 0xffffffff;
        for (byte i = 1; i <= MYsensitivity; i++) pinStatus = (pinStatus << 1) | digitalRead(pin);
      } while ((pinStatus != debounceDontCare) && (pinStatus != 0xffffffff));
      return byte(pinStatus & 0x00000001);
    }//debounce------------------------------------------------------------------------------------------------

    //updateStatus===================================================================
    //After releasing EdgeDebounceLite, I realized that EdgeDebounce could do more
    //With this small piece of code, EdgeDebounce can return if a switch is
    //  .isclosed();  //Conducting current
    //  .isopen();    //Not conducting current
    //  .rose();      //Just went from open to closed
    //  .fell();      //just went from closed to open
    //-------------------------------------------------------------------------------
    void EdgeDebounce::update() {
      byte newStatus = debounce();
      if (MYmode == PULLUP) newStatus = !newStatus;
      if (MYstatus == OPEN && newStatus == CLOSED) MYrose = true;
      else                                         MYrose = false;
      if (MYstatus == CLOSED && newStatus == OPEN) MYfell = true;
      else                                         MYfell = false;
      MYstatus = newStatus;
    }//update-------------------------------------------------------------------------

When I try to compile, I get this error:

    c:\Users\thisuser\Documents\Arduino\libraries\EdgeDebounce\EdgeDebounce.cpp: In member function 'void EdgeDebounce::update()':
    c:\Users\thisuser\Documents\Arduino\libraries\EdgeDebounce\EdgeDebounce.cpp:102:14: error: invalid conversion from 'byte' {aka 'unsigned char'} to 'pinStatus' [-fpermissive]
      102 |   MYstatus = newStatus;
          |              ^~~~~~~~~
          |              |
          |              byte {aka unsigned char}

    exit status 1

    Compilation error: exit status 1

So I see that the byte of "newStatus" doesn't convert to "pinStatus" which is an unsigned long.  I've done a bunch of Google searches but can't quite figure out what the fix is.

title: Trying to resolve invalid conversion from 'byte' {aka 'unsigned char'} to

Answers: 2

body:
`pinStatus`  is an enum:

    enum pinStatus {OPEN, CLOSED};

The pinStatus you posted is a local variable, nothing to do with `pinStatus` in the EdgeDebounce.h file.

The error is pointing out that you can't assign an unsigned char to an enum which can only hold OPEN and CLOSED. The unsigned char might hold various other values.

Whoever coded that has made some confusing code.

body:
In C and in much pre-standard C++ nothing stops you just assigning an integer value to a variable of enumeration type.  In standard C++ (from 1998 onward) that requires an explicit type conversion (a "cast").

The [AVR Arduino core
supplies](https://github.com/arduino/ArduinoCore-avr/blob/1.8.6/platform.txt#L28)
the `-fpermissive` option to the compiler which among other things allows the implicit
conversion they're doing despite not being standards compliant C++.  Whatever you're using (odds are [this](https://github.com/earlephilhower/arduino-pico/blob/3.3.0/platform.txt) or [this](https://github.com/arduino/ArduinoCore-mbed/blob/4.0.2/platform.txt)) for RPI Pico Arduino core does not provide the `-fpermissive` option. A lot of Arduino cores don't and probably shouldn't.

You *could* modify the RPI Pico core's platform.txt to give the `-fpermissive` option to g++, but it is probably better to make the code compliant.

## Minimal change

There are probably dozens of ways to do this, but a combination of *mimimal* and *pleasing* to C++ nerds probably looks like:

```c++
MYstatus = static_cast<pinStatus>(newStatus);
```

### Alternative Casts

```c++
MYstatus = static_cast<decltype(MYstatus)>(newStatus); // fancier
MYstatus = (pinStatus)newStatus;  // traditional cast
MYstatus = pinStatus(newStatus);  // function-style cast
MYstatus = (decltype(MYstatus))newStatus;  // uhhh
MYstatus = (decltype(MYstatus))(newStatus);  // sure... why not?
```

The `static_cast` declares in intent in a way that other types of cast don't. `decltype` would make that line survive changes to the type of MYstatus better, but `decltype` is not as widely understood.

### Alternately not type-converting at all

You can also observe that `return byte(pinStatus & 0x00000001);` is the [only point of return](https://github.com/j-bellavance/EdgeDebounce/blob/ff33c6/EdgeDebounce.cpp#L84) from
`byte EdgeDebounce::debounce(byte pin)`. So you know this function returns either 0 (false) or 1 (truthy). That's just what's going to happen with applying `& 1`.

They've [defined the enumeration type](https://github.com/j-bellavance/EdgeDebounce/blob/ff33c6/EdgeDebounce.h#L34):
```C++
enum pinStatus {OPEN, CLOSED};
```

The rules of C and C++ (even pre-standard C++) will assign these constants
numeric values 0 and 1, where they weren't explicitly given values and were listed in that order.

So, you could replace `MYstatus = newStatus;` with:

```c++
{
  if (newStatus) {
   MYstatus = CLOSED;
  } else {
   MYstatus = OPEN;
  }
}
```

Or use the ternary operator if you want don't mind people trying to argue with you:

```c++
MYstatus = newStatus ? CLOSED : OPEN;
```


body:
The follwoing code echoes whatever arduino recieves through reciever pin. The idea is that arduino will echo whole data in the buffer on the same line and starting from the new line while echoing the next data recieved in the buffer.

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

    void loop()
    {
      if(Serial.available())
        {
            int count = Serial.available();
            for(int i = 0; i < count; i++)
            {
                char character = Serial.read();
                Serial.print(character);
            }
            Serial.print("\n");
        }
    }

When I run the code it prints the characters line by line. for example if I enter the word "QUICK" it echoes the following

    Q
    U
    I
    C
    K
Whereas I think it should be echoing

    QUICK
Please help me out.

title: Why this simple serial monitor code not working?

Answers: 1

body:
You seem to have the assumption, that the string "QUICK" is send as one package of characters, because you send it with one keypress from the Serial Monitor. But Serial (UART) is a "serial" protocol, meaning, that each byte (aka character for ASCII encoding) is send sequentially.

At 9600 baud each byte will take about 1ms to transmit. Also: small random delays can be introduced by the PC or in the USB communication (if you are communication through a USB to Serial chip, like when you connect the Uno via USB).

Your code runs faster than the data arrives at the Unos microcontroller. The first `if` clause is entered as soon, as there is one byte in your Serial buffer. Then you start reading the data from the buffer, but at that time no further bytes did arrive. So the loop is exited after one iteration.

If you want to process the Serial data line by line, you should send a line ending from the Serial Monitor (or whichever program you are using) via the Line ending option. The common way is to use `\n` aka the newline character as line ending. Then in your code you should read the data until you receive the newline character.

That can be done in multiple ways. One way is to read each arriving character into your own buffer, which is big enough to hold the maximum number of characters, that can occur in your messages. Then, when receiving the newline character you can process the data in the buffer. A variables holds the current position in the buffer:

    unsigned int pos = 0;
    char buffer[20] = ""; // enough space for 19 characters + the null character for terminating the string correctly

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

    void loop(){
      if(Serial.available()){
        char c = Serial.read();
        if(c != '\n'){
          buffer[pos] = c; // Adding the received character to the buffer
          if(pos < sizeof(buffer) - 1){
            // incrementing the position variable to point to the next position in the buffer
            // but only, if there is enough space in the buffer left
            // otherwise this code will overwrite the last character
            pos++;
          }
        } else {
          buffer[pos] = 0; // Terminating the string correctly
          // Process the message here
          Serial.println(buffer);
          // Reset buffer by setting the position back to zero
          pos = 0;
        }
      }
    }

Note: This code needs your `loop()` function to iterate fast enough, so that you won't miss more data, than the internal buffer of Serial can hold (I think 32 characters). So you probably don't want to use long delays (which is nearly always a bad idea anyways, see non-blocking coding and the `millis()` function).


body:
When I was testing out a program I found a strange behavior of ESP8266.

LEDs don't turn off completely in the first `digitalWrite(led, LOW)`, just the brightness of the LED goes down, but it does turn off in the second `digitalWrite(led, LOW)`.

I don't know if it's related to the code or the circuit, so here are both (the program is just two different visual patterns of LEDs toggled by a button)
```
#define led1 D0
#define led2 D1
#define led3 D2
#define led4 D3
#define button D7

unsigned long pressedButton;
bool change = 0;
unsigned long previousTime = millis();
unsigned int difference;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(button, INPUT_PULLUP);
}

void loop(){
  if (!digitalRead(button) && millis()-pressedButton>200){       //check if button was pressed to change visual pattern of leds
      pressedButton = millis();
      change = !change;
      digitalWrite(led1, LOW);         //here led completely turn off
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      previousTime = millis();
  }

  difference = millis()-previousTime;

  if (!change){                                     //default visual pattern of leds
    if (!digitalRead(led1) && difference>=200){
      digitalWrite(led1, HIGH);
    }
    if (!digitalRead(led2) && difference>=400){
      digitalWrite(led2, HIGH);
    }
    if (!digitalRead(led3) && difference>=600){
      digitalWrite(led3, HIGH);
    }
    if (!digitalRead(led4) && difference>=800){
      digitalWrite(led4, HIGH);
    }
    if (difference>=1000){
      digitalWrite(led4, LOW);           //the leds just shrink here
    }
    if (difference>=1200){
      digitalWrite(led3, LOW);
    }
    if (difference>=1400){
      digitalWrite(led2, LOW);
    }
    if (difference>=1600){
      digitalWrite(led1, LOW);
      previousTime = millis();
    }
  }

  if (change){                    //alternative pattern
     if (!digitalRead(led1) && difference>=200 && change){
       digitalWrite(led1, HIGH);
       digitalWrite(led4, HIGH);
       digitalWrite(led2, LOW);
       digitalWrite(led3, LOW);
    }
    if (digitalRead(led1) && difference>=400 && change){
       digitalWrite(led1, LOW);
       digitalWrite(led4, LOW);
       digitalWrite(led2, HIGH);
       digitalWrite(led3, HIGH);
       previousTime = millis();
    }
  }
}

````
[![][1]][1]
Actually, it's a NodeMCU Esp8266, with the pins defined on the code and a 470 ohms resistor.  (obs: resistor is not shorted, in my breadboard those rows are separated)

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

title: LED doesn't completely turn off with digitalWrite(led, LOW);

Answers: 1

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

    if (!digitalRead(led3) && difference>=600){
      digitalWrite(led3, HIGH);
    }
    if (!digitalRead(led4) && difference>=800){
      digitalWrite(led4, HIGH);
    }
    if (difference>=1000){
      digitalWrite(led4, LOW);           //the leds just shrink here
    }
    if (difference>=1200){
      digitalWrite(led3, LOW);
    }

Consider what will happen when the difference is >= 1000.

If the LED is off you turn it on (because it passes the first test, the difference is >= 600), and a moment later you turn it off. So the LEDs are being turned on and off in quick succession, which makes them look dim.

Try re-ordering the tests, and add `else` for each subsequent one. That seems to work for me:

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

      if (!change){                                     //default visual pattern of leds
        if (difference>=1600){
          digitalWrite(led1, LOW);
          previousTime = millis();
        }
        else if (difference>=1400){
          digitalWrite(led2, LOW);
        }
        else if (difference>=1200){
          digitalWrite(led3, LOW);
        }
        else if (difference>=1000){
          digitalWrite(led4, LOW);
        }
        else if (!digitalRead(led4) && difference>=800){
          digitalWrite(led4, HIGH);
        }
        else if (!digitalRead(led3) && difference>=600){
          digitalWrite(led3, HIGH);
        }
        else if (!digitalRead(led2) && difference>=400){
          digitalWrite(led2, HIGH);
        }
        else if (!digitalRead(led1) && difference>=200){
          digitalWrite(led1, HIGH);
        }
      }

---

Also, that resistor on the bottom row isn't achieving anything because all the pins on the bottom row are connected together so it is just shorted out. Not good for the LEDs or the processor.


body:
I have conflicting information on the max output rating for the Arduino Mega.  Some say 200 mA and others say 800 mA like the Uno board.  I am running 8 model railroad signal devices that have (3) 3mm LEDs (Red, Yellow, and Green) in each signal.  Of the 24 LEDs, only 8 are energized at any point in time.  8*.020 = 160 mA.  I believe I am good, but confused as to why the Uno board with 13 digital output pins can handle 800 mA and the Mega board with 40 or so output pins (not including all the TX RX IO pins) can only handle 200 mA.  Lots of forum discussion on this, but most go over my head without answering the question! LOL

Simply, how many mA can all of the digital pins combined provide?

---

Well theory (math) is nice, and a good starting point, but reality is better.

The signals I am talking about are (model) railroad trackside warning signal devices that have a red, yellow and green light, and depending on which light is lit, tells the train's Engineer if it is safe to continue down the track.

[![Signal][1]][1]

Each of these signals are 2.1/2" in height and the LEDs use 30 gauge wires and a 1K resistor.

I connected the red LED on all 8 signal devices to my variable power supply, turned it on and lit all 8 red LEDs with 5 volts, and wow, all 8 only used .023 amps total.

I then disconnected 7 of them and a single red LED only used .002 - .003 amps.  I connected the rest of the signals one at a time, and 2 signals used .006 amps, 3 signals used .009 amps, 4 signals used .011 amps, 5 signals used .014 amps, 6 signals used .017 amps, 7 signals used .020 amps and all 8 signals again only used .023 amps.

If this is the case, that is less than the max output from a single pin.

So, my plan is to connect the signals to the Arduino Mega 2560 on at a time, monitor the total current the Arduino in using after connecting each signal, and see just how much these signals are using.

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

title: What is the max output rating of the pins on the Arduino Mega?

Answers: 1

body:
The answers are right there in the [datasheet](https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf).

The datasheet of the ATMega2560 (and 1280 etc.), page 355, states an absolute maximum current of 200 mA for the ATMega package and 40 mA per I/O pin.

In addition (thank you for the comment, @NickGammon), there are some further restrictions that are described from page 356 of the linked datasheet:

 - The sum of current which can be *sunk* from various ports cannot exceed 100 mA, and from others, 200 mA.
 - The same is true for the amount of current that can be sourced from various ports.

For example, for ports A0-A7 you cannot source a total of more than 100 mA (under steady conditions) and not 40 mA * 8 like you might expect.

So, if you had 8 LEDs on at once, continuously, you would only have 12.5 mA available for each of those ports (for a total of 8 x 12.5 mA = 100 mA).

That means that the 160 mA mentioned in the question could easily be out of spec.

It's not recommended to stay at or near the Absolute Maximum values mentioned in the datasheet for an extended amount of time. It's better to design your solution so that these abolute maximum values are never approached.

For your particular situation I would look into external (TTL) buffers between your Mega and your LEDs.

Alternatively, you could reduce the amount of current through the LEDs to make sure the total amount of current will always stay well below 200 mA or the other limitations mentioned above.


body:
I am trying to turn LEDs in an LED bridge based on the voltage reading from a power source. when the Voltage is zero nothing is ON and then the LEDs gradually turn ON as increase the voltage connected to the Ao pin. ( I am using a pro trinket 3V 120 MHZ)

This is my code:

```c++
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 7; // the number of LEDs in the bar graph

int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached

void setup() {
    // loop over the pin array and set them all to output:
    for (int thisLed = 0; thisLed < ledCount; thisLed++) {
        pinMode(ledPins[thisLed], OUTPUT);
    }
}

void loop() {
    // read the potentiometer:
    int sensorReading = analogRead(analogPin);
    // map the result to a range from 0 to the number of LEDs:
    int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

    // loop over the LED array:
    for (int thisLed = 0; thisLed < ledCount; thisLed++) {
        // if the array element's index is less than ledLevel,
        // turn the pin for this element on:
        if (thisLed < ledLevel) {
            digitalWrite(ledPins[thisLed], HIGH);
        }
        // turn off all pins higher than the ledLevel:
        else {
            digitalWrite(ledPins[thisLed], LOW);
        }
    }
}
```

However, I am not getting the outcome I want. when there is 0 voltage one LED turns ON instead of nothing. when there is a voltage all connected LEDs turn ON regardless of what the voltage is

when there is no voltage connected (floating wires), I get this:

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

when I put any amount of Voltage as long as the power supply is ON the results is the same:

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

Note: What am I doing wrong?
edit: connections are something like that but with fewer digital pins.
[![enter image description here][3]][3]

Note: What am I doing wrong!EDIT:
I was able to get around and print the serial monitor result:
- when the power source is OFF, the reading at A0 (sensorreading) is:

[![enter image description here][4]][4]

Note: What am I doing wrong!- when the power source is ON at any value, the reading at A0 (sensorreading) is:

[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/0Itc3.png
  [2]: https://i.stack.imgur.com/e99yj.png

(Note: What am I doing wrong!)

  [3]: https://i.stack.imgur.com/yjNZJ.png
  [4]: https://i.stack.imgur.com/RhxP6.png
  [5]: https://i.stack.imgur.com/OsuIp.png

title: How to turn LEDs based on voltage readings?

Answers: 2

body:
You are using a Full-size breadboard, for the full-size breadboards, the power rails are divided into two half sections as shown in this picture, and you need to have jumpers to bridge the two half-sections if you want to use them as a single power trail full-size section.
[![enter image description here][1]][1]

So on your photo, you thought that your blue wire (for GND) is connected to the rest of GND pins, but it is actually not connected.

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

body:
I can say your code is working but you need to check the wirering of your circuit .

Note that the voltage on the analogread pin should not be an oscillating voltage at low frequency like AC voltage. It should be  a direct stable voltage to get the correct output.

Here is my diagram below for you to make changes with yours .
Ive testedit on my simulation app and its working perfectly.

The code

```

const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 7; // the number of LEDs in the bar graph
int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached

void setup() {
Serial.begin(9600);
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT); }
}

void loop() { // read the potentiometer:
int sensorReading = analogRead(analogPin);
Serial.print("sensor read : ");
Serial.println(sensorReading);

// map the result to a range from 0 to the number of LEDs:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
Serial.print("led Level : ");
Serial.println(ledLevel);

// loop over the LED array:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// if the array element's index is less than ledLevel, // turn the pin for this element on:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}

// turn off all pins higher than the ledLevel:
else {
digitalWrite(ledPins[thisLed], LOW);
} }

//delay(500); //for debugging
 }

```

The diagram

[![voltage-follower][1]][1]

Note that if you're tryingto measure a voltage higher than 5 volts, make sure to build the voltage divider circuit with the appropriate resistor values for you to get 5v output as that is the highest volt the arduino can carry.
measure
Example below shows a 12 volts dc battery voltage measure(note that 5 volts is the highest voltage supplied to the arduino, not the full 12 volts):

[![12 volts][2]][2]

  [1]: https://i.stack.imgur.com/Ji1xW.png
  [2]: https://i.stack.imgur.com/zqAKB.png


body:
I have been having trouble trying to send a small txt file to my server using the following function with TinyGSM. I know I am connected to the internet and reaching the web server, however, I keep receiving a `400 Bad Request` code. I think something is wrong with my `PostHeader`, but I have no clue where or what it could be... I know I am connecting to my server as I try a default get and return webpage text...

    TinyGsm modem(SerialAT);
    TinyGsmClient client2(modem);
    HttpClient client(client2, server, port);

    void fileUpload(String filename){
      if(!initSD()){
        return;
      }
      File dataFile = SD.open(filename.c_str());
      Serial.println("Uploading File...");
      if (!client.connect(server, port)) {
        Serial.println("Failed connecting to Server");
        return;
      }
      String fileType = "text/plain";
      String content = "--boundary1\r\n";
      content += "Content-Disposition: form-data; name=\"fileToUpload\"; filename="+String(filename)+"\r\n";  // the fileToUpload is the form parameter
      content += "Content-Type: "+fileType+"\r\n\r\n";
      //after this, post the file data.
      String closingContent = "\r\n--boundary1--";
      //Serial.println(content);
      client.println(String("POST ") + "/upload.php" +" HTTP/1.1\r\n");
      client.println(String("Host: ") + server + "\r\n");
      client.println("Content-Type: multipart/form-data; boundary=boundary1\r\n");
      client.println("Connection: close\r\n");
      client.println("Content-Length: "+String(content.length()+dataFile.size()+closingContent.length())+"\r\n");
      client.println(content);
      client.println();
      if (dataFile) {  // start sending file content
        while (dataFile.available()) {
          char c = dataFile.read();
            client.print(c);
          }
        dataFile.close();
      }
      client.println(closingContent);
      Serial.println("File Sent.");
        // read the status code and body of the response
      int statusCode = client.responseStatusCode();
      String response = client.responseBody();

      Serial.print("Status code: ");
      Serial.println(statusCode);
      Serial.print("Response: ");
      Serial.println(response);
    }

title: ArduinoHTTPClient POST multipart/form-data from SD card returning 400 Bad Request

Answers: 1

body:
There were a couple issues that I finally managed to solve... I was able to get it to work by *not* using `ArduinoHTTPClient`. Here is working code for anyone else who stumbles here.

    TinyGsmClient client(modem);

    void fileUpload(String filename){
      File dataFile = SD.open(filename.c_str());
      Serial.println("Uploading File...");
      if (!client.connect(server, port)) {
        Serial.println("Failed connecting to Server");
        return;
      }
      String fileType = "text/plain";
      String content = "--boundary1\r\n";
      content += "Content-Disposition: form-data; name=\"fileToUpload\"; filename="+String(filename)+"\r\n";  // the fileToUpload is the form parameter
      content += "Content-Type: "+fileType+"\r\n\r\n";
      //after this, post the file data.
      String closingContent = "\r\n--boundary1--\r\n";
      //Serial.println(content);
      client.println(String("POST ") + "/upload.php" +" HTTP/1.1"); // or wherever you need to call/print to.
      client.println(String("Host: ") + server);
      client.println("Content-Length: "+String(content.length()+dataFile.size()+closingContent.length()));
      client.println("Content-Type: multipart/form-data; boundary=boundary1");
      client.println();
      client.println(content);
      if (dataFile) {  // start sending file content
        String data = "";
        while (dataFile.available()) {
          char c = dataFile.read();
          data += c;
          //write every line break...
          if(c == '\n'){
            client.write(data.c_str());
            data = "";
          }
        }
        dataFile.close();
      }
      client.print(closingContent);
      unsigned long timeout = millis();
      while (client.connected() && millis() - timeout < 50000L) {
        // Print available data
        while (client.available()) {
          char c = client.read();
          Serial.print(c);
          timeout = millis();
        }
      }
      client.stop();
    }


body:
Do you have to upload the UNO after the applied power is disconnected?

Does the UNO retain the code without any power?

And when the power is disconnected, if the code is retained, will the timers retain their values?
Thanks

title: Arduino UNO Power interruption

Answers: 2

body:
>Do you have to upload the UNO after the applied power is disconnected?

No.

>Does the UNO retain the code without any power?

Yes.

>And when the power is disconnected, if the code is retained, will the timers retain their values?

No.

body:
This answer simply add some detail to that provided by VE7JRO to make it more generally applicable but this does look rather like a school assignment.
Program code is stored in flash memory and this is retained after a power down.  It is not necessary to reload it. The registers which hold timer values or other data from a running program are stored in RAM memory and this is lost on power off. It is possible also to save some data from a running program in EEPROM (or in some cases flash memory) which also survives after a power down.


body:
I am trying to pair two gloves containing beetle BLE's on each, one set to a peripheral role and one to central to control leds for kids' party jewelry.

The Arduino.BLE library does not work with this board.  Is there another BLE library that is compatible with the Beetle BLEs, that will allow me to use the NOTIFY command?

title: What library does the Beetle BLE utilize for BLE commands?

Answers: 0


body:
If you install a real time clock like DS3231 Real Time Clock Module RTC Sensor High Precision, can you program digital output (such as turning 12VDC valves on) based on day of week and time?

I mean like turning digital output 5 on Friday at 7am for 10 minutes, for example.

title: Real time programming with real time module

Answers: 0


body:
I want to ask about pin change interrupts on a 1284P chip using MightyCore.  I have a question about the timing of multiple interrupts on one port.  Specifically, if I am servicing a PCINT vector and another pin in the port changes while I am in the ISR, will it generate another interrupt immediately following the one I am servicing?

When I read the datasheet I see:

> Bit 2 – PCIF2: Pin Change Interrupt Flag 2 When a logic change on any
> PCINT[23:16] pin triggers an interrupt request, PCIF2 will be set. If
> the I-bit in SREG and the PCIE2 bit in PCICR are set, the MCU will
> jump to the corresponding Interrupt Vector. The flag is cleared when
> the interrupt routine is executed. Alternatively, the flag can be
> cleared by writing '1' to it.

When it says that the flag is cleared when the interrupt routine is executed, does that mean when it enters or exits the ISR?  If it is at the end, can I clear the flag in the first line of the ISR and allow another pin change to set it again even if it happens before I exit the ISR?

title: Pin Change Interrupt Flag timing on 1284P

Answers: 1

body:
When it is entered. The wording is slightly vague but I think "when the interrupt routine is executed" means the commencement of execution. Otherwise multiple pin-change interrupts could be easily missed, depending on how long you took inside the ISR.

I suggest writing a simple test that saves somewhere what the flag is, upon entering the ISR, and check it is cleared already.

---

I wrote this test for the Uno (which is the same basic architecture):

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

    volatile bool firstTime = true;
    volatile byte PCIFR_copy = 0;

    ISR (PCINT0_vect)
     {
     // handle pin change interrupt for D8 to D13 here

     if (!firstTime)
       return;

     firstTime = false;
     PCIFR_copy = PCIFR;
     }  // end of PCINT0_vect

    void setup ()
      {
      pinMode (9, INPUT_PULLUP);
      Serial.begin (115200);

      // pin change interrupt (for D9)
      PCMSK0 |= bit (PCINT1);  // want pin 9
      PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
      PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
      }  // end of setup

    void loop ()
      {
      Serial.print ("First time is ");
      Serial.print ((int) firstTime);
      Serial.print (", Flag is ");
      Serial.println ((int) PCIFR_copy);
      delay (1000);
      }  // end of loop

The PCIFR flag was always zero, even after triggering the pin-change interrupt, which shows that it was cleared upon **entering** the ISR.

> will it generate another interrupt immediately following the one I am servicing?

So, based on the above, the answer is yes it will. Upon leaving the ISR one more instruction will be executed and then the next interrupt will be serviced (assuming a higher-priority interrupt doesn't get in first).

---

Another way of looking at it is that the pin change will always set that flag. Between instructions the processor would check that flag (and the flags for the other interrupts) and for the highest priority interrupt, if that flag is set, then it would clear that flag and then commencing processing that interrupt. That is really the only logical way it could work.

---

Also, it makes more sense from the design of the processor to clear the flag upon entering the ISR. Apart from the problem that interrupts could be missed if it didn't, when it enters the ISR the processor "knows" which interrupt it is servicing, because it would have checked the PCIFx flag, it would have checked the PCIEx flag (to see if the interrupt should be executed) and it would have then changed the program counter to the appropriate address for that interrupt, after pushing the current program counter onto the stack. This would be the logical time to clear that flag while all this information is in the processor's "head" so to speak.

At the end of the ISR the code simply executes a RTI (Return from Interrupt) instruction which doesn't have associated with it which interrupt it is returning from. Thus it would be hard to clear the flag at that point.


body:
I cannot enter boot mode with my BlackPill F411 board anymore. It's currently running one my sketch successfully uploaded few weeks ago but now, I don't know what's happen.

I've read this [post][1] which unfortunately doesn't help me.

Blue led doesn't blink, CubeProgrammer 2.14 doesn't detect any DFU mode and Arduino says
```
      -------------------------------------------------------------------
                   STM32CubeProgrammer v2.14.0
      -------------------------------------------------------------------

Error: Target device not found
Establishing connection with the device failed
Failed uploading: uploading error: exit status 1
```
I try to upload via USB here is my setting:

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

Get_PnpDevice says in PowerShell: "BLACKPILL_F401CC CDC in FS Mode".

Isn't it strange? So do you have any idea please?

I use STM32 MCU based boards 2.6.0, IDE 2.1.1. don't know if it occured after some release.

  [1]: https://arduino.stackexchange.com/questions/93017/stm32-black-pill-wont-enter-dfu-mode-reliably
  [2]: https://i.stack.imgur.com/q8dcQ.png

title: Blackpill stm32F411 doesn't enter boot mode anymore

Answers: 0


body:
I am following the instruction to setup a microphone with an esp32 with arduino cli.

Here is the tutorial
- https://dronebotworkshop.com/esp32-i2s/#Resources
- https://www.youtube.com/watch?v=m-MPBjScNRk&t=915s

As pointed out in the video (timestamp 14:30 to 15:05), it seems that some functions of the I2S library were downgraded. And, indeed, when I compile the code, I get the following error message:

```
/Users/me/Documents/cs/microcontrollers/ESP32/microphone/microphone.ino: In function 'void i2s_install()':
/Users/me/Documents/cs/microcontrollers/ESP32/microphone/microphone.ino:33:47: error: 'I2S_COMM_FORMAT_STAND_I2S' was not declared in this scope
     .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
                                               ^
Used platform Version Path
esp32:esp32   1.0.6   /Users/me/Library/Arduino15/packages/esp32/hardware/esp32/1.0.6

Error during build: exit status 1
```

Here is the code:

```
/*
  ESP32 I2S Microphone Sample
  esp32-i2s-mic-sample.ino
  Sample sound from I2S microphone, display on Serial Plotter
  Requires INMP441 I2S microphone

  DroneBot Workshop 2022
  https://dronebotworkshop.com
*/

// Include I2S driver
#include <driver/i2s.h>

// Connections to INMP441 I2S microphone
#define I2S_WS 25
#define I2S_SD 33
#define I2S_SCK 32

// Use I2S Processor 0
#define I2S_PORT I2S_NUM_0

// Define input buffer length
#define bufferLen 64
int16_t sBuffer[bufferLen];

void i2s_install() {
  // Set up I2S Processor configuration
  const i2s_config_t i2s_config = {
    .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = 44100,
    .bits_per_sample = i2s_bits_per_sample_t(16),
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
    .intr_alloc_flags = 0,
    .dma_buf_count = 8,
    .dma_buf_len = bufferLen,
    .use_apll = false
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
}

void i2s_setpin() {
  // Set I2S pin configuration
  const i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_SCK,
    .ws_io_num = I2S_WS,
    .data_out_num = -1,
    .data_in_num = I2S_SD
  };

  i2s_set_pin(I2S_PORT, &pin_config);
}

void setup() {

  // Set up Serial Monitor
  Serial.begin(115200);
  Serial.println(" ");

  delay(1000);

  // Set up I2S
  i2s_install();
  i2s_setpin();
  i2s_start(I2S_PORT);

  delay(500);
}

void loop() {

  // False print statements to "lock range" on serial plotter display
  // Change rangelimit value to adjust "sensitivity"
  int rangelimit = 3000;
  Serial.print(rangelimit * -1);
  Serial.print(" ");
  Serial.print(rangelimit);
  Serial.print(" ");

  // Get I2S data and place in data buffer
  size_t bytesIn = 0;
  esp_err_t result = i2s_read(I2S_PORT, &sBuffer, bufferLen, &bytesIn, portMAX_DELAY);

  if (result == ESP_OK)
  {
    // Read I2S data buffer
    int16_t samples_read = bytesIn / 8;
    if (samples_read > 0) {
      float mean = 0;
      for (int16_t i = 0; i < samples_read; ++i) {
        mean += (sBuffer[i]);
      }

      // Average the data reading
      mean /= samples_read;

      // Print to serial plotter
      Serial.println(mean);
    }
  }
}

```
I also tried to install the I2S library with:

```
arduino-cli lib install I2S
```

but got the following error message:
```
Error installing I2S: Library 'I2S' not found

```

How can I solve the problem?

**EDIT 1**

After the comments I tried to Upgrade the ESP32 package. For this I went to Tools -> Boards -> Board Manager, typed ESP32 and got the following window:

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

It seems to me that I cannot upgrade beyond version 1.0.6 (under Arduino IDE 1.8.19)

What am I doing wrong?

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

**EDIT 2**
Ok I followed the installation instruction on the espressif website and it worked

https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html

title: Functions downgraded in the I2S library using an ESP32

Answers: 0


body:
The specific model is the [W39V080FA](https://www.alldatasheet.com/datasheet-pdf/pdf/181469/WINBOND/W39V080FA.html) and I'm quite a noob when it comes to flashing.

I've already prepared the circuit to divide the voltage and use a proper 3.3V.

I have an plcc to dip adapter, but I really don't know how to wire each pin, really need some tips. Thanks.

title: How to flash plcc 32 chip with arduino

Answers: 0


body:
I'm using the DuinoWitchery LCD library (https://github.com/duinoWitchery/hd44780) in a PlatformIO Arduino project with CLion.

The following code works if I stick it in main.cpp:

~~~
// near top of class...
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

hd44780_I2Cexp lcd(0x27);

// ... snip ...

void setup() {
    for (int x=0; x<8; x++)
       lcd.createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}
~~~

... but if I move the code into another class, like:

**Renderer.h**
~~~
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
    };
}
~~~

**Renderer.cpp**
~~~
void Renderer::renderTo(hd44780lcd* lcd) {
    for (int x=0; x<8; x++)
       lcd->createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}
~~~

... the custom characters end up with garbage data.

I **think** I might be breaking some esoteric rule that governs where you're allowed to put a `const PROGMEM uint8_t[]`, and causing the array declared in Renderer.h to end up in SRAM. But I'm not sure how to confirm it OR fix it.

---

note: the for/next loop to create the chars is just for the sake of illustration & to demonstrate that something that works in main.setup() fails in Renderer.renderTo(). In *real* life, the sequence of characters getting rendered to the LCD owns one of the 8 custom characters & redefines it as necessary to be the decimal point and tenths value.

title: PlatformIO and const PROGMEM

Answers: 2

body:
OK, I ended up blindly stumbling over the solution, even though at this moment I have no idea why it actually works.

I moved the `const PROGMEM uint8_t decimalDigit[10][8] = {...}` declaration **from** Renderer.h **to** the almost-top of Renderer.cpp, so it sits between `#include "Renderer.h"` and constructor:

~~~
#include "Renderer.h"

const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

Renderer::Renderer(int col, int row, int customCharNumber) : BaseRenderer(col, row) {
    assignCustomChar(customCharNumber);
}
~~~

For now, I just have to chalk it up as 'black magic', because some subsequent experiments have forced me to question and doubt everything I ever thought I understood about how #include directives work.

body:
The `PROGMEM` qualifier can only be applied to statically-allocated
constant data. When you move the `decimalDigit` array inside the class,
it becomes a data member, i.e. you have one copy of the array per
instance... in RAM. In this case, `PROGMEM` does not work. My compiler
says:

```text
warning: ‘__progmem__’ attribute ignored [-Wattributes]
```

If you want to keep the array inside the class, it must be given the
`static` qualifier. It then becomes statically-allocated class data (not
instance data):

```c++
// Renderer.h:
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
    static const PROGMEM uint8_t decimalDigit[10][8];
};

// Renderer.cpp:
const PROGMEM uint8_t Renderer::decimalDigit[10][8] = {
    {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
    {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
    // ... snip ...
};
```

Of course, putting the array within the class is not an obligation. If
it is going to be private anyway, the outside world (the files that
include Renderer.h) does not need to know about its existence.


body:
I am getting the ```fatal error MD5 of file not match data in flash```. Below is the output of upload.

    [1/5] cmd.exe /C "cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\esp-idf\esptool_py && python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 partition --type app D:/Users/INOMETRICS/espressif/workspace/blink/build/partition_table/partition-table.bin D:/Users/INOMETRICS/espressif/workspace/blink/build/blink.bin"
    blink.bin binary size 0x31340 bytes. Smallest app partition is 0x100000 bytes. 0xcecc0 bytes (81%) free.
    [2/5] Performing build step for 'bootloader'
    [1/1] cmd.exe /C "cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\bootloader\esp-idf\esptool_py && python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 bootloader 0x0 D:/Users/INOMETRICS/espressif/workspace/blink/build/bootloader/bootloader.bin"
    Bootloader binary size 0x5180 bytes. 0x2e80 bytes (36%) free.
    [2/3] cmd.exe /C "cd /D D:\Espressif\frameworks\esp-idf-v4.4\components\esptool_py && D:\Espressif\tools\cmake\3.20.3\bin\cmake.exe -D IDF_PATH="D:/Espressif/frameworks/esp-idf-v4.4" -D SERIAL_TOOL="python D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py --chip esp32s3" -D SERIAL_TOOL_ARGS="--before=default_reset --after=hard_reset write_flash @flash_args" -D WORKING_DIRECTORY="D:/Users/INOMETRICS/espressif/workspace/blink/build" -P D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/run_serial_tool.cmake"
    esptool.py esp32s3 -p COM8 -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 80m --flash_size 2MB 0x0 bootloader/bootloader.bin 0x10000 blink.bin 0x8000 partition_table/partition-table.bin
    esptool.py v3.2-dev
    Serial port COM8
    Connecting...
    Chip is ESP32-S3
    Features: WiFi, BLE
    Crystal is 40MHz
    MAC: 70:04:1d:be:ab:74
    Uploading stub...
    Running stub...
    Stub running...
    Changing baud rate to 460800
    Changed.
    Configuring flash size...
    Flash will be erased from 0x00000000 to 0x00005fff...
    Flash will be erased from 0x00010000 to 0x00041fff...
    Flash will be erased from 0x00008000 to 0x00008fff...
    Compressed 20864 bytes to 13002...
    Writing at 0x00000000... (100 %)
    Wrote 20864 bytes (13002 compressed) at 0x00000000 in 0.1 seconds (effective 1284.4 kbit/s)...
    File  md5: 1d4bc050825217f8434a2cfd167894cd
    Flash md5: 1b32e380d00eb036ce18a632dedbe04d
    MD5 of 0xFF is b145c0e952abec491d69c8c5f8ac47c4

    A fatal error occurred: MD5 of file does not match data in flash!
    CMake Error at run_serial_tool.cmake:56 (message):
      python
      D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py
      --chip esp32s3 failed

I am getting the same error while uploading with esp-idf and Arduino ide or platformio.

How could i solve the issue.

Regards

title: MD5 of File doesnot match data in flash Error with ESP32 S3

Answers: 1

body:
Yes, I have managed to get it working now, the issue encountered was with the strapping pins. Specifically, Pin 45 of ESP32S3 is responsible for configuring VDD_SPI_FLASH. To ensure it operates at 3.3V, the pin should be connected to the ground. Otherwise, it will function at 1.8V, which might cause problems with the Flash functionality.

Fortunately, this can also be resolved by burning some EFUSES using the espefuse.py tool, which comes along with esptool.py. All you need to do is run the command: `espefuse.py set_flash_voltage <voltage>` (where voltage can be either 3.3V or 1.8V or OFF). For more details, you can visit: [link to the official documentation][1].

  [1]: https://docs.espressif.com/projects/esptool/en/latest/esp32s3/espefuse/set-flash-voltage-cmd.html


body:
I need to update **DHT** sensor data to the webserver in ***JSON*** format using **ESP8266**. This is my code.

```c++
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#include <ArduinoJson.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR PASSWORD";
const int dhtPin = D4;
DHT dht(dhtPin, DHT11);
ESP8266WebServer server(80);

void handleRoot() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temperature) || isnan(humidity)) {
     server.send(500, "text/plain", "Failed to read from DHT sensor");
    return;
  }

  StaticJsonDocument<200> jsonDoc;
  jsonDoc["temperature"] = temperature;
  jsonDoc["humidity"] = humidity;

  String jsonString;
  serializeJson(jsonDoc, jsonString);

  server.send(200, "application/json", jsonString);
}

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");
  dht.begin();
  server.on("/", handleRoot);
  server.begin();
  Serial.println("Server started");
}

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

But I got error like,

```
In file included from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/static_array.hpp:11:0,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatTraits.hpp:14,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatParts.hpp:8,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/TextFormatter.hpp:11,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonSerializer.hpp:7,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/ConverterImpl.hpp:7,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:37,
                 from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,
                 from C:\Users\Kuralmozhi.R\Downloads\ID_2\ID_2.ino:5:
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp: In instantiation of 'typename ArduinoJson6193_F1::enable_if<ArduinoJson6193_F1::is_pointer<T>::value, T>::type ArduinoJson6193_F1::pgm_read(const void*) [with T = const __FlashStringHelper*; typename ArduinoJson6193_F1::enable_if<ArduinoJson6193_F1::is_pointer<T>::value, T>::type = const __FlashStringHelper*]':
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/DeserializationError.hpp:85:12:   required from here
c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp:15:45: error: 'const void*' is not a pointer-to-object type
   return reinterpret_cast<T>(pgm_read_ptr(p));
                                             ^

exit status 1

Compilation error: exit status 1
```

I don't know how to solve this error. Please suggest me some ideas!

---

I tried to update ESP8266. But now it shows like this,

```
Variables and constants in RAM (global, static), used 28984 / 80192 bytes (36%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ DATA     1504     initialized variables
╠══ RODATA   1376     constants
╚══ BSS      26104    zeroed variables
Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 60439 / 65536 bytes (92%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ ICACHE   32768    reserved space for flash instruction cache
╚══ IRAM     27671    code in IRAM
Code in flash (default, ICACHE_FLASH_ATTR), used 273120 / 1048576 bytes (26%)
║   SEGMENT  BYTES    DESCRIPTION
╚══ IROM     273120   code in flash
```

title: ERROR: return reinterpret_cast<T>(pgm_read_ptr(p));

Answers: 1

body:
With the info from [the link Fahad provided in the comments][1], I can only offer a guess: Your ESP8266 board definitions are outdated and the old version of the ESP8266 board definitions contains a bug.

There is an outdated URL to the ESP8266 board definition JSON floating around on the web. I _guess_ you found that one. The URL still works, but is not updated anymore. Please check the version of your ESP8266 board definitions: Open the Board Manager (`Tools -> Board -> Board Manager`), search for ESP8266 and verify that the version is at least 3.1.2 (current version as of this writing; I don't know the lowest version where this bug is fixed).

If the Board Manager does not offer to update to version 3.1.2 (or later), you may need to provide the current URL to the board definitions in `File -> Preferences -> Tab "Settings" -> Additional Boards Manager URLs`. Remove the old ESP8266 URL, but don't remove URLs for _other_ boards. Then try to update using the Board Manager again:
```
https://arduino.esp8266.com/stable/package_esp8266com_index.json
```

  [1]: https://github.com/bblanchon/ArduinoJson/issues/1442


body:
I'm trying to interface an encoder and a 1602 i2c display. My encoder seems to be giving an output between steps.

I have tried to make my code as simple as possible and am outputting whether the encoder rotated clockwise or counter clockwise to serial. When I rotate the knob one physical step clockwise, '++' (separated by a new line) outputs to the serial monitor when I am expecting just '+'.  The same occurs when rotating counter clockwise, except with '--' instead of '++'.

Parts:
 - ESP32 Dev Board
 - [Rotary Encoder](https://www.amazon.com/Cylewet-Encoder-Digital-Potentiometer-Arduino/dp/B07DM2YMT4/?_encoding=UTF8&pd_rd_w=dJykK&content-id=amzn1.sym.5f7e0a27-49c0-47d3-80b2-fd9271d863ca:amzn1.symc.e5c80209-769f-4ade-a325-2eaec14b8e0e&pf_rd_p=5f7e0a27-49c0-47d3-80b2-fd9271d863ca&pf_rd_r=8QJDDY22WMD2B9NRE7XB&pd_rd_wg=2tOn9&pd_rd_r=ea853507-cd5e-45d9-b373-d8c5139e071e&ref_=pd_gw_ci_mcx_mr_hp_atf_m)

Code:

    #define enc1 32
    #define enc2 33
    #define button 25
    #define led 2;

    int oldPos1;
    int newPos1;
    int newPos2;

    void setup() {
      pinMode(enc1, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(enc1),encRead,CHANGE);
      pinMode(enc2, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(enc2),encRead,CHANGE);
      Serial.begin(115200);

      oldPos1 = digitalRead(enc1);
    }

    void encRead(){
      newPos1 = digitalRead(enc1);
      newPos2 = digitalRead(enc2);
      if(oldPos1 != newPos1){
        if (newPos1 == newPos2){
          Serial.println("+");
        }
        else{
          Serial.println("-");
        }
      }
      oldPos1 = newPos1;
    }

    void loop() {
      delay(10);
    }

title: Encoder giving value between steps

Answers: 2

body:
Unfortunately you did not provide a link to the data sheet of the encoder.

One physical step at the knob can generate changes on both pins. And since you have assigned the interrupt service routine to both pins, it is called two times for each physical step.

Another possible reason is "[bouncing][1]" of the mechanical contacts in this encoder. That means, that multiple pulses are generated on the change between _open_ and _closed_. Therefore, change or edge interrupts are only a correct solution, if you take bouncing into account.

To investigate the issue, you can insert port pin toggles to your interrupt service routine. For example, set a pin on entry and reset it on exit. Then connect an oscilloscope or logic analyzer and compare the input signals and this output.

Oh, and it is never a good idea to put serial output in an interrupt service routine. Depending on the amount of sent data and the chosen baudrate, this output will block the routine for several milliseconds. During this time, the same interrupt is not serviced, and can be skipped in case of multiple triggers.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_bounce

body:
This is the kind of thing that can happen when you buy cheap parts that
come with no documentation whatsoever: you don't know how they are
supposed to work! Many rotary encoders have two detents per pulse: if
you rotate them by a single detent, you get a single transition on each
pin. If using such an encoder, you would indeed expect a single `+` or
`-` printed per detent. But what about the encoder you bought? You can't
tell, since there is no documentation!

Quite fortunately, a helpful individual left a useful review on the
product page you linked to. It can serve as an ersatz of datasheet:

> Each movement of the spindle from one detent to the next results in
> the encoder1 and encoder2 pins going through multiple transitions, not
> a single one (as you might expect).
>
> Assuming that you have tied the encoder pins to (say) 5V with a
> resistor, a rotation between detents, will produce a set of encoder
> transitions. For example: 11 10 00 01 11 (clockwise) or 11 01 00 10 11
> (anti-clockwise).

This explains the behavior you are experiencing.

Side note: as jsotola writes in a comment, you should
remove the `enc2` `attachInterrupt()`. As your interrupt handler
explicitly ignores transitions in `enc2` (it does nothing unless `enc1`
changed), there is no point in interrupting the processor for those
ignored transitions.


body:
I just discovered that the Dallas DS18B20 can be read from either digital or analog pins. I never thought analog was an option until I stumbled across an article searching for another issue.
So now I'm wondering, if I have a dozen DS18B20's on about 20 feet of wire with a 4.7k resistor, what would be the better option for reading? Digital or Analog?

title: DS18B20 oneWire analog vs digital

Answers: 2

body:
To use multiple DS18B20 devices on the same bus

1/ First get the address of each DS18B20 device by attaching it alone to the Arduino, and calling the `discoverOneWireDevices();` function. Write down the address. This is a set of 8 hexadecimal digits, eg 0x28, 0x13, 0x97, 0x9A, 0x0A, 0x00, 0x00, 0x6A

2/ Hard-code the address of each device, e.g. `#define TEMP_SENSOR1 {0x28, 0x13, 0x97, 0x9A, 0x0A, 0x00, 0x00, 0x6A}` before the call to the setup, and define the corresponding device address: `DeviceAddress tempSensor1 = TEMP_SENSOR1;`

3/ each time you launch a command to a DS18B20, specify to which you are speaking, eg `temperature1 = sensors.getTempC(tempSensor1);`

body:
Analog is not an option as the 1-wire is a digital communication bus, however using an analog pin is on many processors to do this is possible. This is achieved on many of the processors because the analog pin can be configured and used for digital I/O.  Arduinos such as the UNO can accomplish this because of the processor they use. Note not all microprocessors are designed use an analog pin for digital I/O.

There is an application note by AMD called "1-Wire Search Algorithm", https://www.analog.com/en/app-notes/1wire-search-algorithm.html. By using this process you can read all of the sensors independently without knowledge of there addresses. Using this method will not guarantee which sensor you are reading but the sequence will repeat and you can simply replace a sensor but the order will probably change. This allows you to change sensors etc when there are not many sensors involved. Here are some links to better explain this.

https://docs.arduino.cc/learn/communication/one-wire

https://www.arduino.cc/reference/en/libraries/onewire/


body:
I am puzzled. I just connected 3.3 V input to the Analog pin A5 of the Arduino UNO. On the script, I am reading all the input pins. Surprizingly, all the pins are giving voltage as that of A5 pin. This made me think whether all of them shorted?

code:

    int a0_analogPin = A0;
    float a0_val = 0;
    int a1_analogPin = A1;
    float a1_val = 0;
    int a2_analogPin = A2;
    float a2_val = 0;
    int a3_analogPin = A3;
    float a3_val = 0;
    int a4_analogPin = A4;
    float a4_val = 0;
    int a5_analogPin = A5;
    float a5_val = 0;

    void setup() {
      Serial.begin(9600);           //  setup serial
      pinMode(a0_analogPin,INPUT);
      pinMode(a1_analogPin,INPUT);
      pinMode(a2_analogPin,INPUT);
      pinMode(a3_analogPin,INPUT);
      pinMode(a4_analogPin,INPUT);
      pinMode(a5_analogPin,INPUT);
      Serial.println("A0_val,A1_val,A2_val,A3_val,A4_val,A5_val");
    }

    void loop() {
      a0_val = analogRead(a0_analogPin)*5.0/1023.0;  // read the input pin
      Serial.print(a0_val);          // debug value
      Serial.print(",");
      a1_val = analogRead(a1_analogPin)*5.0/1023.0;  // read the input pin
      Serial.print(a1_val);
      Serial.print(",");
      a2_val = analogRead(a2_analogPin)*5.0/1023.0;  // read the input pin
      Serial.print(a2_val);
      Serial.print(",");
      a3_val = analogRead(a3_analogPin)*5.0/1023.0;  // read the input pin
      Serial.print(a3_val);
      Serial.print(",");
      a4_val = analogRead(a4_analogPin)*5.0/1023.0;  // read the input pin
      Serial.print(a4_val);
      Serial.print(",");
      a5_val = analogRead(a5_analogPin)*5.0/1023.0;  // read the input pin
      Serial.println(a5_val);
    }

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

Serial Monitor:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/mStO4.jpg
  [2]: https://i.stack.imgur.com/8jiBs.png

title: Whether my board analog pins shorted? I see same input on all

Answers: 2

body:
Most of your analog pins are not connected to anything. In electrical engineering, that's called "floating". It means they have no reference to anything and thus their value can be anything.

Basically their value is determined by static electricity. Moving your hands near the pins or moving them away may be enough to change the value you read.

It could be that your "oscilloscope view" actually shows that nicely. One pin gets the voltage immediately (`value 6`) and through static electricity, the other pins slowly take that value as well (`value 1`, `value 2`, ...). Probably the steepest curve of those is closest to the pin that is high and the most shallow curve is furthest away. Your observations may vary depending on humidity and temperature, since that makes static electricity spread faster or slower.

Solution: don't let your pins float. Connect them to a defined value, e.g. ground if you want them to have a predictable value.

body:
You are seeing crosstalk between the analog input channels. In the
[datasheet of the microcontroller][datasheet] you can see the analog
input circuitry. See the capacitor labeled “CS/H”? This is
the “sample and hold” capacitor. Its job is to hold the voltage being
read while the ADC performs the conversion. When you measure channel A5,
you are charging this capacitor to 3.3 V. Then, when you switch to
a floating input, the capacitor has no path to discharge, and you end
up measuring the same voltage.

Actually, you do not measure exactly the same voltage. The reason is
that each input pin has a parasitic capacitance. When you switch from A5
to A0, the charge in CS/H splits between this capacitor and
the stray capacitance of the pin A0. Then, you switch to A1 and the
remaining charge is split between CS/H and the stray
capacitance of A1, and so on. Eventually, when you come back to A5, you
charge again CS/H to the full 3.3 V and the cycle starts
again. The net effect is that you are progressively moving charges
between the successive pins. This is why the curves look like
exponential relaxations, where each successive pin charges more slowly
than the preceding one.

The solution, as already written in other answers, is to avoid leaving
the pin floating. The datasheet recommends making sure the connected
source has an impedance no larger than 10 kΩ.

[datasheet]: https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738797


body:
when the Arduino_2 starts the board is not selected.

Is it possible to run a program with such parameters (for example)?: "C:\Program Files\Arduino IDE\Arduino IDE.exe" --board arduino:avr:uno --С:\Users\scetch.ino

title: Startg the Arduino2 with the boards parameters

Answers: 0


body:
I am a complete beginner trying my hand at a home automation project.

Part of my setup includes using an Arduino UNO REV3 (A000066), and connecting two CQRobot Ocean Non-Contact Water/Liquid Level Sensors (CQRSENYW001).

There is great documentation for the sensor:

http://www.cqrobot.wiki/index.php/Non-Contact_Water/Liquid_Level_Sensor_SKU:_CQRSENYW001

And setting up one sensor is a breeze (see setup in image below):

[![Sensor to Arduino][1]][1]

- Red Wire to 5V
- Black Wire to GND
- Green Wire (Output) to 7

Since there is only one 5V on the Arduino (and since the project could expand), it sounds like I need to use a breadboard to allow for expansion.

I used the following video to connect the Arduino to the breadboard for power:

https://www.youtube.com/watch?v=Ia7gkgSor78

**Now to connect the two sensors, do I just need to put the Black and Red Dupont Wires from the sensors anywhere in the - and + columns on the breadboard and connect the green wires back to the Arduino for the output in 6 and 7?**

***In other words, does the setup look correct below?***

[![Sensor Setup][3]][3]

I have noticed that doing this seems to work for the most part (there is power) for the sensor, but I just want to make sure I am doing this right. Thanks!

  [1]: https://i.stack.imgur.com/jlWEl.jpg
  [2]: https://i.stack.imgur.com/ztEru.jpg
  [3]: https://i.stack.imgur.com/05Qh8.jpg

title: How to Connect Two CQRobot Ocean Non-Contact Water/Liquid Level Sensors (CQRSENYW001) to Arduino UNO REV3 (A000066)?

Answers: 0


body:
I have created a circuit with a barebones ATMega328.
I also have an external programmer (Sparkfun's Pocket AVR Programmer)...

Now I want to program a particular sketch... When uploading a sketch, do i also have to flash the bootloader beforehand?

Or is it possible to upload the sketch directly to the microcontroller without a bootloader?

title: Programming barebones ATMega328 with external programmer and no bootloader

Answers: 1

body:
The Pocket AVR Programmer is just a standard ISP programmer, meaning it uses the ISP protocol built into the hardware of the microcontroller to write data to flash and EEPROM. That is also the way, that the bootloader got onto the microcontroller in the first place.

The bootloader of the Arduino on the other hand is a small program to communicate over Serial (or USB depending on the Arduino board) and then write the data to flash and EEPROM.

So: **No, you don't need the bootloader, if you want to use the ISP programmer.** Select your programmer in the corresponding menu of the Arduino IDE to use it.

Though keep in mind, that you won't be able to upload a new sketch via Serial/USB without the bootloader. You can always use the ISP programmer to again write the bootloader to the microcontroller.


body:
ESP32-S2 (Wemos/Lolin S2 mini)
Arduino 2.1.1 on Windows 11

Hello,

Thank you for taking the time to read this post and for any assistance you can provide. I consider myself a newbie when it comes to the more advanced aspects of Arduino, such as hardware functions and 32-bit MCUs. I've spent the last three days working on this code segment from a much larger project, and have searched extensively online to accomplish a seemingly simple task. I hope I'm not wasting anyone's time by asking a question that may have been answered elsewhere in an LMGTFY.

My goal is to output two LED PWM channels using hardware timers to control the frequency and duty cycle of the strobing LEDs. Here are the specific requirements:

1. The LEDs need to be power-controlled (I've been using the `ledc()` function)
1. The LEDs should be able to be strobed at specific intervals within the range of 0 to 1kHz. I'm using hardware timers so blocking functions such as non-DMA SPI updates of the display does not interfere with the strobe.
1. The duty cycle of the strobe needs to be adjustable as a float percentage ranging from 0.01 to 99.99% uptime per cycle.

Unfortunately, I've encountered an issue where I can either (unreliably) time the strobe and duty cycle or (somewhat more reliably) control the PWM power modulation, but not both simultaneously. I've tried various combinations of timer bindings, ledc channels, timing libraries, ISR handling, and rewriting the code from scratch multiple times.

I apologize for the messy state of the code, as it has undergone numerous modifications, and I'm fried at looking at the code. I would greatly appreciate any assistance or pointers you can provide to help resolve this issue.

Thank you once again for your help!

```c+
#include <esp32-hal-timer.h>

// Pin assignments
#define LED_660    17
#define LED_850    16

// Intensity control variables (percentage)
int pwr_850 = 0;
int pwr_660 = 0;

// Strobe control variables
float led_hz = 1.0;   // Strobe cycles per second
float led_duty = 50.0;    // Duty cycle percentage

// Timing variables
volatile unsigned long on_time;
volatile unsigned long off_time;

hw_timer_t *timer_on = NULL;
hw_timer_t *timer_off = NULL;

bool leds_on = false;  // Flag to track the state of LEDs

void IRAM_ATTR onTimer() {
  ledcWrite(2, 254);
  ledcWrite(3, 254);
  timerAlarmDisable(timer_off);
  timerAlarmWrite(timer_on, on_time, true);
  timerAlarmEnable(timer_on);
}

void IRAM_ATTR offTimer() {
  ledcWrite(2, 0);
  ledcWrite(3, 0);
  timerAlarmDisable(timer_on);
  timerAlarmWrite(timer_off, off_time, true);
  timerAlarmEnable(timer_off);
}

void startLEDs() {
  ledcSetup(2, 4000, 8);  // 4 kHz PWM, 8-bit resolution
  ledcSetup(3, 4000, 8);  // 4 kHz PWM, 8-bit resolution
  ledcAttachPin(LED_660, 2);
  ledcAttachPin(LED_850, 3);
  if (led_hz == 0) {
    ledcWrite(2, (pwr_660 / 100.0) * 255);
    ledcWrite(3, (pwr_850 / 100.0) * 255);
    leds_on = true;
  }
  else if (!leds_on && led_hz > 0.0) {
    // Calculate on/off times based on strobe parameters
    unsigned long cycle_time = 1000000.0 / led_hz;  // Convert Hz to microseconds
    off_time = ((cycle_time * led_duty) / 100);
    on_time = (cycle_time - off_time);

    // Update timer alarms
    timerAlarmWrite(timer_on, on_time, true);
    timerAlarmWrite(timer_off, off_time, true);

    // Enable timers
    timerAlarmEnable(timer_on);
    timerAlarmEnable(timer_off);  // Enable this at the same time as timerOn
    leds_on = true;
  }
}

void stopLEDs() {
  if (leds_on) {
    ledcWrite(1, 0);
    ledcWrite(0, 0);
    timerAlarmDisable(timer_on);
    timerAlarmDisable(timer_off);
    leds_on = false;
  }
}

void setup() {
  pinMode(LED_660, OUTPUT);
  pinMode(LED_850, OUTPUT);
  pinMode(15, OUTPUT);

  // Create timers
  timer_on = timerBegin(0, 80, true);  // Timer 0, prescaler 80 (1MHz)
  timer_off = timerBegin(1, 80, true);  // Timer 1, prescaler 80 (1MHz)

  // Attach interrupts
  timerAttachInterrupt(timer_on, &onTimer, true);
  timerAttachInterrupt(timer_off, &offTimer, true);
}

void loop() {
  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 1);
  led_hz = 1;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 0);
  led_hz = 2;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 1);
  led_hz = 5;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();

  pwr_850 = 30;
  pwr_660 = 30;
  digitalWrite(15, 0);
  led_hz = 10;   // Strobe cycles per second
  led_duty = 50;
  startLEDs();
  delay(5000);
  stopLEDs();
}
```

title: ESP32 trouble with running ledcWrite inside of ISR

Answers: 0


body:
I've just started playing around with a NodeMcu V3 and a [BME280 sensor][1].

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

wiring

    VCC -> 3.3V
    GND -> GND
    SCL -> D1 (GPIO5)
    SDA -> D2 (GPIO4)

I've tried this sketch /  I2C scanner: it finds the BME280 at 0x76

    #include <Wire.h>

    // Set I2C bus to use: Wire, Wire1, etc.
    #define WIRE Wire

    void setup() {
      WIRE.begin();

      Serial.begin(9600);
      while (!Serial)
         delay(10);
      Serial.println("\nI2C Scanner");
    }

    void loop() {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        WIRE.beginTransmission(address);
        error = WIRE.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknown error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(5000);           // wait 5 seconds for next scan
    }

Then I've tried library BMx280I2C into this sketch:

    #include <Wire.h>
    #include <BMx280I2C.h>

    BMx280I2C bmx280(0x76);

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

      // Setup BMx280
      Wire.begin();
      bmx280.begin();
      bmx280.resetToDefaults();
      bmx280.writeOversamplingPressure(BMx280I2C::OSRS_P_x16);
      bmx280.writeOversamplingTemperature(BMx280I2C::OSRS_T_x16);
      bmx280.writeOversamplingHumidity(BMx280I2C::OSRS_H_x16);

    }

    void loop() {

      // T,P,H measurements
      bmx280.measure();

      do{
        delay(100);
        Serial.println("No value, yet!");
      } while (!bmx280.hasValue());

      Serial.print("Pressure ");
      Serial.println(bmx280.getPressure());

      Serial.print("Temperature ");
      Serial.println(bmx280.getTemperature());

      Serial.print("Humidity ");
      Serial.println(bmx280.getHumidity());

      delay(1000);

    }

the output is always and only:

>     -> No value, yet!
>     -> Pressure nan
>     -> Temperature nan
>     -> Humidity nan

Why? How can I understand the origin of the problem?Thanks!

  [1]: https://www.ebay.it/itm/173602844579?mkcid=16&mkevt=1&mkrid=711-127632-2357-0&ssspo=zP2vxbj4Rpe&sssrc=4429486&ssuid=P9XaWv98RhG&var=&widget_ver=artemis&media=COPY
  [2]: https://i.stack.imgur.com/t7Uqi.png

title: NodeMcu V3 & BMe280 -> Temperature, Humidity, Pressure: value nan

Answers: 1

body:
Solved with [Adafruit library][1]

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define SEALEVELPRESSURE_HPA (1013.25)

    Adafruit_BME280 bme;

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

      if (!bme.begin(0x76)) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      }
    }

    void loop() {
      Serial.print("Temperature = ");
      Serial.print(bme.readTemperature());
      Serial.println(" *C");

      Serial.print("Humidity = ");
      Serial.print(bme.readHumidity());
      Serial.println(" %");

      Serial.print("Pressure = ");
      Serial.print(bme.readPressure() / 100.0F);
      Serial.println(" hPa");

      Serial.print("Approx. Altitude = ");
      Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
      Serial.println(" m");

      Serial.println();

      delay(2000);
    }

  [1]: https://www.arduino.cc/reference/en/libraries/adafruit-bme280-library/


body:
I can store and restore my data with avr/eeprom.h if I don't change the sketch.

 1. I have a sketch that stores the data. After power cycle of the device the data are fine.
 2. If I change the sketch with Serial.print statements (I want to re-read the data on-screen) the sketch seeks the data in wrong addresses of EEPROM, although I can verify with another sketch that the data are fine.

More detailed: I store around 50 bytes, but I verified the location for only the 4 bytes variable. I can see that this variable is at the start of the EEPROM (address: 0). But the second sketch seeks the data on address 30. Not even close.

To my understanding avr/eeprom.h is more easy to use since you don't need to police the location of data. But it seems that if change (what?) in your sketch it seeks the data on other locations although on eeprom are fine.

In other words, it's like if I change the firmware (not the EEMEM variables / definitions!), that firmware seeks the data on different places.

I understood something wrong?

In my situation is better to use the arduino EEPROM.h with static location of EEPROM addresses?

Fun fact. Google Bard seems it got it completely wrong:
>What are the differences of avr/eeprom.h and EEPROM.h from arduino?

(Google Bard Answer)

>The avr/eeprom.h and EEPROM.h libraries in Arduino are both used to access the EEPROM memory on AVR microcontrollers. However, there are some key differences between the two libraries.
>avr/eeprom.h is a lower-level library that provides direct access to the EEPROM registers. This means that it can be used to access any location in the EEPROM, but it also requires more code and can be more error-prone.
>EEPROM.h is a higher-level library that provides a more user-friendly interface to the EEPROM. It only allows you to access addresses that are within the range of the EEPROM, but it is easier to use and less error-prone.
>In general, avr/eeprom.h should only be used if you need to access specific locations in the EEPROM that are not within the range of EEPROM.h. Otherwise, EEPROM.h is the preferred library to use.

Edit: avr-objdump of eeprom section

| Prints on Sketch | Without prints | Prints both on Library and Sketch |
|------------------|-------------------|----------------|
|00810000 <eeprom_lw_dev_nonce>:| 00810000 <eeprom_lw_f_nwk_s_int_key>:| 00810000 <eeprom_lw_dev_addr>:|
|00810002 <eeprom_lw_f_nwk_s_int_key>:| 00810010 <eeprom_lw_s_nwk_s_int_key>:| 00810004 <eeprom_lw_dev_nonce>:|
|00810012 <eeprom_lw_s_nwk_s_int_key>:| 00810020 <eeprom_lw_has_joined>:| 00810006 <eeprom_lw_f_nwk_s_int_key>:|
|00810022 <eeprom_lw_join_nonce>:| 00810021 <eeprom_lw_dev_nonce>:| 00810016 <eeprom_lw_s_nwk_s_int_key>:|
|00810026 <eeprom_lw_has_joined>:| 00810023 <eeprom_lw_join_nonce>:| 00810026 <eeprom_lw_nwk_s_enc_key>:|
|00810027 <eeprom_lw_tx_frame_counter>:| 00810027 <eeprom_lw_tx_frame_counter>:| 00810036 <eeprom_lw_app_s_key>:|
|00810029 <eeprom_lw_rx_frame_counter>:| 00810029 <eeprom_lw_nwk_s_enc_key>:| 00810046 <eeprom_lw_has_joined>:|
|0081002b <eeprom_lw_nwk_s_enc_key>:| 00810039 <eeprom_lw_rx_frame_counter>:| 00810047 <eeprom_lw_rx_frame_counter>:|
|0081003b <eeprom_lw_app_s_key>:| 0081003b <eeprom_lw_app_s_key>:| 00810049 <eeprom_lw_tx_frame_counter>:|
|0081004b <eeprom_lw_dev_addr>:| 0081004b <eeprom_lw_dev_addr>:| 0081004b <eeprom_lw_rx2_data_rate>:|
|0081004f <eeprom_lw_rx2_data_rate>:| 0081004f <eeprom_lw_rx1_delay>:| 0081004c <eeprom_lw_rx1_data_rate_offset>:|
|00810050 <eeprom_lw_rx1_data_rate_offset>: |00810050 <eeprom_lw_rx2_data_rate>:| 0081004d <eeprom_lw_join_nonce>:|
|00810051 <eeprom_lw_rx1_delay>:| 00810051 <eeprom_lw_rx1_data_rate_offset>:| 00810051 <eeprom_lw_rx1_delay>:|

Image kept for historical reasons.

1st window: Serial.print(s) only in sketch.
2nd window: without Serial.print(s)
3rd window: Serial.print(s) both on sketch and library.
[![EEMEM from avr-objdump -D][1]][1]

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

title: How EEMEM maps the variables? (avr/eeprom.h)

Answers: 2

body:
I managed to reproduce your issue with the simple sketch below:

```c++
#include <avr/eeprom.h>

EEMEM uint8_t int8_ee;
EEMEM uint16_t int16_ee;
EEMEM uint32_t int32_ee;
EEMEM char str_ee[40];

void show(const char *name, void *address)
{
    Serial.print(name);
    Serial.print(": ");
    Serial.println((uint16_t) address);
}

void setup() {
    Serial.begin(9600);
    show("int8_ee", &int8_ee);
#ifdef SWAP_PRINTING_VARS
    show("int32_ee", &int32_ee);
    show("int16_ee", &int16_ee);
#else
    show("int16_ee", &int16_ee);
    show("int32_ee", &int32_ee);
#endif
    show("str_ee", str_ee);
}

void loop(){}
```

As is, it prints:

    int8_ee: 46
    int16_ee: 44
    int32_ee: 40
    str_ee: 0

If I `#define SWAP_PRINTING_VARS`, it prints instead:

    int8_ee: 46
    int32_ee: 42
    int16_ee: 40
    str_ee: 0

I have no proper answer to your question. Although one may try to unveil
the linker's reasoning, I believe it is safer to just assume that the
way these variables are allocated is unpredictable, and unstable between
subsequent versions of the program.

For your specific issue, I suggest you allocate _only one_ variable to
EEMEM: put everything you need in a single `struct`, and allocate that
as a whole. I am quite confident it will always end at address zero.
This should be robust against changes in the program provided that, if
you ever add extra fields to that `struct`, you add them at the end.

body:
I wouldn't rely on the compiler necessarily allocating variables at any particular memory address, especially after what you posted. You can make a little include file that simplifies reading from/writing to EEPROM, as below:

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

    #include <Arduino.h>  // for type definitions
    #include <EEPROM.h>

    template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
    {
        const byte* p = (const byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         EEPROM.write(ee++, *p++);
        return i;
    }

    template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
    {
        byte* p = (byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         *p++ = EEPROM.read(ee++);
        return i;
    }

Then you can do something like this:

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

    int someData;  // declare a local variable

    ...

    EEPROM_readAnything (0, someData);  // read into it, from address zero in EEPROM

    ...

    someData++;
    EEPROM_writeAnything (0, someData);  // write it back out, to address zero

The library above uses templates to manage any size data, so you can write or write ints, arrays, etc. One possibility would be to make a struct and read/write the whole thing every time. That way you don't need to keep track of offsets (the whole struct could be written to address 0).

---

Here's an example of doing that, using `offsetof` to manage the offsets of individual fields inside your overall struct, the thing that is stored in the EEPROM.

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

    #include <EEPROMAnything.h>

    const long MAGIC_ID = 'Nick';

    // information in EEPROM
    typedef struct {
        unsigned long magic;   // to see if we initialised EEPROM
        unsigned long counter;
        char myName [30];
    }  myInformation;

    void setup() {
      Serial.begin (115200);
      Serial.println ("Starting ...");

      // see if EEPROM initialised

      unsigned long magicTest;
      EEPROM_readAnything (offsetof (myInformation, magic), magicTest);

      if (magicTest != MAGIC_ID)
        {
        Serial.println ("Initialising EEPROM");
        myInformation initStuff;
        initStuff.magic = MAGIC_ID;
        initStuff.counter = 0;
        strcpy (initStuff.myName, "Nick Gammon");
        EEPROM_writeAnything (0, initStuff); // write whole struct
        } // end of if not initialised

      // find counter
      unsigned long myCounter;
      EEPROM_readAnything (offsetof (myInformation, counter), myCounter);
      Serial.print ("Counter is ");
      Serial.println (myCounter);

      // find name
      char hisName [sizeof (myInformation().myName)];
      EEPROM_readAnything (offsetof (myInformation, myName), hisName);
      Serial.print ("Name is ");
      Serial.println (hisName);

      // add to counter
      myCounter++;

      // write counter back
      EEPROM_writeAnything (offsetof (myInformation, counter), myCounter); // write whole struct

      Serial.println ("Done.");

    } // end of setup

    void loop()
    {
      // whatever
    }   // end of loop


body:
I have been using https://wokwi.com/ to learn Arduino and I am having a problem that seems to be happening no matter what I do. I am trying to set up a push button and an LED. The end goal here is to set it up so that when I tap the push button down and release it that the LED blinks like a turn signal in a car. When I push it down and release it again, the LED should stop blinking. I have tried tons of different code, even using code copied and pasted directly from Arduino's website. What ends up happening is that the button is unreliable. Sometimes the button will click, other times it won't register. It is very bizarre behavior. I read about the bouncing effect but any code I put in to ignore bouncing doesn't seem to have any effect on the system. Why are push buttons so unreliable? I know in real life they aren't because I am able to type this using presumably push buttons on my keyboard. What am I doing wrong??

Here is an example. The push button is totally unpredictable. Why is it behaving like this?

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

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

    int state = 0;

    void setup()
    {
      pinMode(9, OUTPUT);
      pinMode(6, INPUT);
    }

    void loop()
    {
      if (digitalRead(6)) {
        state = !state;
      }
      digitalWrite(9, state);
    }

title: Push button issues

Answers: 1

body:
You've got the button wired wrong.  Your resistor is inline with the signal going to the pin.  It should be going from the pin to 5V.  The button should be wired directly to the pin and ground.  Or you can use INPUT_PULLUP in pinMode instead of INPUT and eliminate the resistor entirely.

Your code should test for the button pin being LOW, not HIGH.  When you press the button it will read LOW.  When unpressed it will read HIGH.  This is the normal way that buttons are wired up.

Also note that your loop() function will repeat thousands of times per second.  As long as you still have your finger on the button it will keep cycling the state.  That means that every time you press the button, the state gets cycled a few tens of thousands of times and there's no real way of knowing which state it will be on when you finally get your finger off the button.

You should look at the "State Change Example" in the Arduino IDE.  It shows how to keep track of the previous state of the button so you can react once to each press.


body: I am not interested into the AnalogRead() part, but rather on how he converts 5 or 2 V into a number between 0 and 1023. How does it practically do it to convert the voltage level into a number or into bits to then send to the processor? Thanks in advance

title: How does actually arduino measure voltage?

Answers: 2

body:
The Arduino Uno is powered by an ATmega328P microcontroller. According
to [the datasheet][]:

> The ATmega48A/PA/88A/PA/168A/PA/328/P features a 10-bit successive
> approximation ADC.

On the next page, you can see the following schematic, where I have
highlighted the most essential parts of the converter. You can see the
DAC, the comparator, and the SAR data register.

[![Schematic of the ADC of the ATmega328P][1]][1]

If you want to get into the details of how this works, see the Wikipedia
article on [Successive-approximation ADC][w]. You may notice the
schematic at the top of that Wikipedia page is somewhat similar to the
one above.

[the datasheet]: https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738665
[w]: https://en.wikipedia.org/wiki/Successive-approximation_ADC
[1]: https://i.stack.imgur.com/r7qpu.png

body:
The ATmega328P features a 10-bit successive approximation ADC. The ADC is connected to an 8-channel Analog Multiplexer.

[![ADC schematic][1]][1]

First, an input is selected from the multiplexer on the left. This allows any of 8 input channels to be active at one time (but only one). These are: A0 to A5 on the Uno (some boards also have A6 and A7). There are also additional input channels (not shown) which also allows the selection of:

* The internal temperature sensor
* Ground
* Bandgap reference voltage

The input channel (multiplexer output) is connected to a "sample and hold" capacitor, as shown. Once an analog conversion starts the switch is opened after 1.5 ADC cycles (12 µs with the default prescaler of 128) so that the capacitor retains its current reading (ie. it holds it) so that the input voltage can now change without affecting the result. This would be useful for fast-changing signals, as the whole conversion can take 104 µs (depending on the prescaler).

To work out the voltage the logic applies the analog reference voltage (ARef) divided down by a DAC (digital-to-analog converter) under the control of the ADC logic. The output of the DAC is sent to the comparator which determines if the input voltage is higher or lower than the reference voltage, at its current divided state. For example, the high-order bit would be set or cleared by setting the DAC to divide the reference voltage by 2 (ie. 2.5V if ARef is 5V). If the input is higher than 2.5V then the high-order bit in the result is set. This takes one ADC cycle (8 µs at the default prescaler of 128 with a 16 MHz processor clock).

To get the next result bit the DAC would be set to the next step (ie. 0.25 of ARef or 0.75 of ARef depending on whether the first bit was set or not) and another comparison done. This process is repeated for all 10 bits.

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


body:
I am trying to make an LED clock using DS3231 to keep track of time, but for some reason, it's not keeping time when Arduino is turned off. I tried to disconnect the clock from a power source for 5 minutes, and when I powered it back on, the clock picks up the time it was displaying before powering off. I thought the battery I was using at first ran out, and so I replaced it with a new one, but the issue persist. Then I read that it could be that I am using the non-rechargeable one, and to fix this, I removed some resistors and diodes to turn off the charging function, but that also didn't fix the issue. At this point, I'm not sure if this is more on hardware or software issue that the clock is not keeping count of time when Arduino is turned off. It could be that the module I bought was the cheap knockoff, which doesn't function like it should, so I ordered a better one.

I'll the provide the snippet of codes I used:
```
#include <RTClib.h>
#include <Wire.h>

RTC_3231 rtc;

int hoursNow;
int minutesNow;
int secondsNow;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
//  rtc.adjust(DateTime(2023, 6, 31, 14, 21, 0));
}

void loop() {
  DateTime now = rtc.now();
  hoursNow = now.hour();
  minutesNow = now.minute();
  secondsNow = now.second();
  Serial.print(hoursNow);
  Serial.print(":");
  Serial.print(minutesNow);
  Serial.print(":");
  Serial.print(secondsNow);
  delay(1000);
}

```
Maybe I'm missing something on the code that is causing it to not do the way I wanted it to do, but I've looked online, and most were pretty similar to the code I have.

title: DS3231 Not Matching Up Time when Arduino is Turned Off

Answers: 1

body:
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

You have this line in setup that sets the date and time to the date and time that the code was compiled.  That's fine to set it once, but that time never changes.  It's the time that it was when you compiled the code.  So every time it runs, you are setting the time back to this.  The RTC keeps the time running while the Arduino is off, but as soon as it's turned on your code sets it back to what it was before.

If you remove that line, then things will work the way you want.  You might need to load a sketch once with a line like this to set the time, run it once, then load a new sketch without that line.  Or include a routine in your code to allow a user to set the time.


body:
I am using **DEVKIT V1 DOIT board** and **30 pinout board**.

When I upload this code for checking analog value from serial monitor:

        // Define the analog input pin for the IR sensor
    const int analogPin = 13;

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

    void loop() {
      // Read the analog value from the IR sensor
      int sensorValue = analogRead(analogPin);

      // Display the analog value in the Serial Monitor
      Serial.print("Analog Value: ");
      Serial.println(sensorValue);

      // Add a short delay to avoid rapid readings
      delay(500);
    }

it came just normally fine.

But when I upload this code:

    #include <WiFi.h>
    #include <HTTPClient.h>

    const char* ssid = "JANINA";
    const char* password = "sayma01720";
    const char* websiteURL = "http://192.168.1.105:4747/araf/phploginscript-master/sense_value.php?uid=56"; // Replace with your website URL

    const int analogPin = 19;

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
      }
      Serial.println("Connected to WiFi");
    }

    void loop() {
      int sensorValue = analogRead(analogPin);
      Serial.print("Analog Value: ");
      Serial.println(sensorValue);

      // Prepare the temperature to be sent
      String temperature = "temperature=" + String(sensorValue);

      WiFiClient client;
      HTTPClient http;

      bool success = http.begin(client, websiteURL);
    if (!success) {
      Serial.println("Could not connect to the server");
      return;
    }

      // Set content type to application/x-www-form-urlencoded
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");

      int httpResponseCode = http.POST(temperature);

      if (httpResponseCode > 0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String response = http.getString();
        Serial.println(response);
      } else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }

      http.end();

      // Wait for some time before sending the next temperature
      delay(2000);
    }

It stop read analog value.
This was the result shown in serial monitor,

> `Analog Value: 0 HTTP Response code: 200`

Please help me SIR.

title: DEVKIT V1 DOIT 30 pinout board could not read analog value when using wifi library

Answers: 0


body:
I'm having an issue where anytime I run a program such as the SD card read write example (Below) the COM port disconnects. The only changes I have made to the example code is I am using SPI1 instead of SPI0 so the pins changed.

When the COM disconnects it comes back about 20 seconds later with an error message in its properties window

"Windows has stopped this device because it has reported problems. (Code 43)

A request for the USB device descriptor failed."

Additionally I am suspicious of these lines through isolating them, if I remove all lines relating to SPI the code doesn't fail and I don't have the COM issue. (though the SD card obviously doesn't work)
```
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);
```
Thanks!
-Rian
```
/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
   ** MISO - pin 4
   ** MOSI - pin 7
   ** CS   - pin 5
   ** SCK  - pin 6

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

// This are GP pins for SPI0 on the Raspberry Pi Pico board, and connect
// to different *board* level pinouts.  Check the PCB while wiring.
// Only certain pins can be used by the SPI hardware, so if you change
// these be sure they are legal or the program will crash.
// See: https://datasheets.raspberrypi.com/picow/PicoW-A4-Pinout.pdf
const int _MISO = 16;
const int _MOSI = 15;
const int _CS = 17;
const int _SCK = 14;

#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  Serial.print("Initializing SD card...");

  // Ensure the SPI pinout the SD card is connected to is configured properly
  SPI.setRX(_MISO);
  SPI.setTX(_MOSI);
  SPI.setSCK(_SCK);

  if (!SD.begin(_CS)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}
```

title: COM disconnects and program fails when including code trying to initialize SD card (RP2040 Pi Pico W running Arduino)

Answers: 0