message:
http request in time intervals

I'm doing a program that receives data from a web page every so often, but only receives the data once and then receives everything blank. I need help to receive the data every time indefinitely. I am using arduino uno with arduino etherner shield

My code:

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress ip(192, 168, 0, 177);
    EthernetClient client;

    int REDLed= 2;
    int GREENLed= 3;
    int BLUELed= 4;

    void setup()
    {
      pinMode(REDLed, OUTPUT);
      pinMode(GREENLed, OUTPUT);
      pinMode(GREENLed, OUTPUT);
      Ethernet.begin(mac, ip);
      Serial.begin(9600);
      Serial.println("power up" );
      delay(3000);
    }

    void loop()
    {
      Serial.println("SubmitHttpRequest - started" );
      SubmitHttpRequest();
      Serial.println("SubmitHttpRequest - finished" );
      delay(10000);
    }

    void SubmitHttpRequest()
    {
      if (client.connect(server, 80))
      {
        Serial.println("connected");
        client.println("GET /arduino/getstate.php?color=All HTTP/1.1");
        client.println("Host: cybertodo.mx");
        client.println("Connection: close");
        client.println();
      }
      else
      {
        Serial.println("connection failed");
      }
      delay(100);
      changeLed();
    }

    void changeLed()
    {
      String content = "";
      Serial.println(client.available());
      while(client.available()!=0)
      {
        content = content + String(char (client.read()));
      }
      Serial.println(content);
      if(content.substring(30,31)== "1")
      {
        digitalWrite(REDLed, HIGH);
      }
      else if (content.substring(30,31)== "0")
      {
        digitalWrite(REDLed, LOW);
      }

      if(content.substring(31,32)== "1")
      {
        digitalWrite(GREENLed, HIGH);
      }
      else if (content.substring(31,32)== "0")
      {
        digitalWrite(GREENLed, LOW);
      }

      if(content.substring(32,33)== "1")
      {
        digitalWrite(BLUELed, HIGH);
      }
      else if (content.substring(32,33)== "0")
      {
        digitalWrite(BLUELed, LOW);
      }
      content = "";
    }

body:
Immediately after making the request when reading client.available() will be 0 since no data was received yet so:

      while(client.available()!=0)
      {
        content = content + String(char (client.read()));
      }

Will never actually run. Try something like:

    unsigned long last = millis();
    String content = "";

    while(client.connected()) {
      int len = client.available();
      if(len > 0) {
        last = millis();

        char buff[len];
        for(int i = 0; i < len; i++) {
          buff[i] = client.read();
        }
        content += String(buff);

      } else {
        if(millis() - last > 2000) {
          client.stop();
          return;
        }
        delay(1);
      }
    }

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.


sender: user

message:
DAC to play audio samples

I have a buffer which contains *16000 PCM* samples of *8Khz 8-bit mono*. I am trying to play it using *12 bit MCP4725 DAC*. I have tried using `micros()` to control the write interval for the DAC. Here's my code:

    uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
    long previousMicros = 0; // Sorry for missing this out!!

    void setup() {

    Serial.begin(115200);
    Wire.begin(D2, D1);
    delay(100); // delay 100 ms
    Serial.flush();
    delay(1000);

    }

    void value_write(uint16_t temp){

      Wire.beginTransmission(0x62);
      Wire.write(64);
      Wire.write(temp >> 4);        // the 8 most significant bits...
      Wire.write((temp & 15) << 4); // the 4 least significant bits...
      Wire.endTransmission();

    }

    void loop() {

      unsigned long currentMicros = micros();

    // 125 uS sampling for 8KHz signal
    if(currentMicros - previousMicros > 125) {
      Serial.print("Index: ");
      Serial.println(indx);
      uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

      value_write(temp);
    }

    }

The write should logically be completed within *2 seconds* but takes way more time. Any help regarding successfully writing the *PCM values to the DAC* at *8000Hz* is greatly appreciated.

sender: assistant

body: In your code, you never set or update `previousMicros` value.


body:
One sample takes 38 I2C clock cycles to write. That's:

    1 START
    7 Address
    1 R/W
    1 ACK
    8 Byte
    1 ACK
    8 Byte
    1 ACK
    8 Byte
    1 ACK
    1 STOP

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second *absolute maximum*.

You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second *absolute maximum*.  That would just about be do-able.

I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.

There's also the matter of the `map()` function which is just nasty in this situation. You can just bit-shift.

So besides just removing the Serial commands (which will slow things down massively) you should also:

1. Change the I2C clock to *at least* 400kHz
2. Change `map()` to `soundData[indx++] << 4`
3. Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.


message:
Battery life calculation using Nano, NRF24L01+ and window magnetic reed switch

I'm trying to make my own home wireless security system.  I will be using probably 3 AA batteries to power these devices.  My problem is that I need to know if the batteries will be enough to power the devices for at least 6 months.
Below are the details of all the devices I will be using:

1. Mini Nano V3.0 ATmega328P Microcontroller Board w/USB Cable For Arduino
2. Makerfire Arduino NRF24L01+ 2.4GHz Wireless RF Transceiver Module
3. uxcell MC 38 Mount Wired Door Window Sensor Magnetic Reed Switch Recessed

Below are some project requirements that might be useful:

1. For the Nano, I want to put it to sleep using delay(2000) in the loop() function.  The Nano will be the one checking the window sensor.
2. I will be using a project enclosure of about 4X4 inches.

If this will not be possible maybe someone knows of other devices that use less power that will be more suitable for this project? I would prefer something easy to use like Arduino Nano with USB so I can easily program it.

EDIT: sorry but I just like to add that from the main HUB component, I would like to check the status of the window sensor if it is open/closed.  This will be useful if there is an open window/door around the house when going to sleep. Probably the Nano will broadcast its current window sensor status to the main HUB program. Thanks.

body:
You should use interrupts for the reed switch and then put the microcontrolller into sleep for a keep alive interval. Your master device should check that the sensor is still active and set off the alarm if its not. You would also want to allow for a battery low condition that might disable the alarm for convince. This still should keep the power consumption low.

The nano is roughly 1mA @ 3.3v while the CPU is running and 72uA when its in sleep. Discounting power consumption in the alarm condition triggered by the interrupt using an interval of 9 seconds using delay or interrupt timers then average consumption then about a second to wake up and send a keep alive over the RF. (0.000072 * 9 + 0.001 * 1) / 10 = 0.0001648 amps. (average over 10 second duty cycle)

My guesstimate of your RF power consumption without knowing what kind of protocol would be somewhere around 128 bytes per transmission taking about 90ms. (0.0001 * 9910 + 0.015 * 90) / 10,000 = 0.0002341 amps.

Total of their averages is: 0.0003989 or 398.9uA.

Alkaline AA cells vary widely. So instead based on some Ni-MH with 2400mAh per cell and 1.2v

3 cells would be 3.6v so you'll "get" most of the mAhs out of the batteries.

2400mAh = 2400000uAh

2400000uAh / 398.9uA ~= 6016.54 hours or 250 days or 8 months.

Power consumption were intentional overestimates. You should be able to make it last a lot longer.

https://www.avrprogrammers.com/howto/atmega328-power
http://harizanov.com/2013/05/nrf24l01-power-consumption-footprint/


body: It only seems to do one thing: activate an alarm if the reed switch changes.  Power the system _through_ the reed switch. It will have zero standby current and the battery will last the shelf life. That said, you might be able to use an RF module w/o even a MCU, though not that particular one...


body: You should use a reed switch that is both NC and NO. Then power only the disconnected part of the switch and listen to pin changes and put everything into sleep. This can improve your power consumption. See the answers postet here: [Low Power Pin Change Detection](https://arduino.stackexchange.com/questions/34067/low-power-pin-change-detection-attiny)


message:
FastLED + structs + PROGMEM strange behavior

I'm afraid I have to post a lengthy bit of code, because I can't pinpoint what's causing my issues – in short, it appears **repeatedly** adding `float position + float speed` in a struct ends up borking the whole thing.

The purpose of the code is to animate at most `MAX_PARTICLES` particles ("pixels") traveling at random speeds across the LED stripe.

The array named `particles` stores the current list of particles being managed. Each particle in the array is stored as a struct, as defined at the beginning of the code. Particles are added to the array using function `addParticle()` at the very end of the code. Particles which reach the end of the stripe are killed in the second part of the `loop()` function (after `FastLED.show()`).

Here's the code:

    #define FASTLED_INTERNAL // Eliminates a compiler warning
    #include <FastLED.h>
    #include <colorutils.h>
    #define NUM_LEDS 149
    #define DATA_PIN 6
    #define MAX_PARTICLES 5 // This uses up the memory, mostly
    CRGB leds[NUM_LEDS];

    struct particle {
      float position;
      CRGB color;
      float speed;
      int id;
    };
    typedef struct particle Particle;
    Particle particles[MAX_PARTICLES];
    int numParticles = 0;
    int maxId = 0;

    // Gramma correction tables (Defalt Gamma = 2.8)
    const uint8_t PROGMEM gammaR[] = {
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,
        2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,
        5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,
        9,  9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14,
       15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
       23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33,
       33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46,
       46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
       62, 63, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75, 76, 78, 79, 80,
       81, 83, 84, 85, 87, 88, 89, 91, 92, 94, 95, 97, 98, 99,101,102,
      104,105,107,109,110,112,113,115,116,118,120,121,123,125,127,128,
      130,132,134,135,137,139,141,143,145,146,148,150,152,154,156,158,
      160,162,164,166,168,170,172,174,177,179,181,183,185,187,190,192,
      194,196,199,201,203,206,208,210,213,215,218,220,223,225,227,230 };

    const uint8_t PROGMEM gammaG[] = {
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
        2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,  5,  5,
        5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9, 10,
       10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
       17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
       25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
       37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
       51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
       69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
       90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
      115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
      144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
      177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
      215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };

    const uint8_t PROGMEM gammaB[] = {
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,
        2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,
        4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  6,  6,  7,  7,  7,  8,
        8,  8,  8,  9,  9,  9, 10, 10, 10, 10, 11, 11, 12, 12, 12, 13,
       13, 13, 14, 14, 15, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19,
       20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28,
       29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40,
       40, 41, 42, 43, 44, 44, 45, 46, 47, 48, 49, 50, 51, 51, 52, 53,
       54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70,
       71, 72, 73, 74, 75, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89,
       90, 92, 93, 94, 96, 97, 98,100,101,103,104,106,107,109,110,112,
      113,115,116,118,119,121,122,124,126,127,129,131,132,134,136,137,
      139,141,143,144,146,148,150,152,153,155,157,159,161,163,165,167,
      169,171,173,175,177,179,181,183,185,187,189,191,193,196,198,200 };

    void setup() {
      FastLED.addLeds<WS2812B, DATA_PIN, BGR>(leds, NUM_LEDS);
      randomSeed(analogRead(0));
      Serial.begin(115200);
    }

    void loop() {
      if (numParticles < MAX_PARTICLES && random(10)>8) {
        addParticle();
      }

      for (int i=0; i<numParticles; i++) {
        // Antialiasing
        int basePosition = floor(particles[i].position);
        byte percentOnePos = round(255 * (particles[i].position-basePosition));
        byte percentBasePos = 255 - percentOnePos;
        CRGB color0 = particles[i].color % percentOnePos;
        CRGB color1 = particles[i].color % percentBasePos;

        leds[basePosition] += color0;
        leds[basePosition+1] += color1;
      }

      // Apply gamma correction
      for (int i=0; i<NUM_LEDS; i++) {
        //leds[i] = applyGamma_video(leds[i], 2.2);
        // *** applyGamma_video(2.2) pros and cons:
        // PROs: smoother color transitions
        // CONs: much slower; much worse color calibration
        // TODO: pre-render custom, color calibrated gamma tables

        leds[i].red = pgm_read_byte(&gammaR[leds[i].red]);
        leds[i].green = pgm_read_byte(&gammaG[leds[i].green]);
        leds[i].blue = pgm_read_byte(&gammaB[leds[i].blue]);
      }

      FastLED.show();

      for (int i=0; i<numParticles; i++) {
        int basePosition = floor(particles[i].position);
        leds[basePosition] = CRGB::Black;
        leds[basePosition+1] = CRGB::Black;
        particles[i].position += particles[i].speed;
        if (particles[i].position > (NUM_LEDS+1)) { // We want to render it fading out
          for (int j = i; j<numParticles-1; j++) {
            particles[j] = particles[j+1];
          }
          numParticles--;
          i--; // We want the for() cycle to process the particle we shifted down
        }
      }
      debugParticles();
    }

    void debugParticles()
    {
      for (int i = 0; i<MAX_PARTICLES; i++) {
        if (i>0) {
          Serial.print(", ");
        }

        Serial.print(i);
        Serial.print(",");
        Serial.print(particles[i].id);
        Serial.print(",");
        Serial.print(particles[i].position);
      }
      Serial.println("");
    }

    void addParticle()
    {
      particles[numParticles].color = CHSV(random8(),255,150);
      particles[numParticles].position = 0;
      particles[numParticles].speed = (0.0+random(10))/100+0.01;
      particles[numParticles].id = maxId++;
      numParticles++;
    }

For debugging purposes, each unique particle ever created has a unique ID. The debugging output contains the following fields:

- [0] the array index for the first entry in the array (always 0)
- [1] the unique ID of the particle stored in the first record of the array
- [2] the position of the particle stored in the first record of the array
- [3] the array index for the second entry in the array (always 1)
- [4] the unique ID of the particle stored in the second record of the array
- [5] the position of the particle stored in the second record of the array
- (and so on – three fields for each record in the particles array)

Finally, here's an interesting excerpt from the output, after ~1,500 records:

    0 0 30.36 1 1 30.28 2 2 147.70 3 3 59.04 4 4 73.15
    0 0 30.38 1 1 30.30 2 2 147.80 3 3 59.08 4 4 73.20
    0 0 30.40 1 1 30.32 2 2 147.90 3 3 59.12 4 4 73.25
    0 0 30.42 1 1 30.34 2 2 148.00 3 3 59.16 4 4 73.30
    0 0 30.44 1 1 30.36 2 2 148.10 3 3 59.20 4 4 73.35
    0 0 8.00 1 1 30.38 2 2 148.20 3 3 59.24 4 4 73.40
    0 0 8.00 1 1 30.40 2 2 148.30 3 3 59.28 4 4 73.45
    0 0 8.00 1 1 30.42 2 2 148.40 3 3 59.32 4 4 73.50
    0 0 8.00 1 1 30.44 2 2 148.50 3 3 59.36 4 4 73.55
    0 0 8.00 1 1 30.46 2 2 148.60 3 3 59.40 4 4 73.60
    0 0 8.00 1 1 30.48 2 2 148.70 3 3 59.44 4 4 73.65
    0 0 8.00 1 1 30.50 2 2 148.80 3 3 59.48 4 4 73.70
    0 0 8.00 1 1 30.52 2 2 148.90 3 3 59.52 4 4 73.75
    0 0 8.00 1 1 30.54 2 2 149.00 3 3 59.56 4 4 73.80
    0 0 8.00 1 1 30.56 2 2 149.10 3 3 59.60 4 4 73.85
    0 1 0.00 1 2 149.20 2 3 59.64 3 4 73.90 4 4 73.85
    0 1 0.00 1 2 149.30 2 3 59.68 3 4 73.95 4 4 73.85
    0 1 0.00 1 2 149.40 2 3 59.72 3 4 74.00 4 4 73.85

Notice how in all but the last three lines, the array index and the particle ID are still in sync (0=>0, 1=>1, 2=>2, 3=>3, 4=>4), which means no particles have died yet (new particles would have larger IDs). I'm trying to say that no particle re-assignment magic has happened yet – for now, we're just running the boring code which moves particles along the strip.

And yet, on the sixth line in the output, the first particle's position becomes mangled – notice how on the first five lines the first particle's position has steadily increased by 0.02 (presumably that particle's speed) up to 30.44, whereas on the sixth line it inexplicably becomes 8.00 (other times I experimented, it becomes 32.00). Not only that, but that 8.00 (the particle's position) never increases again, and three lines from the bottom the code also decides to kill the first particle altogether (notice that the second column becomes 1, which means the first record in the particles array now stores the particle with unique ID 1, instead of unique ID 0).

I have no idea what I'm doing wrong – I've been experimenting with this over and over, killing off all the bugs and warnings I could find, and still no luck.

body:
As you are keeping the particles over the position 149 (because of fading), I'd expect overwritting the memory after the space allocated for the `leds` variable.

According to the log it started somewhere around position 148, which is earlier, but in your code is this:

    int basePosition = floor(particles[i].position);
    leds[basePosition] += color0;
    leds[basePosition+1] += color1;

So if you have position 148, you are already changing something after the array. It might add zero values in the color1 (for `148.0` and `148.1`) so it didn't changed anything but later the value gets nonzero and changes a wrong memory.


message:
ESP8266 SPIFFS file not found

I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.

In the set up, I refer to the following function to read the file:

    String readTemplatefile(){
      String retval ="";
      File fr = SPIFFS.open("/templatecfg.htm", "r");

      if(!SPIFFS.exists("/templatecfg.htm")){

        Serial.println("Template file not available ");
        }
        while (fr.available()){
            retval += char(fr.read());
          }

    fr.close();
    Serial.println("Template file = ");
    Serial.println(retval);
    return retval;
    }

I always get 'Template file not found'. I have

    SPIFFS.begin();

at the beginning of the setup function

My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.

Thanks in advance to any help.

body: SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.


message:
Undefined reference to stdlib (strtof) while compiling

I'm trying to run the AzureIoTProtocol_MQTT/esp8266 example, but I get linker errors:

> Archiving built core (caching) in:
> /var/folders/fj/y3vtrz597kv4885q1b_5qypr0000gn/T/arduino_cache_934614/core/core_esp8266_esp8266_d1_mini_CpuFrequency_80,UploadSpeed_921600,FlashSize_4M3M_e1e103f2055a19e071ac9522162e1787.a
> libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function `sscanfd':
> /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
> undefined reference to `strtoull'
> libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
> `sscanfllu':
> /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
> undefined reference to `strtoull'
> libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType_From_String+0xac):
> undefined reference to `strtof'
> libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
> `CreateAgentDataType_From_String':
> /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571:
> undefined reference to `strtof' collect2: error: ld returned 1 exit
> status

The issue can be broken down to the call to `strtof` function call. I get the same error with only this very simple code snippet:

    #include <stdlib.h>

    void setup() {
      char szOrbits[] = "686.97";
      float f;
      f = strtof (szOrbits, NULL);
    }

    void loop() {
    }

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.

body:
Its because the "strtof" function resides in "stdlib.h",
"Stdio.h" deals with i/o tasks.

Since you din't include you get that undefined reference error.
Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

>## Update1:
After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.

> Cite:
>
>1. https://www.arduino.cc/reference/en/language/variables/data-types/double/
>2. https://www.arduino.cc/reference/en/language/variables/data-types/float/

## Reason:
The size of the double and float is the same, ie: 4 bytes
and even if you use double its actually the float itself and wont gain any precision advantage.

##Solution:
Since the size of the double and the float is same there is not point in having two function definition doing the same job.
so

 1. **Use "strtod"  instead of "strtof"** or
 2. Define a macro **#define strtof(A, B) strtod(A, B)** in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".


body:
Its because you haven't added the core of esp8266 to the arduino IDE.
you are defaulting it to the "UNO" board and compiling it.
so you get that error for which i have explanation

here: https://arduino.stackexchange.com/a/48719/3557

solution for your problem is simple added the esp8266 core and select the right board and compile again.

Cite: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon

Follow above link and install the esp8266 core.


message:
Lifecycle hook in Arduino to know if Arduino is reset or powered down

I am new to Arduino programming and I'm really fascinated with its working. Is there a way to know if an Arduino is getting switched off or being reset? Like a function would be called before the Arduino gets switched off.

I want to detect this event *to preserve a value*, where a user resets his Arduino, or switches it off. Is it possible?

body:
You can read the `MCUSR` status register to determine the source of the reset.

Sources can be the Watchdog timer, brownout (too low a voltage), reset (button), or power-cycle.


body:
> EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.

However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.

A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.

Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

---

> Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

---

  > Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

---

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.


message:
Can I get the current connection speed with ESP8266?

Using an ESP8266 I can get the RSSI of the Wifi network using `Wifi.getNetworkInfo()` or `Wifi.RSSI()`. But is there a way to know the actual connection speed in Mbps, after joining successfully a WiFi network?

body:
Wifi modules decide on link speed based on signal strength. So you can estimate the link speed with signal strength, which you can get with `WiFi.RSSI(network)`.

[The datasheet](https://www.itead.cc/wiki/ESP8266_Serial_WIFI_Module) of ESP8266 contains a table mapping RSSI to link speed under "Sensitivity":

- -98 dBm: 1 Mbps
- -93 dBm: 6 Mbps
- -91 dBm: 11 Mbps
- -75 dBm: 54Mbps
- -71 dBm: 65Mbps, 72.2Mbps

Whenever these values are "minimum", "maximum" or "typical" remains unclear. These dBm limits are also quite low, which means the link speed will probably be capped by the other communication peer (your router). [Here](http://bpastudio.csudh.edu/fac/lpress/471/hout/wireless/wifipower.htm)'s the same table for a random D-link router, DI-624.


message:
Code for determining beats per min when timing a wooden clock

I'm new to Arduino and coding but I build wooden clocks.  The biggest problem is timing the clock to the correct beats per min when adjusting pendulum length.  I'm thinking Arduino and an IR sensor?? to detect when the pendulum breaks the beam, then displaying the beats per min real time would be possible.  If not real time then just beats in a variable time period, ie 1 min or 2 or 5 or 10 min.  I've looked for this type of code and circuit but haven't been able to find one.  Any help would sincerely be appreciated.

body:
I'd suggest to have the Arduino send a message to the PC when a 'tick' occurs. Then have the PC do the calculations over a larger number of ticks. You can even have the PC measure it's drift using NTP (PC clocks also aren't extremely accurate, but better that the crystal on the Arduino).

The procedure that I used, I found at https://www.logre.eu/wiki/Horloge_analogique_24h/en#Quartz_calibration I ran it for a few hours. Which might also be useful in your case to see if the swing is consistent.

I used this to calibrate my Arduino clock to within a few seconds per year,


body:
If the accuracy you require is about 1%, that should be doable with any
Arduino. Much higher accuracies would be hard to achieve because most
Arduinos are clocked off a ceramic resonator, and these have a frequency
tolerance of about 0.5%.

Given that your signal is very slow, the simplest approach may be to
poll the pin connected to the sensor and record the time (using
`micros()`) of the low → high transition. Then you can compute the
beat frequency as the inverse of the time between consecutive
transitions.

There is, however, the possibility that the sensor is not exactly in
the middle of the swing. Then, for better accuracy, I would measure the
time taken by _two_ beats, i.e. a full swing. This way the pssible
asymmetry will not affect the accuracy.


message:
How do I create a constant loop with an event that only occurs once?

I am currently working in void loop() and have setup a distance meter that constantly checks the distance.

Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?

    if (distance <= 150){
        personPresent();
        }

      if(distance > 150){
        personAbsent();
          }

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.

In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

body:
    static boolean didItAlready = false;

    if(distance > 50 && !didItAlready){
         doIt();
         didItAlready = true;
    }

You simply need a variable to keep track of whether or not it has been done.  If and when you want to do the action again then set your variable back to false.


body:
What you want is not to check the distance but to check that the distance condition changed.

    static boolean present = false;

Inside loop:

    if (present == false && distance <= 150){
        personPresent();
        present = true;
    } else if(present == true && distance > 150) {
        personAbsent();
        present = false;
    }


body:
You just need a global variable to track whether it is done or not like this...

    //  other Codes

    bool State=0;

    void setup(){

    // other Codes...

    }

    void loop(){

    if(distance <= 150 && State==0){

    personPresent(); // This function should get executed only once
    State=1;

    }else if(distance>150 && State==1){

    personAbsent(); // This sould also get executed once
    State=0;

    }

    }

The global boolean variable ''' State ''' will keep track of how and when the functions need to be executed once, whenever conditions are met. And the boolean variable changes everytime (distance AND Sate) the conditions are met triggering those functions once per bool update.


message:
VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a

I was working on a project build initialy from the Arduino IDE to program an attiny84a (without a bootloader) using the board from https://github.com/damellis/attiny

I got an atmel-ice recently and I was trying to debug the arduino sketch using it.

I installed AtmelStudio (because I know it has an GUI debugger) and found VisualMicro that should help me to compile arduino sketch.
Unfortunatly as soon as a set the project to debug I got a compilation error :

    'Serial' was not declared in this scope

(I don't have this error in Release mode).

My code doesn't use any serial (because I don't have any pin left), so this was wierd. I still tried to add the SoftwareSerial.h include (just in case) without success.

So I created an empty (I mean with only an empty setup() and loop() methods) and it throw the same error.

I tried to setup different versions of arduino IDE into VisualMicro (1.6.13, 1.8.1, 1.8.5 and 1.9 build 34) without success.

Then after a couple of hours I found the .cpp source generated by VisualMicro and it try to use the member "Serial" for some debugging reason.

I would like an easy way to integrate with arduino (all those library and easy to install library) and to be able to debug as well, what can I look for or do?

Thank

body:
    'Serial' was not declared in this scope

This error is not surprising when compiling for ATtiny84 because in Arduino `Serial` refers to the hardware serial port and ATtiny84 [doesn't have one](https://www.microchip.com/wwwproducts/en/ATtiny84).

But you didn't use `Serial` in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html

So in fact your sketch is attempting to use `Serial` without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.

Visual Micro does allow you to change the debugging output to software serial:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html

but since you say you have no pins available that may not be any help.


body:
I found how to disable the vMicro debugging, in AtmelStudio open the "vMicro" menu then click the "Debugger" item and make sure the option "Atmel Studio Debugger" is checked.

1) Change the optimization flag to a usefull state (-Og or -O0) in order to NOT have "Unknown identifier" or "Optimized away" when looking at variable.

I tried:

- Put -Og in the project property "Extra flags" (vMicro)
- Before my code I added

        #pragma GCC push_options
        #pragma GCC optimize ("Og")

    then at the end of my code

       #pragma GCC pop_option

**ANSWER:** I probably fuckup in the rebuild because only the line below is enough (in the .cpp file):

        #pragma GCC optimize ("Og")

- Replaced -Os in playform.txt (in this case it didn't work at all)

I saw a size changes in my binary (except for the last point), but when running the simulator I still couldn't see any value.

2) Couldn't start a debugging session
(When I try to change the debugging device it always crash AtmelStudio, I think it is because the target IC is force to ATSAM3X8E by the vMicro plugin which isn't supported on my computer, and because it isn't supported I can't change the target IC to attiny84a...)

**ANSWER:** When creating the project vMicro read the current board selected (yes before you even can select it) to detect if it has to create a 32 bits or 8 bits project

Also you **MUST** create a project with an .ino (even if it is empty) as the same name as the project in order to be able to compile.


message:
Input 4-digit number using 4*4 keypad and show in serial monitor

#include <Keypad.h>

    int myNum[4];

    const byte ROWS = 4;
    const byte COLS = 4;
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

    void loop() {
      Serial.println("Enter four-digit num -");  // request for input
      for (int i = 0; i < 4;){
        if(keypad.getKey()!= NO_KEY) {
          myNum[i] = keypad.getKey();
          i = i+1;
        }
      }
      Serial.print("Entered number is = ");
      Serial.print(myNum[0]);
      Serial.print(myNum[1]);
      Serial.print(myNum[2]);
      Serial.println(myNum[3]);
      delay(500);
    }

I want that when I press a 4-digit number on the keypad it should be shown in the serial monitor. This code gives 0000 when I press any key on keypad.

body:
`keypad.getKey()` is non-blocking as you can read [here][1]: it will return a value immediately, even if no key is pressed.  You have a `for` loop which will increment `i` each time, and you also increment it yourself. So what's happening is that your code is immediately making four readings, all of which are no-key-pressed so it doesn't store them, and then printing whatever happens to be in the `myNum` buffer.

Instead, you need to wait each time until a key is pressed, and only then move to the next digit. There are of course many ways you could do this.  I hope this is clear:

    #include <Keypad.h>

    int myNum[4];

    const byte ROWS = 4;
    const byte COLS = 4;
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

    void loop() {
      Serial.println("Enter four-digit num -");  // request for input

      for (int i = 0; i < 4; ++i){
        while((myNum[i] = keypad.getKey())==NO_KEY) {
          delay(1); // Just wait for a key
        }
        // Wait for the key to be released
        while(keypad.getKey() != NO_KEY) {
          delay(1);
        }

      }

      Serial.print("Entered number is = ");
      Serial.print(myNum[0]);
      Serial.print(myNum[1]);
      Serial.print(myNum[2]);
      Serial.println(myNum[3]);
      delay(500);
    }

  [1]: https://playground.arduino.cc/Code/Keypad


body:
    #include <Keypad.h>

    char myNum[4];

    const byte ROWS = 4;
    const byte COLS = 4;
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

    void loop() {
      Serial.println("Enter four-digit num -");  // request for input

      for (char i = 0; i < 4; ++i){
        while((myNum[i] = keypad.getKey())==NO_KEY) {
          delay(1); // Just wait for a key
        }
        // Wait for the key to be released
        while(keypad.getKey() != NO_KEY) {
          delay(1);
        }

      }

      Serial.print("Entered number is = ");
      Serial.print(myNum[0]);
      Serial.print(myNum[1]);
      Serial.print(myNum[2]);
      Serial.println(myNum[3]);
      delay(500);
    }


message:
ATmega 2560 with Arduino bootloader running issue

I have designed a board based on an ATmega2560 chip and I burned the bootloader by following [this tutorial][1].

Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

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

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

- I also have tried by removing D1 diode but no luck !

  [1]: https://www.gammon.com.au/bootloader
  [2]: https://i.stack.imgur.com/tF78W.png

body:
The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.

Solution:- Connect 10K pull-down on RX pin resolved this problem.


message:
L298 module - unusual power specs

I would like to purchase this [dual H-bridge module][1]. I plan on connecting it to an Arduino Uno. In the products [datasheet][2] the specified power supply (Vd) is 6.5-12V, and the voltage for the motor control pins is 2.3V HIGH and -0.3V LOW.

**My question** is whether this product is compatible with the standard 5V of Arduino Uno for both the power supply and logic; i.e. can I connect the Vd to the 5V terminal of the Arduino and the control pins to the digital terminals?

If not, what modifications do I need in order to use this H-bridge with an Arduino?

*Note:* Originally I bought [this][3] cheap module and connected the motor control pins to the Arduino, but each output returned a different output voltage!

  [1]: https://www.digikey.com/products/en?mpart=DRI0002&v=1738
  [2]: https://media.digikey.com/pdf/Data Sheets/DFRobot PDFs/DRI0002_Web.pdf
  [3]: https://www.aliexpress.com/item/Free-shipping-1pcs-lot-Special-promotions-2pcs-lot-L298N-motor-driver-board-module-stepper-motor-smart/1872427142.html?spm=a2g0s.9042311.0.0.DWm0WZ

body:
That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

> High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

> Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.

"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.

**The diagram at the end of the datasheet shows how it can be used with an Arduino.** A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.

I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)

You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.


message:
Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328

I need to monitor a battery plugged to an ATmega running on standalone mode.

I use the "ATmega on a breadboard (8 MHz internal clock)" bootloader.
[More info here][1]

When the ATmega is powered with 5V the sketch outputs good values : arround 5100 mV.

But when I power it with 3.3V the sketch gives strange values : arround 178619 mV.

Here is my code [Inspired from here][2]

    void setup()
    {
      Serial.begin(9600);
      Serial.println(F("Internal Voltage Sensor"));
    }

    void loop()
    {
      Serial.println( readVcc());
      delay(1000);
    }

    long readVcc()
    {
      long voltage=0;
      uint8_t wADC;

      // Read 1.1V reference against AVcc
      // set the reference to Vcc and the measurement to the internal 1.1V reference
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      ADCSRA |= _BV(ADEN);  // enable the ADC

      delay(20); // Wait for Vref to settle

      ADCSRA |= _BV(ADSC); // Start conversion
      while (bit_is_set(ADCSRA,ADSC)); // measuring

      // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
      wADC = ADCW;

      voltage = 11253000L / wADC; // Calculate Vcc (in mV); 1125.3 = 1.1*1023*1000
      return voltage; // Vcc in millivolts
    }

I don't understand what's going on. The returned value with Vcc=3.3V should be lower than with VCC=5V. Something like 3300 mV !

  [1]: https://forum.mysensors.org/topic/3018/tutorial-how-to-burn-1mhz-8mhz-bootloader-using-arduino-ide-1-6-5-r5
  [2]: https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

body:
Thanks for your answers!
Jot gave the solution: wADC must be a uint16_t.

Here is the corrected code :

 void setup()
 {
   Serial.begin(9600);
   Serial.println(F("Internal Voltage Sensor"));
 }

 void loop()
 {
   Serial.println(readVcc());
   delay(1000);
 }

 long readVcc()
 {
   long voltage=0;
   uint16_t wADC;

   // Read 1.1V reference against AVcc
   // set the reference to Vcc and the measurement to the internal 1.1V reference
   ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
   ADCSRA |= _BV(ADEN);  // enable the ADC

   delay(20); // Wait for Vref to settle

   ADCSRA |= _BV(ADSC); // Start conversion
   while (bit_is_set(ADCSRA,ADSC)); // measuring

   // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
   wADC = ADCW;

   voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
   return voltage; // Vcc in millivolts
 }


message:
Arduino connection with Arduino

I have 3 Arduino boards, let's call them be A, B, C. I'm connecting A with a bluetooth module and I'm getting the input from the bluetooth module.
Now I want to send output from A using the digital pins and I want the output of A to be the inputs of B and C. The output sent from A will be based on voice input from the bluetooth module. The inputs of B and C will provide output signals to L293D and L298N motor drives. I have only one bluetooth module. Is this possible? Please let me know, it's urgent. I'm working on a project.

body:
If you can connect ABC with wires, then it is easy - I use Wire library to send a lot of messages to net of many Arduinos.

Also other protocols are avaiable, like SPI, software serial, ... or if the communication is extremely easy (like just On/Off), then digitalWrite()/digitalRead() would work really easy.

I see the voice input to be more difficult in Arduino-size computers (voice recognition is not easy), but maybe you can process the voice before sending BT (on PC/tablet/phone/...) and then the BT would transfer only simple commands and it would be no problem at all.

If there is something I missed, you may write more, where you see the main problem.


message:
"Soft WDT reset" stack error: RFID-RC522 with NodeMCU

I have been all over the internet to try and find a solution to this, but after one solid week of intense Google searching I have come up with nothing.

**What I'm trying to accomplish:**

I am simply trying to use the RFID-RC522 NFC reader on an NodeMCU development board (built in ESP8266) with the mfrc522 library.

**Problem:**

Upon initiating the mfrc522 library, reaching the line `mfrc522.PCD_Init();` the Serial outputs the following "error":

    Soft WDT reset

    ctx: cont
    sp: 3ffefa10 end: 3ffefc40 offset: 01b0

    >>>stack>>>
    3ffefbc0:  00241001 00000001 3ffeec20 40106895
    3ffefbd0:  00000002 3ffee9d8 3ffee9f4 40202794
    3ffefbe0:  402010b2 00000001 00000032 402010a7
    3ffefbf0:  3fffdad0 00000010 3ffee9d8 4020290d
    3ffefc00:  402010b2 3ffee9d8 3ffee9d8 40202a01
    3ffefc10:  feefeffe 00000000 3ffeebec 40202080
    3ffefc20:  feefeffe 00000000 3ffeec08 40203e08
    3ffefc30:  feefeffe feefeffe 3ffeec20 40100108
    <<<stack<<<
    R+⸮⸮⸮

I found a tool that can translate the error [EspExceptionDecoder](https://github.com/me-no-dev/EspExceptionDecoder), translated error:

    Decoding 10 results
    0x40106895: __digitalWrite at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring_digital.c line 84
    0x40202794: MFRC522::PCD_ReadRegister(MFRC522::PCD_Register) at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
    0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
    0x402010a7: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 51
    0x4020290d: MFRC522::PCD_Reset() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
    0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
    0x40202a01: MFRC522::PCD_Init() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
    0x40202080: setup at C:\Users\my_user\OneDrive\Arduino\projekter\RFID_DumpInfo_test/RFID_DumpInfo_test.ino line 53
    0x40203e08: loop_wrapper at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_main.cpp line 57
    0x40100108: cont_norm at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/cont.S line 109

When the `mfrc522.PCD_init();` line is commented out the stack-error does *not* appear.
Reading the NFC tags has worked before on the NodeMCU unit, and I sometimes stubmled upon this error when adding *one* simple line like `var1 = var2;` somewhere in the loop, but now the error is there constantly, even with code that once worked - however I *did* change the pin-loadout, and I suspect that this is the problem.

**What I have tried:**

 - With the configurable pins I have tried most combinations I could
   think of, trying both the SS and the RST in every available pin.
 - [this](https://github.com/Jorgen-VikingGod/ESP8266-MFRC522) Github
   example suggets
 - [this](http://www.instructables.com/id/MFRC522-RFID-Reader-Interfaced-With-NodeMCU/)
   instructables tutorial.
 - 3 different RFID-RC522 modules (same model)
 - 2 different NodeMCU units (same model)

**Pin layout:**

My pin layout for the RFID-RC522 module is as follows;

 - **SDA (SS)**: D4
 - **RST**: D3
 - **SCK**: D5
 - **MOSI**: D7
 - **MISO**: D6
 - **GND**: GND
 - **3v3**: 3v3

**Arduino project info:**

 - Arduino IDE 1.8.5
 - Latest MFRC522 from the Library Manager
 - **Board:** NodeMCU 1.0 (ESP-12E Module)

**Code:**

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN          D4
    #define RST_PIN         D3

    MFRC522 mfrc522(SS_PIN, RST_PIN);

    void setup() {
     Serial.begin(9600);
     delay(100);
     SPI.begin();
      delay(100);
     mfrc522.PCD_Init();
     mfrc522.PCD_DumpVersionToSerial();
     Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

I've been on this issue for days now, and my Google searches tell me that I'm not the only one who has had this problem before. Any input is very welcome.

body:
can you also try to increase the serial boud rate to fe. 115200 instead of 9600?
In some cases I had some issues with 9600, because some buffers were not cleared fast enough and forces some WDT resets.

Cheers,
Jorgen


body:
I have come to the conclusion that using RFID with NodeMCU is not going to work - I can't confirm this, but I'm pretty sure the two libraries (ESP8266 and mfrc522) have some complications caused by one another.

A good workaround is using the TX and RX pins to communicate from an Arduino Nano which has the RFID reader to a NodeMCU board - this way you can send the NFC data to your WiFi board without complications.


message:
Using malloc() and free() for a stack/linkedlist

I know this question has been asked before, however it was asked two years ago and I have some other constraints to add.

(Previous question here) : https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino

I understand that dynamically allocating and freeing memory can cause fragmentation, and without an operating system to manage the memory, this fragmentation can reach a point where no memory can be allocated because the current memory is a mess.

That being said, the only memory allocation I plan to do is for a linked list that I am using as a stack. This means that I will only even be adding or removing from one end of the linked list. In the case that the arduino `malloc()` implementation is 'next fit', is it safe to assume that I can use this linked list safely, since the only element I'll be removing is the next one that fit, and everything else will stay where it is?

tl;dr the two questions I'm asking:

Is the arduino `malloc` implementation 'next fit'? Where can I read up on this in detail?

AND

A single stack running in a 'next fit' environment will never cause fragmentation, correct?

body:
Probably it will not be a problem, since when you free memory, those memory sizes will be equal than the memory size you malloc. E.g. suppose one element of a linked list is 24 bytes, if this is freed, the next time when 24 bytes are requested by malloc, it will use that space.

So my assumption it works when you never use free or malloc, EXCEPT when using it for one single linked list with elements that are always equal size.

However, you have to make sure:

- You do not free memory elsewhere (with different size)
- You do not malloc memory elsewhere (with different size)
- All libraries you use do not call a malloc/free under water.

Also, you can do an easy check by malloc/free and fill one item a lot of times one element (thus adding and removing it), and checking the memory usage is similar (or it does not crash to have a very simple test).

Btw, afaik Arduino pointers use 2 bytes, so this can cause quite some memory. If you use max. 256 elements, consider using indices, but in this case you have to write your own 'linked list' library (e.g. when removing, you have to move all subsequent indices).


body:
There are many implementations of malloc() and AFAIK, none is specified in the standard. So, while you could get lucky and and find that your preferred environment uses a malloc() algorithm compatible with your intended use, your code will not be known portable to another, unspecified, environment, and even a compiler or library revision to your preferred environment could break you code.

You'd be better off to write an allocator that works as you need it to work. Whether you need a linked-list or an array of fixed size blocks to accomplish your stack structure, using a `getStackFrame()`, `freeStackFrame()` pair of functions, written and controlled by you, will avoid some potential nasty surprises.


body:
On [my answer][] to the question you are referencing, I state that “_If
you use the heap like a stack (last in is first out), then it will
behave like a stack and not fragment._” This seems to be exactly your
usage pattern, thus you should not fear fragmentation. Of course, the
caveat written in Michel Keijzers’ answer applies: you should make sure
that no other part of your code, including libraries, is using
`malloc()` and `free()`.

Just to give some evidence, the avr-lic documentation provides some
[implementation details about malloc][impl]:

> When allocating memory [...] If nothing could be found on the
> freelist, heap extension is attempted. [...] When deallocating the
> topmost chunk of memory, the size of the heap is reduced.

All this can be seen in action in the [source code of malloc() and
free()][malloc.c], which is abundantly commented and quite readable.

[my answer]: https://arduino.stackexchange.com/a/8947
[impl]: http://www.nongnu.org/avr-libc/user-manual/malloc.html#malloc_impl
[malloc.c]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libc/stdlib/malloc.c?revision=2149&view=markup

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

**Edit 1**: From the same section of the avr-libc documentation, we learn
about how `realloc()` grows a memory chunk:

> If [...] the old chunk is at the top of heap, and the above freelist
> walk did not reveal a large enough chunk on the freelist to satisfy
> the new request, an attempt is made to quickly extend this topmost
> chunk (and thus the heap), so no need arises to copy over the existing
> data.

Based on this, I would suggest you use an array, rather than a linked
list, and use `realloc()` to adjust the size of the array. A linked list
of _n_ objects of size _m_ has a memory cost _n_ × (_m_+4):
each objects has an overhead of 2 bytes for the linking pointer, plus 2
bytes for `malloc()`'s internal bookkeeping. The cost of an array would
be only (_n_ × _m_)+2.

In this case, however, it is essential that no other part of your code
uses `malloc()`, otherwise `realloc()` could end up allocating a whole
new array, which would be very costly.

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

**Edit 2**: I wrote a small test program that randomly grows and shrinks
a memory buffer. Running the test on an Uno shows that the allocated
memory chunk never changes address even though its size varies wildly.

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

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

    void loop()
    {
        static void *p;
        static size_t sz;
        sz = random(max(sz, 22) - 20, min(sz + 20, 1536) + 1);
        p = realloc(p, sz);
        Serial.print((uintptr_t) p);
        Serial.print("  ");
        Serial.println(sz);
    }


message:
Use of array in case statement

I want to know how I can use case statement for each array.

Below is my code:

<!-- language: lang-cpp -->

    int incomingByte = 0;

    void setup()
    {
      Serial.begin(115200);
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        pinMode(thisPin, OUTPUT);
      }
    }

    void loop()
    {
      int button1[] = {0xFF, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05};
      int button2[] = {0xFF, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06};
      int button3[] = {0xFF, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
      int button4[] = {0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C};

      if (Serial.available() > 0)
      {
        incomingByte = Serial.read();
      }

      switch (incomingByte)
      {
        case button1:
          digitalWrite(2, HIGH);
          break;
        case button2:
          digitalWrite(3, HIGH);
          break;
        case button3:
          digitalWrite(4, HIGH);
          break;
        case button4:
          digitalWrite(5, HIGH);
          break;
        default:
          for (int thisPin = 2; thisPin < 6; thisPin++)
          {
            digitalWrite(thisPin, LOW);
          }
      }
    }

body: `case` doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.


body:
Not checked/compiled, just to give an idea.

    /* One button message is 12 bytes, it is assumed that all received messages are 12 bytes. If note, you have to check later differently. */
    #define MSG_SIZE 11
    byte incomingBytes[MSG_SIZE]; /* Storage for 11 bytes */
    byte index = 0; /* Current byte to set within incomingBytes */

    void setup()
    {
      Serial.begin(115200);
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        pinMode(thisPin, OUTPUT);
      }
    }

    void loop()
    {
      if (Serial.available() > 0)
      {
        /* Store the next incoming byte. Assume 0xFF is the start of a message. */
        byte incoming_byte = Serial.read();
        if (incoming_byte == 0xFF)
        {
          index = 0;
        }

        incomingBytes[index] = incoming_byte;
        index++;
        if (index >= MSG_SIZE)
        {
           check_message();
           index = 0;
        }
      }
    }

    /* Checks which button is pressed and performs an action based on the
    pressed button. */
    void check_message()
    {
      case check_button_pressed())
      {
        case 1:
          digitalWrite(2, HIGH);
          break;
        case 2:
          digitalWrite(3, HIGH);
          break;
        case 3:
          digitalWrite(4, HIGH);
          break;
        case 4:
          digitalWrite(5, HIGH);
          break;
        default:
          for (int thisPin = 2; thisPin < 6; thisPin++)
          {
            digitalWrite(thisPin, LOW);
          }
      }
    }

    /* Checks which button is pressed by comparing 11 incoming bytes to the
    four buttons to be checked. Returns -1 for an illegal message/unsupported
    button and 1, 2, 3 or 4 for the pressed button. */
    int check_button_pressed()
    {
      int button_pressed = -1;
      if ((incomingBytes[0] == 0xFF) &&
          (incomingBytes[1] == 0x04) &&
          (incomingBytes[3] == 0x00) &&
          (incomingBytes[4] == 0x00) &&
          (incomingBytes[5] == 0x00) &&
          (incomingBytes[6] == 0x00) &&
          (incomingBytes[7] == 0x00) &&
          (incomingBytes[8] == 0x00) &&
          (incomingBytes[9] == 0x00))
      {
        if ((incomingBytes[2] == 0x01) && (incomingBytes[10] == 0x05))
        {
          button_pressed = 1;
        }
        else if ((incomingBytes[2] == 0x02) && (incomingBytes[10] == 0x06))
        {
          button_pressed = 2;
        }
        else if ((incomingBytes[2] == 0x04) && (incomingBytes[10] == 0x08))
        {
          button_pressed = 3;
        }
        else if ((incomingBytes[2] == 0x08) && (incomingBytes[10] == 0x0C))
        {
          button_pressed = 4;
        }
      }
      return button_pressed;
    }


message:
Meaning of part number suffix on top of atmega2560 chip

I have been working on creating a stand alone atmega2560 arduino. When trying to program it with a serial adapter using the rx and tx pins nothing was happening. After a lot of debugging I found the problem was with the chip.

I found that the ones that worked said atmega2560 16AU 0721, the ones that did not work said Atmega2560 16AU 1241. When looking on eBay, i noted that the Atmega2560 16AU comes with many different versions of those last four numerals, does anyone know what the last four digits on top of the atmega2560 16AU mean?

body:
The data sheet (or supplemental product-line documentation) will specify the formal package marking codes, but for an ATmega, the `16AU` is part of the variant specification but the following would appear to be date or lot codes.

These are probably not your problem.

More likely, the chip you are trying to interact with via the serial port

- **does not have a bootloader flashed (normally they are sold blank)**
- has a bootloader which requires a different baud rate
- is fused for a clock source you are not providing
- has the brownout detector set lower than the supply you are providing
- is improperly or incompletely soldered
- is damaged

While there was the infamous case of Sparkfun being sold a reel of power supply chips falsely marked as ATmega328's, this is still a relatively unlikely possibility compared to the more likely ones above, especially the simple lack of a bootloader.  And a date code is no proof of authenticity - though if you ended up co-mingly inventory from various sources/purchases, it might help you with preliminary sorting them.


body:
The last four digits are a date code - the date of manufacture.

It's in the form `YYWW` where `YY` is the last two digits of the year, and `WW` is the week number.

So `0721` is the 21st week of 2007, and `1241` is the 41st week of 2012.


message:
Portal gun sound effects and lights

I'm building a portal gun from the game Portal and I'm struggling with the wiring for the lights and sound. I've the lights working using the first image from Instructables and adding more LEDs shouldn't be a problem. I'm trying to add the SD card and speaker so when you flick the switch, as well as the lights changing, the firing sound is played. Image 2. everything is wired quite nicely the only change is I'm using pin 10 not 4 on the memory card.

[![2 leds 1 spdt ][1]][1]

[![SD Card and speaker][2]][2]

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

This is my code and it all compiles fine and seems to make sense to me but I'm new to programming.

The lights work but none of the sounds play. I've formatted the SD card and also made sure the .wav files are the right format: mono 8 bit 16000 Hz. I can't work out what's wrong and why I can't get it to play the sounds.

I also have an Adafruit amp just in case it isn't loud enough but not a clue how to wire it in.

<!-- language: lang-cpp -->

    #include <pcmRF.h>
    #include <TMRpcm.h>
    #include <SD.h>                       // need to include the SD library
    #define SD_ChipSelectPin 10            // using digital pin 10 on arduino uno 328, can use other pins
    #include <SPI.h>

    void setup()
    {
      // put your setup code here, to run once:
      TMRpcm tmrpcm;
      tmrpcm.speakerPin = 9;          //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin))
      {
        Serial.println("SD fail");
        return;
      }
      tmrpcm.setVolume(6);
      tmrpcm.play("1.wav");
      tmrpcm.play("2.wav");

      //set the switch input, pin 8, as an
      pinMode(8, INPUT);

      //set both the LED pins, pin 5 and 6 as OUTPUTs
      pinMode (5, OUTPUT);
      pinMode (6, OUTPUT);
    }

    void loop()
    {
      TMRpcm tmrpcm;
      int switchValue = digitalRead(8);
      if (switchValue == 1)
      {
        digitalWrite(5, HIGH);
        digitalWrite(6, LOW);
        tmrpcm.setVolume(6);
        tmrpcm.play("4.wav");
      }
      else
      {
        digitalWrite(6, HIGH);
        digitalWrite(5, LOW);
        tmrpcm.setVolume(6);
        tmrpcm.play("5.wav");
      }
    }

body:
At a guess I would say your main problem is you are defining your TMRpcm objects within the setup and loop functions, which means that as soon as that function exits the TMRpcm objects will be disposed of. I.e., it won't work. It may *start* playing a sound in `setup()`, but it will stop (and maybe even crash completely) before you even have a chance to hear it.

Your `TMRpcm` object *must* be declared globally for you to have any hope of making it work.

    TMRpcm tmrpcm;

    void setup() {
        // ....
        tmrpcm.speakerPin=9;
        tmrpcm.setVolume(6);
        tmrpcm.play("1.wav");
    }

etc.

Another thing to note is that `TMRpcm` plays the sounds *asynchronously*. That is, it doesn't wait while it plays the sound, so if you play one sound and then another sound the second sound will start before the first one has even begun playing, so you'll never hear the first one.  Instead, if you want to play sounds sequentially, you should for the first sample to finish using something like:

    while (tmrpcm.isPlaying()) {
        delay(1);
    }

which will stop your sketch running until the last sound has finished.  Including the `delay(1)` is a good idea since it allows `yield()` to execute allowing anything that needs it to run (not really a problem on an Uno, but on things like an ESP8266 it's absolutely critical or you get a watchdog timeout).


message:
This logic level converter does not want to work

I got this logic level converter to be able to use my lcd but I can't figure out how to get it to work, the problem is that the current is not passing through. This is the model: TXS0108E

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

Any help is appreciated.

[EDIT]

A few Combinations that I have tried:

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

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

And I tried to swap the voltages, same wiring as in the pictures but 3.3v instead of 5v and vice versa.

  [1]: https://i.stack.imgur.com/0eTAL.jpg
  [2]: https://i.stack.imgur.com/2oqNJ.png
  [3]: https://i.stack.imgur.com/Z0mRn.png

body:
The TSX0108 doesn't magically provide you with a regulated voltage. You have to provide the voltage, the TSX0108 merely switches it.

As you can see from [the datasheet](http://www.ti.com/lit/ds/symlink/txs0108e.pdf), the basic wiring is:

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

In the circuit above the 1.8V connection is your 3.3V connection, and the 3.3V is your 5V connection.

**You must provide both the 3.3V and 5V power sources.**

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


message:
Arduino Nano wih mfrc522 warning error

**UPDATE**

I have managed to get rid of the `WARNING: Communication failure, is the MFRC522 properly connected?`. Unfortunately, that did not fix the firmware error it now says `0x80`. I have now also tried using different IDEs from arduino in the hopes of fixing this, still nothing. The connection error between the reader and the arduino has come back as well.

Furthermore...

    *****************************
    MFRC522 Digital self test
    *****************************
    Firmware Version: 0x92 = v2.0
    -----------------------------
    Only known versions supported
    -----------------------------
    Performing test...
    -----------------------------
    Result: DEFECT or UNKNOWN

would this now mean that my device is a defect?

Also, that version has gone back to showing `unknown` and the other hexadecimal codes.

I have just bought the parts. The arduino nano v3 and the MFRC522 based RFID reader. I have followed the typical pin layout after downloading the library from arduino. When I go to test one of the examples I get a warning within the arduino serial monitor :

    Firmware Version: 0xFF = (unknown)
    WARNING: Communication failure, is the MFRC522 properly connected?
    Scan PICC to see UID, SAK, type, and data blocks...

I try to scan one of the existing cards but nothing happens. It either stats that it is version `0xFF` or `0x0`. I am new with this and this is my first 'project'. the pins are defined.[![enter image description here][2]][2]

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

I have 3.3V on the reader to 3v3 on the arduino
I have RST on the reader to D9 on the arduion
I have GND on the reader to GND on the arduino (on the same side as the 3v3 is )
I have MISO on the reader to D12 on the arduino
I have MOSI on the reader to D11 on the arduino
I have SCK on the reader to D13 (on the same side as the 3v3 is)
I have SDA on the reader to D10 on the arduino

The code I am using is from the arduino library manager:

      /*
      * --------------------------------------------------------------------------------------------------------------------
      * Example sketch/program to test your firmware.
      * --------------------------------------------------------------------------------------------------------------------
      * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
      *
      * This example test the firmware of your MFRC522 reader module, only known version can be checked. If the test passed
      * it do not mean that your module is faultless! Some modules have bad or broken antennas or the PICC is broken.
      * NOTE: for more informations read the README.rst
      *
      * @author Rotzbua
      * @license Released into the public domain.
      *
      * Typical pin layout used:
      * -----------------------------------------------------------------------------------------
      *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
      *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
      * Signal      Pin          Pin           Pin       Pin        Pin              Pin
      * -----------------------------------------------------------------------------------------
      * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
      * SPI SS      SDA(SS)      10            53        D10        10               10
      * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
      * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
      * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3              15
      */

     #include <SPI.h>
     #include <MFRC522.h>

     constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout    above
     constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout    above

     MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

     /**
      * Check firmware only once at startup
      */
     void setup() {
       Serial.begin(9600);   // Initialize serial communications with the PC
       while (!Serial);      // Do nothing if no serial port is opened (added for    Arduinos based on ATMEGA32U4)
       SPI.begin();          // Init SPI bus
       mfrc522.PCD_Init();   // Init MFRC522 module

    Serial.println(F("*****************************"));
    Serial.println(F("MFRC522 Digital self test"));
    Serial.println(F("*****************************"));
    mfrc522.PCD_DumpVersionToSerial();  // Show version of PCD - MFRC522 Card Reader
    Serial.println(F("-----------------------------"));
    Serial.println(F("Only known versions supported"));
    Serial.println(F("-----------------------------"));
    Serial.println(F("Performing test..."));
    bool result = mfrc522.PCD_PerformSelfTest(); // perform the test
    Serial.println(F("-----------------------------"));
    Serial.print(F("Result: "));
    if (result)
      Serial.println(F("OK"));
    else
      Serial.println(F("DEFECT or UNKNOWN"));
    Serial.println();
     }

     void loop() {} // nothing to do

  [1]: https://i.stack.imgur.com/JW89P.jpg
  [2]: https://i.stack.imgur.com/xOVCq.png

body: You are using SPI comm. The code is fine too. Usually this "communication failure" happens due to wrong pin connections. Say for eg. If MOSI and MISO are interchanged. Check all connections, ground and VCC connections once more. I have also seen that soldering the pins of MFRC522,  instead of simply connecting by wire has solved this issue most of the time. Another work around is repeatedly calling PCD_init() function even after failing result inside loop() . And see whether its working. If none of these worked, hard luck. I think its firmware issue or defective board.


message:
Ethernet shield compatibility

Does anyone know if there is an Ethernet shield is compatible with the Arduino Ethernet shield (R3)? The R3 does not seem to be in production anymore and I need a replacement shield. Found some from Velleman, or maybe Ethernet Shield 2?

* [Arduino Ethernet Shield R3][1]
* [Arduino Ethernet Shield 2][2]
* [Velleman Ethernet Shield][3]

  [1]: https://store.arduino.cc/arduino-ethernet-shield-without-poe-module
  [2]: https://store.arduino.cc/arduino-ethernet-shield-2
  [3]: https://www.velleman.eu/products/view/?id=412244

body:
No, it is not compatible.  It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.

You can use it if you refactor all your code to use the [Ethercard library](https://github.com/jcw/ethercard) instead of the Ethernet library.

There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.


message:
How to create a log file document which is not editable by a word processor on SD card

I'm using a **Arduino Mega 2560**  and **SD card shield** to make an industrial logging panel. Is there any way to write log data document in a **read-only type** file like a **pdf** on SD card so that the contents cannot be edited once created by word processing software? The data has to presented as a document on a windows machine.

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

body:
There is no such thing as a file that cannot be edited.

If a file can be read it can be edited.

However, there are ways of making it possible to know if a file has been edited - i.e., to integrity check the file. To make it *hard* to edit a file and maintain the intrinsic integrity of the file.

The simplest method is to create a checksum of the data in the file and store that in the file as well. If the data is, for example, a CSV file, you could include in each row a checksum of the data in that row as an extra column. If the data gets changed the checksum will no longer match. Of course, that doesn't preclude someone calculating the new checksum and entering that.  So maybe adding a checksum of all the checksums at the end of the file as well so you know if any checksums have changed.

Again, it's possible for someone to recalculate that checksum as well.

The most secure method is to digitally sign the file (in the way the PGP or GnuPG does). Without the private key, it's impossible to re-sign the file after modification. However, that kind of operation is comparatively heavyweight and not something an Arduino is particularly suited to doing (I'm not sure if it's even physically possible given the lack of resources an Arduino has).


message:
PROGMEM doesn't cause Sketch size to change

I'm trying to pinpoint some strange behaviour involving the use of PROGMEM and the size of a Sketch.

I've written a library that contains a number of functions, in addition to several large global byte arrays and 32-bit uint arrays. These arrays are stored in PROGMEM using the pgmspace library. The library compiles fine, and all code works properly when uploaded to an Arduino.

I'm performing testing on the functions using a testing sketch that in turn uses my library. In order to test the performance, I've been switching between using PROGMEM and not using PROGMEM in the library (all arrays are under 2KB). When using PROGMEM, it drops the Global Variable dynamic memory count by the expected amount... but the the sketch program size remains either constant, or seems to arbitrarily increase or decrease by a very small amount, depending on the function. For example, a uint8_t byte[256] array, when moved to the PROGMEM, causes the Global Variable size to go down by about 256 bytes... but the sketch size only increases by about 12 bytes.

Each entry in the array is unique and is accessed, so the compiler shouldn't be optimizing it away. I tried just using avr-size directly on the ELF file, but the sketch size was the same. I can't tell if the data is being stored in PROGMEM all the time (even when not declared as PROGMEM, due to some sort of issue with PROGMEM in libraries?), or if PROGMEM data simply isn't being counted as part of the sketch size, or ??? I have tried moving the functions directly out of the library into the sketch, changing data types, adding/removing static and const declarations... but the lack of change in sketch size continues to confuse me. Any help would be greatly appreciated.

body: all constant data are part of the sketch. where else should they be? in runtime they are loaded into RAM. PROGMEM directive prevents the loading into RAM.


message:
Confusion with Serial Communication

Is a buffer used for outputting data from the arduino?

OR

Is the output from the arduino buffered before sending it to Computer?

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

Eg- If am sending a text through the Serial Monitor to the arduino and I am also doing Serial.println("sth") then are they both using the same buffer?

How can i relate Serial buffer with these processes

Please Help!

Arduino Noob

EDIT-1

Can you please explain about the TX buffer overflow

body:
> Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

> Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

> Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation.
The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.


message:
Integer looping in EEPROM Read

I am reading data from a 24LC1025 over I2C with an Arduino and then outputing that data to my PC through the Serial interface. The EEPROM chip is seperated into two pages and at address 65535 [0x0FFFF] it switches over to the second page sending [0x10000 through 0x1FFFF] I had it working by reading each address with a random read:

    #include <Wire.h>

    byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
        byte rdata = 0xFF;
        Wire.beginTransmission(deviceaddress);
        Wire.write((eeaddress >> 8)); // MSB
        Wire.write((eeaddress & 0xFF)); // LSB
        Wire.endTransmission();
        Wire.requestFrom(deviceaddress,1);
        if (Wire.available()) rdata = Wire.read();
        return rdata;
    }

    void setup() {
      Wire.begin(); // initialise the connection
      Serial.begin(9600);
      delay(100); //add a small delay
      Serial.println("Arduino Group Delay Read Program");

      for (unsigned long i = 0; i < 128000; i++){
        Serial.print(i);
        Serial.print(",");
        byte a = i2c_eeprom_read_byte(0x50, i);
        Serial.println(a, BIN);
      }
    }

    void loop() {
      //
    }

To reduce overhead and speed up the process I am now using the code below:

    #include <Wire.h>

    byte bytes[32];

    void i2c_eeprom_read_buffer( int deviceaddress, unsigned long eeaddress, byte *buffer, int length ) {
        Wire.beginTransmission(deviceaddress);
        Wire.write((eeaddress >> 8)); // MSB
        Wire.write((eeaddress & 0xFF)); // LSB
        Wire.endTransmission();
        Wire.requestFrom(deviceaddress,length);
        int c = 0;
        for ( c = 0; c < length; c++ )
            if (Wire.available()) buffer[c] = Wire.read();
    }

    void setup() {
      Wire.setClock(400000); // 400kHz
      Wire.begin(); // initialise the connection
      Serial.begin(250000);
      delay(100); //add a small delay
      Serial.println("Arduino Group Delay Read Program");

      for (unsigned int i = 0; i < 128000;){
        i2c_eeprom_read_buffer(0x50, i, (byte *)bytes, 32);
        for (int j = 0; j < 32; j++){
          Serial.print(i);
          Serial.print(",");
          Serial.println(bytes[j], BIN);
          i++;
        }
      }
    }

    void loop() {
      //
    }

Unfortunately, the program now loops at the page boundary back to the start of the address range. Here is a sample of the output:

    65500,1110100
    65501,1101000
    65502,1101001
    65503,1110011
    65504,100000
    65505,1101001
    65506,1110011
    65507,100000
    65508,1100100
    65509,1100001
    65510,1110100
    65511,1100001
    65512,100000
    65513,1100110
    65514,1110010
    65515,1101111
    65516,1101101
    65517,100000
    65518,1110100
    65519,1101000
    65520,1100101
    65521,100000
    65522,1100101
    65523,1100101
    65524,1110000
    65525,1110010
    65526,1101111
    65527,1101101
    65528,0
    65529,11111111
    65530,11111111
    65531,11111111
    65532,11111111
    65533,11111111
    65534,11111111
    65535,11111111
    0,0
    1,0
    2,1
    3,110000
    4,111000
    5,111001
    6,110110
    7,110001
    8,111001
    9,1000001
    10,101110
    11,1011000
    12,110001
    13,110001
    14,1010110
    15,1011001
    16,110001
    17,110111
    18,110100
    19,110001
    20,1110100
    21,1101000
    22,1101001
    23,1110011
    24,100000
    25,1101001
    26,1110011
    27,100000
    28,1100100
    29,1100001
    30,1110100
    31,1100001
    32,100000
    33,1100110
    34,1110010
    35,1101111
    36,1101101
    37,100000
    38,1110100
    39,1101000
    40,1100101
    41,100000
    42,1100101
    43,1100101
    44,1110000
    45,1110010
    46,1101111
    47,1101101
    48,0
    49,111001
    50,100010
    51,11010010
    52,110101
    53,1001000
    54,11101011
    55,11000000
    56,110101
    57,11101011
    58,1011100
    59,10010100
    60,110101
    61,100000
    62,10100011
    63,1110110
    64,10110100
    65,10110001
    66,1111010
    67,11100000
    68,10110110
    69,101100
    70,11010110

I could see how an error in the code could cause the second page to display the first page's values, but there is nothing in the code that should cause the counter itself to loop. Any idea what could be causing this?

**Edit:
For anyone who is working a similar issue, here is the code that I ended up with once I solved this issue and then dealt with the page boundary problem (line 4):**

    #include <Wire.h>

    byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
      byte rdata = 0xFF;
       if( eeaddress > 65535 ){
        deviceaddress = deviceaddress | B00000100;
        eeaddress = eeaddress & 0xFFFF;
        }
      Wire.beginTransmission(deviceaddress);
      Wire.write((eeaddress >> 8));   // MSB
      Wire.write((eeaddress & 0xFF)); // LSB
      Wire.endTransmission();
      Wire.requestFrom(deviceaddress,1);
      if (Wire.available()) rdata = Wire.read();
      return rdata;
    }

    void setup() {
      Wire.setClock(400000);
      Wire.begin(); // initialise the connection
      Serial.begin(115200);
      delay(100); //add a small delay
      Serial.println("Arduino Group Delay Read Program");

      for (unsigned long i = 0; i < 128000; i++){
        Serial.print(i);
        Serial.print(",");
        byte a = i2c_eeprom_read_byte(0x50, i);
        Serial.println(a, BIN);
      }
    }

    void loop() {
    }

Note that this last code will work with the i2c_eeprom_read_buffer function as well as long as you add the if statement starting at line 4.

body:
    for (unsigned int i = 0; i < 128000;){

An `unsigned int` can only count from 0 to 65536 on an 8-bit system...  You need that to be an `unsigned long`, or better, a `uint32_t` (better because it's guaranteed to be an unsigned 32-bit value on any platform regardless of how wide its registers are).


message:
Help with Serial.print()

How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?

Also, **What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?**

And please explain the difference with Serial.write()

Thanks!

body:
`Serial.print()` feeds the data into the TX buffer one character at a time (through the `Print` class's inherited `.write()` function which `HardwareSerial` implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.

Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.

To put it in more detail:

* When you call `Serial.print()` it's actually calling `Print.print()`, because `Print` is a parent class of the `HardwareSerial` class.
* `Print.print()` repeatedly calls `Print.write()` for each character to print.
* `Print.write()` is a *pure virtual* function (which means it's only got the definition in the `Print` class and child classes must implement it).
* `HardwareSerial.write()` implements the `Print.write()` function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
* `Serial` is an instance of the `HardwareSerial` class.


message:
Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound

My Dad and I are just learning how to use my new UNO.

We have learned how to make leds flash at the touch of a button. We have also learned how to make a passive buzzer sound at the touch of a button and change tone to sound like a police car.

We have just learned that we cant run more than one loop so we have combined the buzzer code and the LED code twice (for blue and red LEDs) and it works... but the delay on the LEDs is ruining the buzzer sound. Is there anything we can do?

The code is below.

Thank you!

Code:

    int buzzerPin = 9;    // the number of the buzzer pin
    int BlueLEDpin = 5;   // the number of the blue LED pin
    int RedLEDpin = 7;    // the number of the Red LED pin
    float sinVal;         // Define a variable to save sine value for buzzer
    int toneVal;          // Define a variable to save sound frequency for buzzer

    void setup() {
      pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
      pinMode(BlueLEDpin, OUTPUT); // Set Blue LED pin to output mode
      pinMode(RedLEDpin, OUTPUT); // Set Red LED pin to output mode
    }

    void loop() {
        Buzzer();
        BlueLED();
        RedLED();

    }

    void Buzzer() {
      for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
        sinVal = sin(x * (PI / 180));       // Calculate the sine of x
        toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
        tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
        delay(1);
      }

     }

      void BlueLED() {
      digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1);              // wait for a second
      digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
      delay(1);              // wait for a second
    }

    void RedLED() {
      digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1);              // wait for a second
      digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
      delay(1);              // wait for a second
    }

body: Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.


body:
We have done it. Thanks for the help Harper Shelby.

We combined the Blink Without Delay example with our original code:

    int buzzerPin = 9;    // the number of the buzzer pin
    const int BlueLEDpin = 5;
    const int RedLEDpin = 7;
    float sinVal;         // Define a variable to save sine value
    int toneVal;          // Define a variable to save sound frequency
    int BlueLEDState = LOW;
    int RedLEDState = HIGH;
    unsigned long previousMillisBlue= 0;
    unsigned long previousMillisRed= 0;
    const long interval = 200;

    void setup() {
      pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
      pinMode(BlueLEDpin, OUTPUT);
      pinMode(RedLEDpin, OUTPUT);
    }

    void loop() {
        Buzzer();
        BlueLED();
        RedLED();

    }

    void Buzzer() {
      for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
        sinVal = sin(x * (PI / 180));       // Calculate the sine of x
        toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
        tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
        delay(1);
      }

     }

      void BlueLED() {
      unsigned long currentMillisBlue = millis();

      if (currentMillisBlue - previousMillisBlue >= interval) {
        previousMillisBlue = currentMillisBlue;
        if (BlueLEDState == LOW) {
          BlueLEDState = HIGH;
        } else {
          BlueLEDState = LOW;
        }

        digitalWrite(BlueLEDpin, BlueLEDState);
      }

    }

    void RedLED() {
      unsigned long currentMillisRed = millis();

      if (currentMillisRed - previousMillisRed >= interval) {
        previousMillisRed = currentMillisRed;
        if (RedLEDState == LOW) {
          RedLEDState = HIGH;
        } else {
          RedLEDState = LOW;
        }

        digitalWrite(RedLEDpin, RedLEDState);
      }

    }


body:
Firstly, congratulations! you've taken your first step into the very rewarding world of micro-controllers. I teach robotics at a local university, so it's always nice to see when the light-bulb goes on and people start understanding.

As mentioned above, the blink without delay code is a good start. Good code should also be expandable in case later you want to add another light or 10, and this is where coding every line can get very large. There are many other methods for doing this sort of task, however you might want to have a look at this series of tutorials. [Multitasking with the Arduino.][1]

The benefit to the state machine approach used in that example is it becomes very easy later on to change your code; if you want to have more lights flashing in sequence (like the knight-rider lights) or more sirens, it becomes easier to include. In your second code, the void redLED() and void blueLED() codes contain mostly the same lines; you could make an object called 'LED' and then just make as many instances of this as you need, all working at different speeds and different pins (the example on the website should provide this much. The buzzer can probably reuse the servo sweep part of the code). You could also for example, program 4 different types of siren as a switch:case, and after the elapsed time, switch between them.

Another more advanced method would be to include a real-time operating system. An RTOS makes it very easy to have multiple independent tasks running. Each light could be on its own task and the siren on a third, and the system would keep each working, effectively simultaneously. This approach then has advantages if you want to change the timing of one light; it gets changed in one place without fear of needing to change the whole code. Information on FreeRTOS on the arduino can be found [here.][2] There is an example at the bottom of the page which includes both Blink and analog read examples.

These are fairly advanced topics, but I think you and your dad will get there. Once again, congratulations.

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview
  [2]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc


body:
We made it better with Nathan's pointer.

We learned how to make a class but the LEDs flashed together so we learned how to make another class (with Public and Void Update in the class - caught us out at first that bit). One class starts with state HIGH and the other with state LOW so the LEDs alternate. When we press all three buttons we get the two tone buzzer, and the alternating LEDs.

Using this method we can add as many new LEDs as we like.

Here is the code we wrote:

    /*
      Jacob & Dad’s Police Car light and sounds
    */

    int buzzerPin = 9;
    float sinVal;
    int toneVal;

    class FlashingLED_A
    {
     int ledPin;
     long OnTime;
     long OffTime;
     int ledState;
     unsigned long previousMillis;
      public:
      FlashingLED_A(int pin, long on, long off)
      {
     ledPin = pin;
     pinMode(ledPin, OUTPUT);
     OnTime = on;
     OffTime = off;
     ledState = LOW;
     previousMillis = 0;
      }

     void Update()
      {
        // check to see if it's time to change the state of the LED
        unsigned long currentMillis = millis();

        if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
         ledState = LOW;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(ledPin, ledState);  // Update the actual LED
        }
        else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
          ledState = HIGH;  // turn it on
          previousMillis = currentMillis;
          digitalWrite(ledPin, ledState);
        }
      }

    };

    class FlashingLED_B
    {
     int ledPin;
     long OnTime;
     long OffTime;
     int ledState;
     unsigned long previousMillis;
      public:
      FlashingLED_B(int pin, long on, long off)
      {
     ledPin = pin;
     pinMode(ledPin, OUTPUT);
     OnTime = on;
     OffTime = off;
     ledState = HIGH;
     previousMillis = 0;
      }

     void Update()
      {
        // check to see if it's time to change the state of the LED
        unsigned long currentMillis = millis();

        if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
         ledState = LOW;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(ledPin, ledState);  // Update the actual LED
        }
        else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
          ledState = HIGH;  // turn it on
          previousMillis = currentMillis;
          digitalWrite(ledPin, ledState);
        }
      }

    };

    FlashingLED_A led1(5, 100, 400);
    FlashingLED_B led2(7, 100, 400);

    void setup() {
      pinMode(buzzerPin, OUTPUT);
    }

    void loop() {
      Buzzer();
     led1.Update();
     led2.Update();
    }

    void Buzzer() {
      for (int x = 0; x < 360; x++) {
        sinVal = sin(x * (PI / 180));
        toneVal = 2000 + sinVal * 500;
        tone(buzzerPin, toneVal);
        delay(1);
      }
     }