body:
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.

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

Answers: 2

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.


body:
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?

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

Answers: 3

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);
    }


body:
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);
          }
      }
    }

title: Use of array in case statement

Answers: 2

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;
    }


body:
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?

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

Answers: 2

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.


body:
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");
      }
    }

title: Portal gun sound effects and lights

Answers: 1

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).


body:
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

title: This logic level converter does not want to work

Answers: 1

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


body:
**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

title: Arduino Nano wih mfrc522 warning error

Answers: 1

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.


body:
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

title: Ethernet shield compatibility

Answers: 1

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.


body:
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.

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

Answers: 1

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).


body:
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.

title: PROGMEM doesn't cause Sketch size to change

Answers: 1

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.


body:
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

title: Confusion with Serial Communication

Answers: 1

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.


body:
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.

title: Integer looping in EEPROM Read

Answers: 1

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).


body:
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!

title: Help with Serial.print()

Answers: 1

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.


body:
I have a keypad that is connected to my Arduino and each time a key is pressed, the number should be outputted to an LCD screen. The issue is that after the screen is cleared, and a new ID is being entered, any number on the first row will not trigger a keypress event but only on its first click. If you press it twice, it works completely fine. I am using the Keypad library and here is my code. Thanks for any help!
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <Keypad.h>
    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    #define I2C_ADDR    0x3F // <<----- Add your address here.  Find it from I2C Scanner
    #define BACKLIGHT_PIN     3
    #define En_pin  2
    #define Rw_pin  1
    #define Rs_pin  0
    #define D4_pin  4
    #define D5_pin  5
    #define D6_pin  6
    #define D7_pin  7

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

    const char* host = "**";
    const char* getSystem = "**";
    const char* apiKey = "**";
    const char* systemIdentifier = "**";

    const byte n_rows = 4;
    const byte n_cols = 3;

    char keys[n_rows][n_cols] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[n_rows] = {D2, D3, D4, D5};
    byte colPins[n_cols] = {D6, D7, D8};

    int n = 1;
    String idNumber;

    boolean checkingIn = false;

    LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);
    Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);

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

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      lcd.begin (16, 2);

      // Switch on the backlight
      lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.home ();

      lcd.print("Connecting");

      while (WiFi.status() != WL_CONNECTED) {
        lcd.print(".");
        delay(500);
      }

      setLCD("Please Enter ID#", 0);
      setLCD("                ", 1);

      delay(500);
    }

    void loop() {
      if (!checkingIn) {
        char myKey = myKeypad.getKey();
        Serial.print(myKey);
        if (myKey != NULL && (String)myKey != "*" && (String)myKey != "#") {
          Serial.print("Key pressed: ");
          Serial.println(myKey);
          idNumber += (String)myKey;
          setLCD(idNumber, 1);
        } else if ((String)myKey == "*" && idNumber.length() > 0) {
          idNumber = idNumber.substring(0, idNumber.length() - 1);
          setLCD("                ", 1);
          setLCD(idNumber, 1);
        } else if ((String)myKey == "#") {
          setLCD("                ", 0);
          setLCD("                ", 1);
          setLCD(" Checking in... ", 0);
          checkIn();
        }
      }
    }

    void setLCD(String text, int line) {
      lcd.setBacklight(HIGH);
      lcd.setCursor(0, line);
      lcd.print(text);
    }

    void checkIn() {
      checkingIn = true;
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        setLCD("                ", 1);
        setLCD("    Failed!     ", 0);
        return;
      }

      // We now create a URI for the request
      String url = "/assets/api.php?SYSTEM=";
      url += getSystem;
      url += "&API_KEY=";
      url += apiKey;
      url += "&SYSTEM_IDENTIFIER=";
      url += systemIdentifier;
      url += "&ID=";
      url += idNumber;

      // This will send the request to the server
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");
      unsigned long timeout = millis();
      while (client.available() == 0) {
        if (millis() - timeout > 1000) {
          setLCD("                ", 1);
          setLCD("    Failed!     ", 0);
          client.stop();
          return;
        }
      }

      // Read all the lines of the reply from server and print them to //Serial
      while (client.available()) {
        String line = client.readStringUntil('\r');
        if (line.indexOf("[response|failed]") > -1) {
          setLCD("Invalid Login...", 0);
          setLCD("                ", 1);
        } else if (line.indexOf("*") > -1) {
          setLCD("Welcome:        ", 0);
          setLCD("                ", 1);
          setLCD(line, 1);
        }
        //Serial.println(line);
      }
      idNumber = "";
      delay(750);
      checkingIn = false;
      setLCD("Please Enter ID#", 0);
      setLCD("                ", 1);
    }

title: Why is my keypad requiring a double-click only on the first row to register?

Answers: 0


body:
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
    }

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

Answers: 5

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);
      }
     }

body:
This is probably a bit advanced but...

You could use a base class and pointers to the derived LED and Buzzer classes to reduce you loop function to a loop.  You won't gain much at this level, but as you add more objects, such as the flashing headlights and mirror lights, maybe even a rear facing message board you will make life easier for your self.

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

    class BaseOutputObject
    {
    protected:
     int Pin;
    public:
     BaseOutputObject(const int& pin)
      : Pin(pin)
     {
      pinMode(Pin, OUTPUT);
     }
     virtual void Update()
     {
     }
    };

    class FlashingLED : public BaseOutputObject
    {
     long OnTime;
     long OffTime;
     int ledState;
     unsigned long previousMillis;
    public:
     FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
      : BaseOutputObject(pin)      // Call base class constructor
      , OnTime(on)       // Use initialisers rather than assignments
      , OffTime(off)
      , ledState(startLow ? LOW : HIGH)
      , previousMillis(0)
     {
     }

     void Update()
     {
      // check to see if it's time to change the state of the LED
      const unsigned long currentMillis = millis();   // Make it const because it won't change within this call of the function.

      if (currentMillis - previousMillis >= OnTime)
      {
       ledState = (ledState == LOW ? HIGH : LOW); // Toggle the state.
       previousMillis = currentMillis;  // Remember the time
       digitalWrite(Pin, ledState);  // Update the actual LED
      }
     }
    };

    class Buzzer : public BaseOutputObject
    {
     float SinValue;
     int ToneValue;
    public:
     Buzzer(const int& pin)
      : BaseOutputObject(pin)
      , SinValue(0.0f)  // Always initialise variables, in case you change the code later.
      , ToneValue(0)
     {
     }

     void Update()
     {
      for (int x = 0; x < 360; x++)
      {
       SinValue = sin(x * (PI / 180));
       ToneValue = 2000 + SinValue * 500;
       tone(Pin, ToneValue);
       delay(1);
      }
     }

    };

    // The objects could be declared dynamically, but thats not a great idea on embedded systems.
    FlashingLED ledOne(5, 100, 400);
    FlashingLED ledTwo(7, 100, 400);
    Buzzer buzzer(9);
    enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
    // Have to have pointers to the objects to allow you to cast them down to the base objects.
    BaseOutputObject* objects[MaxObjects] = {  &ledOne, &ledTwo, &buzzer};

    void setup()
    {
    }

    void loop()
    {
     for (int index = 0; index < MaxObjects; ++index)
     {
      objects[index]->Update();
     }
    }


body:
I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by `dnf` from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:

    "/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
    lto1: internal compiler error: Segmentation fault
    Please submit a full bug report,
    with preprocessed source if appropriate.
    See <https://bugzilla.redhat.com/> for instructions.
    lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
    compilation terminated.
    /usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
    collect2: error: ld returned 1 exit status
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.

I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

title: Segmentation fault at Serial.begin()

Answers: 1

body: There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


body:
I am new to Arduino.
I have currently connected a FSR sensor to the TOUT pin of ESP WROOM-02.
How do I add additional FSR sensor to ESP WROOM-02?
[![enter image description here][1]][1]

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

title: How to add additional sensors [Arduino]

Answers: 1

body:
An [FSR][1] (Force Sensing Resistor) varies in resistance as force or pressure is applied.  Most often such devices are connected to the positive power rail and the ADC input of a embedded micro controller.  At the same time a second known fixed resistor is connected to the opposite power rail (ground) and the same ADC input.  This forms a resistor divider network where the ADC in the embedded micro controller can measure the force applied to the FSR by measuring the voltage of the resistor divider.

To measure 2 or more FSRs using the same ADC input, consider connecting one lead of each FSR to a digital input/output pin of the embedded micro controller. Then connecting the other lead of each FSR to the ADC input.  To measure the force on the 1st FSR, configure the connected digital pin as a high ouput using software.  So that all the other FSRs do not influence the measurement, configure all the other digital pins to have high impedance.  Often this can be done by programming these other digital pins as inputs.  Cycle through all FSRs in a similar fashion using software.

  [1]: https://en.wikipedia.org/wiki/Force-sensing_resistor


body:
I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.

Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?

Thanks for your help

title: Multiple LED on arduino

Answers: 2

body: If you connect them in parallel instead of series you'll be able to turn them on and off with 3.6 volts (5 volts through an appropriate dropping resistor), assuming the Arduino can supply the current. [Here's](https://www.ledsupply.com/blog/wiring-leds-correctly-series-parallel-circuits-explained/) a general explanation of the difference.

body:
Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.

Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.

This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.


body:
I am trying to combine codes for my 3 sensors: GSR, Pulse sensor, and ECG but I keep getting errors. I have a poor background in coding. I have the 3 codes separately and I'm not the one who wrote them.
Here are the new Sketch after Combining the loops and the setups.I didn't get any error after uploading and verifying but I am not getting values in my Serial Monitor

Combined sketch:

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

    #include <Wire.h>
    #include "rgb_lcd.h"
    #define ANALOG_IN 2   // analog input pin to display
    #define OUTPUT_PIN 10 // test signal output pin
    #define PULSE_MS 250  // pulse width in ms

    int PulseSensorPurplePin = 1;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
    int LED13 = 13;   //  The on-board Arduion LED
    int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
    int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

    const int BUZZER=3;
        const int GSR=A0;
        int threshold=0;
        int sensorValue;
        rgb_lcd lcd;

    long ms;        // timer in ms
    int out = HIGH;     // output level

    void setup() {
       pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
       Serial.begin(9600);         // Set's up Serial Communication at certain speed.

       long sum=0;
          //VERIFY VALUE
          lcd.begin(16, 2);
          Serial.begin(9600);
          pinMode(BUZZER,OUTPUT);
          digitalWrite(BUZZER,LOW);
          delay(1000);
    //VERIFY VALUE
          for(int i=0;i<500;i++)
          {
          sensorValue=analogRead(GSR);
          sum += sensorValue;
          delay(5);
          }
          threshold = sum/500;
           Serial.print("threshold =");
           Serial.println(threshold);

           pinMode(OUTPUT_PIN, OUTPUT);    // set output pin mode
           Serial.begin(19200);        // initiate serial communication
           digitalWrite(OUTPUT_PIN, out);  // set initial digital output
           ms = millis();          // query current time (in ms)

    }

    void loop() {
      Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                                  // Assign this value to the "Signal" variable.

       Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

       if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
         digitalWrite(LED13,HIGH);
       } else {
         digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
       }

    delay(100);

       int temp;
          sensorValue=analogRead(GSR);
          Serial.print("sensorValue=");
          Serial.println(sensorValue);
          lcd.setCursor(0, 0);
          lcd.print("GSR Value: ");
          lcd.print(sensorValue);
          temp = threshold - sensorValue;
          if(abs(temp)>50)
          {
            sensorValue=analogRead(GSR);
            temp = threshold - sensorValue;
            if(abs(temp)>50){
           digitalWrite(BUZZER,HIGH);
            Serial.println("YES!");
            delay(3000);
            digitalWrite(BUZZER,LOW);
            delay(1000);}
          }

          int val = analogRead(ANALOG_IN);    // read voltage at input pin
      Serial.write( 0xff );         // write value to serial port
      Serial.write( (val >> 8) & 0xff );
      Serial.write( val & 0xff );

      if (millis() >= ms+PULSE_MS) {    // check if pulse width has elapsed
        ms = millis();            // query current time (in ms)
        out = !out;             // invert output value
        digitalWrite(OUTPUT_PIN, out);    // update digital output
      }
    }

title: Combining codes for 3 sensors

Answers: 1

body:
In general:

- There can be only one setup, in most cases you can put the code from all three setup's together, but checkout the code does not interfere, i.e. does not use the same pins. In that case, change the pin numbers if possible (and change the circuit accordingly).

- For the loops it can be more tricky:
  - Check how often each loop should be called. If one loop costs e.g. 500 ms that means the other loops will be called less often, which can affect the precision or even good readout of the sensor.
  - If all loops are relatively small and the duration do not matter, you can just call them after each other (rename the loops and call them one by one).
  - If there is a time constraint, than split the lengthy loop in a small part, and call it whenever needed. There is no clear rule for this.

What you can try is:

- Check for reach loop how long it takes
- Than for each loop add a delay with same time as the other loops, thus:
  - Test the duration (average) of loop 1, than of loop 2, than of loop 3. Assume loop1 takes 100, loop2 200 and loop3 300 ms.
  - Test loop1 without calling loop2 and loop3, but just add the delay (200+300=500 ms).
  - Check if it works, if so, it means you can call the other loops without problems.
  - Do the same for loop2 (with 100+300ms delay) and loop3 (100+200ms).
  - If all loops work correctly, than you can call the loop1, loop2, loop3 in sequence.
  - If not, you have to call the loop(s) that do not work either more often or in a different way.


body:
My system looks like this:

ESP8266 is connected to Arduino Uno (2, 3 pins) and a relay's data input to Arduino's pin 12 and power for relay is provided from another source.

Arduino gets data from server and switches on/off relay according to that signal. This system works perfectly for few hours and then suddenly crashes. In my WiFi console I have:

> wlan0: STA 2c:3a:e8:4e:bf:70 WPA: pairwise key handshake completed
> (RSN) wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0:
> AP-STA-DISCONNECTED 2c:3a:e8:4e:bf:70 wlan0: STA 2c:3a:e8:4e:bf:70
> IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11:
> associated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated
> wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA
> 2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: AP-STA-CONNECTED
> 2c:3a:e8:4e:bf:70

I have read [this Arduino question][1], but circuit diagram similar to that one. I get power from my PC to run Arduino.

This is my Arduino code :

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

    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2, 3); // RX, TX
    #endif

    char ssid[] = "RPi";            // your network SSID (name)
    char pass[] = "raspberry";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "192.168.50.1";

    unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds
    int testLED = 12;
    // Initialize the Ethernet client object
    WiFiEspClient client;

    void setup()
    {
      pinMode(testLED, OUTPUT);
      // initialize serial for debugging
      Serial.begin(9600);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println("You're connected to the network");

      //printWifiStatus();
    }

    void loop()
    {
      // if there's incoming data from the net connection send it out the serial port
      // this is for debugging purposes only
      while (client.available()) {
        char c = client.read();
        //code to run relay
        if (c == '#')
        {
          while (client.available() == 0) { } // Do nothing while we wait for the next value

          // reading the second charactor
          c = client.read();
          if (c == '1') {
            Serial.println("On");
            digitalWrite(testLED, HIGH);
            delay(600000);
          }
          else if (c == '0') {
            Serial.println("Off");
            digitalWrite(testLED, LOW);
            delay(600000);
          } //end of C cheking if-else
        }  //end of first charactor # if
        //end of replay code
      }
      // if 10 seconds have passed since your last connection,
      // then connect again and send data
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server
    void httpRequest()
    {
      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");

        // send the HTTP PUT request
        client.println(F("GET /simple.txt HTTP/1.1"));
        client.println(F("Host: localhost"));
        client.println("Connection: close");
        client.println();
        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        WiFi.begin(ssid, pass);
        Serial.println("Reconnecting again");
      }
    }

  [1]: https://arduino.stackexchange.com/questions/43641/esp8266-disconnects-after-relay-switch

title: ESP8266 disconnects after few hours

Answers: 3

body: As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.

body:
After quite long research I found the solution for my problem.

I did some changed power connection to ESP-8266.

ESP 8266    ---------  Arduino Uno

`Vcc`       --------->  3.3v

`CH_PD`     --------->  5v divided into 3.3v using resistors

`RX`        --------->  PIN-2 via 3.3v regulator.

After this configuration, my system was working perfectly for days. Thanks for the all suggestions given.

body: After four months of searching - Just use 3.3 V with 1.5 or 2 A and everything will work correctly.


body:
I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch [GitHub][1] that reads out the Euler data, I changed it a bit to print out quaternion data.

    #include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
    #include <Wire.h>

    NAxisMotion mySensor;         //Object that for the sensor
    unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
    const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

    void setup() //This code is executed once
    {
      //Peripheral Initialization
      Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
      I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
      //Sensor Initialization
      mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
      mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
      mySensor.setUpdateMode(MANUAL); //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
      //Setting to MANUAL requires fewer reads to the sensor
    }

    void loop() //This code is looped forever
    {
      if ((millis() - lastStreamTime) >= streamPeriod)
      {
        lastStreamTime = millis();
        mySensor.updateQuat();        //Update the Quat data into the structure of the object
        mySensor.updateCalibStatus();  //Update the Calibration Status

        Serial.print("Time: ");
        Serial.print(lastStreamTime);
        Serial.print("ms ");

        Serial.print(" W: ");
        Serial.print(mySensor.readQuatW());

        Serial.print(" X: ");
        Serial.print(mySensor.readQuatX());

        Serial.print(" Y: ");
        Serial.print(mySensor.readQuatY());

        Serial.print(" Z: ");
        Serial.print(mySensor.readQuatZ());

        Serial.println();
      }
    }

Here is a snippet of the "NAxisMotion.h" header file:

        /*******************************************************************************************
     *Description: This function is used to return the w-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatW(void);

     /*******************************************************************************************
     *Description: This function is used to return the x-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatX(void);

     /*******************************************************************************************
     *Description: This function is used to return the y-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatY(void);

     /*******************************************************************************************
     *Description: This function is used to return the z-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
        int16_t readQuatZ(void);

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array?
Because it seems the only way to access them is through "mySensor.readQuatX()"

  [1]: https://github.com/arduino-org/brackets-arduino/blob/master/libraries/NAxesMotion/Euler/Euler.ino

title: Store values in array

Answers: 1

body:
If I understand correctly you want to store a number of signed integers in an array.  Arrays have fixed sizes so you need to know the number of values you want to store.

    // Global declarations
    enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
    int16_t qData[MaxValues] = {0};

    // Code inside loop
    qData[WAxis] = readQuatW();
    qData[XAxis] = readQuatX();
    qData[YAxis] = readQuatY();
    qData[ZAxis] = readQuatZ();

    // Pass the array  of values to another function with the declaration
    // void SomeFunction (int *ar);
    // or
    // void SomeFunction (int ar[]);
    SomeFunction (qData);

Is that what you mean?


body:
How do you find how many bytes are currently waiting in the transmit buffer?

I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.

I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

title: How to find how much data in the transmit buffer?

Answers: 2

body:
> I now want to make sure the problem isn't because the serial buffer is
> overflowing, from the Arduino trying to send too much data.

If you are using the software serial Arduino library there is a way to [check for overflow][1].

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerialOverflow

body:
If you really want to know (not that it would do you any good) you can use the `Serial.availableForWrite()` function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.

    int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

I haven't tested it, but you may be able to use `SERIAL_TX_BUFFER_SIZE` instead of the `64` to make it properly portable.

    int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable


body: I need my ESP8266 web server to load my website files with `.php` extensions. So far I managed to load `.htm` `.css` and `.js` files from my SD card, but when I upload PHP files on my SD card, they won't run. How can I do that?

title: ESP8266 PHP Web Server

Answers: 1

body:
It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.

This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.

Your device can serve `.htm` `.css` and `.js` files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.


body:
I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.

I found this method on Arduino website in an example code:

<!-- language-all: lang-js -->

    while(!client) { ; } // waiting to get ready
Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.

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

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
    char server[] = "www.google.com";    // name address for Google (using DNS)

    IPAddress ip(192, 168, 1, 213);

    EthernetClient client;

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

      Ethernet.begin(mac, ip);
      delay(1000);
      //while(!client){ ; }
      Serial.println(Ethernet.localIP());
    }

title: Why Ethernet webclient fails to initiate?

Answers: 2

body:
What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).

so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).

body:
Your `while(!client){ ; }` line can never do anything useful.

It is used to wait for a client socket to connect to a remote port. You aren't connecting to a remote port (that `client` object is doing *nothing*), so how it can never succeed.

It's like saying "Do nothing, and tell me when you're done".

I don't know what you hope to achieve with that line of code...


body:
I am using a NodeMCU, so ESP8266. I installed the core via the Boards Manager at the last version.

My goal is to control a GoPro camera through WiFi.

I am getting mad with these few lines of code:

    uint8_t GoProControl::sendRequest(String request) {
       client.stop();
       if (!client.connect(_host.c_str(), _port)) {
      if (debugStatus){
          Serial.println("Connection lost");
          GoProConnected = false;
      }
        return false;
       }

     client.print(request);
     client.print("Connection: close\r\n\r\n");

     if (debugStatus){
      Serial.println("my request is:");
      Serial.println("-------------");
        Serial.print(request);
        Serial.print("Connection: close\r\n\r\n");
      Serial.println("-------------\n");
     }
       if (listen() == "HTTP/1.1 200 OK\r") {
         return true;
       }
       else {
         return false;
       }

    }

the client is connected without problem (it never gives me error) and so i send the request:

    GET http://10.5.5.9/camera/SH?t=password&p= HTTP/1.1
    Connection: close

the listen function mainly does:

    char c = client.read();
    response += c;

and then print the response, this is what i get from it:

    HTTP/1.1 404 Not Found
    Connection: close
    Date: Sat, 13 Jan 2018 16:26:27 GMT
    Server: Cherokee/1.2.101b150604_3b16072 (UNIX)
    Content-Length: 355
    Content-Type: text/html
    Cache-Control: no-cache
    Pragma: no-cache

    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    <title>404 Not Found</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

404 Not Found

    The requested URL /camera/SH was not found on this server.

    Cherokee web server 1.2.101b150604_3b16072 (UNIX), Port 80

It looks like I am connected to the wrong host.
Since I am sure that this is the correct request, where is possible that I am doing any error?

title: ESP8266WiFi client.print() strange response

Answers: 0


body:
I am trying to get working SIM808 with Arduino. Can GET and POST GPRS HTTP request but only what cames on it's just body from server side `{"error":true,"message":"Unauthorized"}`
but I need header as it brings cookie for session.

    +CREG: 0,1

    AT+SAPBR=3,1,"Contype","GPRS"

    OK

    AT+SAPBR=3,1,"APN","giffgaff.com"

    OK

    AT+SAPBR=3,1,"USER","giffgaff"

    OK

    AT+SAPBR=3,1,"PWD",""

    OK

    AT+SAPBR=1,1

    AT+SAPBR=2,1

    +SAPBR: 1,1,"xx.xxx.xxx.xxx"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","http://www.xxx.co.uk/index.php"

    OK
    AT+HTTPPARA="UA","MH Tracker"

    OK
    AT+HTTPPARA="CONTENT","Content-Length: 42"

    OK
    AT+HTTPPARA="CONTENT","Content-Type: application/x-www-form-urlencoded"

    OK
    AT+HTTPSSL=0

    OK
    AT+HTTPDATA=41,30000

    pass=xxxx&user=xxxx&action=xxxx

    OK

    AT+HTTPACTION=1

    OK

    +HTTPACTION: 1,401,39

    AT+HTTPREAD

    +HTTPREAD: 39

    {"error":true,"message":"Unauthorized"}

    OK

    AT+HTTPTERM

I got some results, but with error, looks like my code have some junk characters

any advice

POST /client/index.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.mhprojects.co.uk
Content-Length: 41

pass=xxx6&user=xxx&action=xxx

SEND OK
HTTP/1.1 400 Bad Request
Date: Thu, 01 Feb 2018 00:38:56 GMT
Server: Apache
Content-Length: 357
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>

Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.

Arduino code

    char data[350]="POST /client/index.php HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: www.mhprojects.co.uk\r\nContent-Length: 41\r\n\r\npass=xxx&user=xxx&action=xxx";
int PowerOn = 12;//Power on pin
int Reset = 11;//Reset pin
char aux_str[50];
//////////////
void setup() {

  pinMode(PowerOn, OUTPUT);
  pinMode(Reset, OUTPUT);
  Serial.begin(9600);// UART baud rate

  power_on();

  Serial.println(F("Powering ON"));
  Serial.println();
  Serial.println(F("Connecting to the network..."));

  while( send_command("AT+CREG?", "+CREG: 0,1", 1000)== 0 );

}

/////////////
void loop() {

char buffer[200];

if (send_command("AT+CIPMUX=0", "OK", 2000) == 1)// Selects Single-connection mode
  {
  if (send_command("AT+CSTT=\"giffgaff.com\",\"giffgaff\",\"\"", "OK", 2000) == 1)// Sets the APN, user name and password
    {
      if (send_command("AT+CIICR", "OK", 10000) == 1)// Brings Up Wireless Connection
        {
          if (send_command("AT+CIFSR", ".", 3000) == 1)// Gets Local IP Address
            {
              if (send_command("AT+CIPSTART=\"TCP\",\"www.mhprojects.co.uk\",\"80\"","CONNECT OK", 10000) == 1)// Opens a TCP socket
                  {
                     sprintf(aux_str,"AT+CIPSEND=%d", strlen(data));
                     if (send_command(aux_str, ">", 1000) == 1) {

                     send_command(data, "SEND OK", 1000);

                     while (true)  {

                     read_UART_buffer(buffer,sizeof(buffer), 0);

                     }
                     Serial.println(buffer);
                     }
                                }
                                else
                               {
                             Serial.println(F("Error setup TCP connection\r\n\r\n"));
                           }
                        }
                      else
                    {
                  Serial.println(F("Error getting the IP address\r\n\r\n"));
                }
              }
             else
           {
         Serial.println(F("Error bring up wireless connection\r\n\r\n"));
        }
      }
    else
  {
Serial.print(F("Error setting the APN\r\n\r\n"));
    }
      }
        else
        {
          Serial.print(F("Error setting the single connection\r\n\r\n"));
         }

    send_command("AT+CIPCLOSE", "CLOSE OK", 1000);

    send_command("AT+CIPSHUT", "SHUT OK", 1000);

}

////////////////
void power_on() {

        // power on pulse
        digitalWrite(PowerOn,LOW);
        delay(500);
        digitalWrite(PowerOn,HIGH);
        delay(3000);
        digitalWrite(PowerOn,LOW);
        delay(3000);
}

///////////////
void reset()  {
  digitalWrite(Reset,LOW);
  delay(500);
  digitalWrite(Reset,HIGH);
  delay(3000);
  digitalWrite(PowerOn,LOW);
  delay(500);
}

///////////////////////////////////////////////////////////////////////////////////
int8_t send_command(char* ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0,  answer = 0;
  char response[50];
  unsigned long previous;

  memset(response, '\0', 50);    // Initialice the string

  delay(100);

  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer

    Serial.println();
    Serial.println();
    Serial.println(ATcommand);    // Send the AT command

  x = 0;
  previous = millis();

  // this loop waits for the answer
  do {
    if (Serial.available() != 0) {  // if there are data in the UART input buffer, reads it and checks for the asnwer
      response[x] = Serial.read();
      Serial.print(response[x]);
      x++;
      if (strstr(response, expected_answer) != NULL)    // check if the desired answer (OK) is in the response of the module
      {
        answer = 1;
      }
    }
  }

  while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  return answer;
  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer
}

////////////////////////////////////////////////////////////
void read_UART_buffer(char *buffer,int count, unsigned int timeOut) {
  int i = 0;
  unsigned long timerStart;
  timerStart = millis();

 while(1) {
  while  (Serial.available()!=0){
    Serial.write(Serial.read());
    char c = Serial.read();
    buffer[i++] = c;

  }
  //buffer[i]='\0';
    if((unsigned long) (millis() - timerStart)  > timeOut * 1000UL) {
            break;
        }
 }
}

title: Arduino + SIM808 HTTP GET POST headers

Answers: 1

body:
Are you sure the Content length is 41? Doesn't seem like it, make sure it's the same length as your message body.

This depends from server to server, but I think you should also put a CRLF after your message body.


body:
I'm new to Arduino - just got an ESP32-based Adafruit Feather HUZZAH32. I got it up and running on my Macbook Air (High Sierra) with no problem, following the instructions at this page linked from the [Adafruit page on the HUZZAH32][1]:

https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/mac.md (dead link)

Basically, install the Arduino IDE, install the Espressif stuff using a big shell command, and install the driver for the CP2104 USB->UART bridge.

It worked like a charm on the Macbook Air, no problem. But it was a different story when I went to install it on my 2009 vintage Mac Pro running El Capitan. Everything seemed to install ok, and the Arduino IDE runs and shows "Adafruit ESP32 Feather" (under Tools->Board).
However, when I try to upload a sketch (the "Blink" built-in example), it compiles ok but seems to hang while uploading, eventually finishing after about 5 minutes.  But the sketch isn't there, the one I previously uploaded from the HighSierra machine still executing.

Furthermore, it does weird things to the Mac: the System Profiler (About This Mac) no longer runs (shown as "Not Responding" in Activity Monitor), even after I've quit the IDE; occasionally I can't even seem to quit the IDE; and next time my computer sleeps, it can't be woken up (I have to restart with the power button).   Another thing: when I start the upload, the kernel-task (PID 0) starts using over 100% of the CPU (from Activity Monitor).

Maybe it's a version compatability issue with the Espressif uploader?   Or maybe I screwed up with the CP2104 driver, first installing the one here, [CP210x USB to UART Bridge VCP Drivers][2], as pointed to by the [How-To at Adafruit][1], and when things did not work, and the uninstall shell script for the driver failed too, I just deleted what seemed to be the relevant files before then installing the "legacy" driver, which also did not work.

Looked at some of the debugging stuff here ... The CP2104 driver shows up under USB in System Profiler, and both `cu.SLAB_USBtoUART` and `tty.SLAB_USBtoUART` show up under `/dev` (in Terminal).   So nothing seems wrong there.

Here is a screen grab (with verbose output for upload selected):
```none
Archiving built core (caching) in:
 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_cache_759917/core/core_espressif_esp32_featheresp32_FlashFreq_80,UploadSpeed_921600,DebugLevel_none_4423141e818963094868f9e8ffa4e8ec.a

Sketch uses 136741 bytes (10%) of program storage space. Maximum is 1310720 bytes.

Global variables use 10908 bytes (3%) of dynamic memory, leaving 284004 bytes for local variables. Maximum is 294912 bytes.

/Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/esptool --chip esp32 --port /dev/cu.SLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/partitions/boot_app0.bin 0x1000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.bin 0x8000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.partitions.bin
```

It just seems to be a very long command line to run esptool, and then... nothing.

I'm at a loss - I've asked at Adafruit forums: [trouble getting HUZZAH32 working on Mac][3]

... and filed an "issue" at the Github page too: [upload hangs on older Mac configuration (Mac Pro 4,1 w/ El Capitan) #983][4]

In short, this Github issue says that the thing works fine on the USB ports on the rear of my Apple monitor, but hangs (as described in OP) on the ones on the front of the Mac Pro tower as well as the ones on the rear of the tower (including the one into which the monitor was plugged).

  [1]: https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/using-with-arduino-ide
  [2]: https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
  [3]: https://forums.adafruit.com/viewtopic.php?f=57&t=128986
  [4]: https://github.com/espressif/arduino-esp32/issues/983

title: Adafruit ESP32 device working on OSX 10.13 but not on OSX 10.11 on older machine

Answers: 0