message:
RFID RC522 reads the previous tag serial with different tag

I hope someone can help me.

I'm using a Mega with RC522, and this happens:

I use a tag, it reads the right serial (e.g. AA:BB:CC:DD). Then I use a second tag and sometimes it gives me the correct value (e.g. 00:11:22:33), but often it gives me the previous tag serial (AA:BB:CC:DD). After a few attempts, it finally gives me the right one (00:11:22:33).

I really can't find what's wrong and i'd be grateful if someone could shed some light.

Here's the code:

    if (RC522.PICC_IsNewCardPresent())  {
               RC522.PICC_ReadCardSerial();
              String strID = "";
            for (byte i = 0; i < 4; i++) {
              strID +=
                (RC522.uid.uidByte[i] < 0x10 ? "0" : "") +
                String(RC522.uid.uidByte[i], HEX) +
                (i != 3 ? ":" : "");
            }
            String seriale = strID;

            if (seriale != "0"){

              for(h=0; h<=numerogiocatori -1;h++){

                if (seriale == seriali[h]) {
                  lcd.clear();
                  lcd.print("Saldo Gioc. ") ;
                  lcd.print(h + 1) ;
                  Serial.print("tag ID: ");
                  Serial.print(seriale);
                  Serial.print(" .    ");
                  lcd.setCursor(0, 1);
                  lcd.print(totaledenaro[h]) ;
                  delay(1500);
                  lcd.clear();
                  lcd.print("Importo");
                  lcd.setCursor(0, 1);
                }
              }
            }}}

Thanks to anyone willing to help!

body:
One rule for writing safety code is :

*The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked inside each function.*

You forgot to check if the tag has been readed i.e the return value of PICC_ReadCardSerial. If it fails the value is not updated, that is the reason why the value is still the old one.

Using the following code (from the ReadNUID example of the MFRC522 library https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino)

    // Init array that will store new NUID
    byte nuidPICC[4];

    void loop() {

      // Look for new cards
      if ( ! rfid.PICC_IsNewCardPresent())
        return;

      // Verify if the NUID has been readed
      if ( ! rfid.PICC_ReadCardSerial())
        Serial.println(F("NUID has NOT been readed."));

      if (rfid.uid.uidByte[0] != nuidPICC[0] ||
        rfid.uid.uidByte[1] != nuidPICC[1] ||
        rfid.uid.uidByte[2] != nuidPICC[2] ||
        rfid.uid.uidByte[3] != nuidPICC[3] ) {
        Serial.println(F("A new card has been detected."));

        // Store NUID into nuidPICC array
        for (byte i = 0; i < 4; i++) {
          nuidPICC[i] = rfid.uid.uidByte[i];
        }

        Serial.println(F("The NUID tag is:"));
        printHex(rfid.uid.uidByte, rfid.uid.size);
        Serial.println();
      }
      else Serial.println(F("Card read previously."));

      // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
    }

    void printHex(byte *buffer, byte bufferSize) {
          for (byte i = 0; i < bufferSize; i++) {
            Serial.print(buffer[i] < 0x10 ? " 0" : " ");
            Serial.print(buffer[i], HEX);
      }
    }

the result is
>A new card has been detected.

>The NUID tag is:

> 97 C6 6E 09

>**NUID has NOT been readed.

>Card read previously.**

>A new card has been detected.

>The NUID tag is:

> CC 16 5D 83

>A new card has been detected.

>The NUID tag is:

> 97 C6 6E 09

>**NUID has NOT been readed.

>Card read previously.**

>A new card has been detected.

>The NUID tag is:

> CC 16 5D 83

Sometimes when the second tag is used the tag is not read and the uid remains the same.


sender: user

message:
How do I turn on/off led with the same IR button?

I'm trying to make the led switch on/off by the same case(): code.
But its not working could anyone help me?

sender: assistant

body:
It would be good if you add your sketch if you have one.

In principle, you have to create a boolean variable which keeps the current state of the LED. When you get an IR command, inside the IR button handler invert the state of the boolean. Than change the LED accordingly.

Something like:

Const/Global variable:

    #define LED_PIN 8

    int ledState;

In setup:

     ledState = FALSE;
     digitalWrite(LED_PIN, ledState);

In side loop:

    case IR_BUTTON_CHANGE_LED:
       ledState = ledState == LOW ? HIGH : LOW; // Invert state
       digitalWrite(LED_PIN, ledState); // Set LED according to state
       break;


message:
How to rotate two or more steppers simultaneously by giving ARRAY of angles?

The following is the code that I am trying but the problem is steppers rotate one after each other. However, I want to rotate steppers simultaneously.
This code for two stepper motors.

    int pulse=3;

    int direc=4;

    int pulse1=5;

    int direc1=6;

    int i,j,k;

    float angle[5][3]={{360,360,3},{7,8,9},{11,12,13},{14,15,16},{17,18,19}};

    float steps;

    void motor1(){

      for(k = 0; k<=4; k++){

        Serial.println(angle[k][0]);

        steps = (1600*angle[k][0])/360;

        Serial.println(steps);

        for(j = 0; j<=steps;j++){

          digitalWrite(3,HIGH);

          delayMicroseconds(100);

          digitalWrite(3,LOW);

          delayMicroseconds(100);
            }

    }

    }

    void motor2(){

      for(k = 0; k<=4; k++){

        Serial.println(angle[k][1]);

        steps = (1600*angle[k][1])/360;

        Serial.println(steps);

        for(j = 0; j<=steps;j++){

          digitalWrite(5,HIGH);

          delayMicroseconds(100);

          digitalWrite(5,LOW);

          delayMicroseconds(100);

            }

    }

    }

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

      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
    }

    void loop(){
        motor1();

        motor2();

       //while(1);
    }

body:
I can't understand clearly what you want, but maybe you want to drive your two servos simultaneously. To do this, after you determine the angle of servos, you can drive them without delay between their commands.

Like you use above, you can't drive them at the same time, there are loops and they have to be completed before the next instruction is run so your servos wait each other.

Here is a good example code for you:

    #include <Servo.h>

    Servo myservo1;  // create servo object to control a servo
    Servo myservo2;  // create servo object to control a servo

    float angle[5][3]={{360,360,3},{7,8,9},{11,12,13},{14,15,16},{17,18,19}};

    void setup() {
      myservo1.attach(9);  // attaches the servo on pin 9 to the servo object
      myservo2.attach(10);  // attaches the servo on pin 10 to the servo object
    }

    void loop() {
      for(k = 0; k<=4; k++){
        pos = (1600*angle[k][0])/360; //Calculate the angle which you want

        //The most impportant part, there shouldn't be a delay between them
        myservo1.write(pos);              // tell servo to go to position in variable 'pos'
        myservo2.write(pos);              // tell servo to go to position in variable 'pos'

        delay(1000);                       // waits 1000ms for the servo to reach the position
      }
    }


body:
(Half a year ago, but what the hey...)

Your motor1() and motor2() are currently written as:

    do until done:
      take a step
      wait
    end

, so yeah, one finishes before the next one even starts.

Each motor function needs to do:

    if motor's current-position is not the final position,
       if it is time to take a step,
          take a step
          calc when to take another step
          calc motor's new current-position
       end
    end

Now call your motor functions *as frequently as possible*. Notice that either `if` test can cause the function to return without doing anything - that is *intentional*.

This is non-blocking programming - coding in such a way that *nothing keeps control while waiting for something to happen* (clock ticks, in this case), it just does something, or does nothing, *right now*, if there is or is not something to do right now, but it *does release the processor* (the function returns immediately) whether it did something or not.

I call these functions "maybe-do" functions:

 - maybe step a motor (if, and only if, a certain interval has passed, step the motor);

 - maybe light an LED (if, and only if, the button is being pressed and it wasn't pressed the last time we looked, turn on the LED;

 - maybe read the terminal keyboard (if there is at least one character in the Serial input buffer, collect a character).

Then your loop() function should do *nothing but* call each maybe-do function, in sequence, as *fast as possible*. And it follows from the above that your maybe-do functions need to execute as quickly as possible and do no more than is necessary to (1) decide whether to act, and if so, (2) to carry out its action, and (3) in either case, return immediately.

<br>
And - Bang-Boom! - right there is a half-semester course in block-free programming without interrupts!


message:
Coin recognition using Coin Accepter in Arduino Uno

I'm working on a vending machine project and I'm using CH-926 and an Arduino Uno for that. I've already set the coin accepter for different number of coins and respective output pulses. I'm unable to get the desired output for this. With every coin I insert the output varies even when I put the same coin.

    int pulse = 0;

    void coin_value() {
      pulse = pulse + 1;
    }

    void setup() {
      Serial.begin(9600);
      pinMode(2, INPUT);
      Serial.println("Ready to be collected");
    }

    void loop() {
      if (digitalRead(2) == HIGH) {
        attachInterrupt(0, coin_value, FALLING);

        if (pulse == 3) {
          Serial.println("50");
        }
        if (pulse == 2) {
          Serial.println("20");
        }
        if (pulse == 1) {
          Serial.println("10");
        }
      }

      pulse = 0;
    }

For each coin there are different specific pulses which helps to recognize the coin.`int pulse=0;`.

So when I insert coin 1 then the output should be 10, for coin 2 the output should be 20 and for coin 3 the output should be 50.

body:
Your code is faulty in a number of respects.

---

1. `pulse` should be declared volatile, i.e.

        volatile int pulse = 0;

    That is because it can change in an interrupt service routine.

---

2. You should only do `attachInterrupt` once, in `setup`.

---

3. Your code to display the count will be timing dependent. What if you happen to display the count after one pulse has arrived, but before they all have? Then you set the count back to zero.

---

Better would be something like this, untested however:

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

    volatile int pulse = 0;

    void coin_value() {
      pulse = pulse + 1;
    }

    void setup() {
      Serial.begin(9600);
      pinMode(2, INPUT);
      Serial.println("Ready to be collected");
      attachInterrupt(0, coin_value, FALLING);
    }

    void loop() {

      if (pulse > 0)
        {
        delay (1000);   // let the other pulses arrive
        if (pulse == 3) {
          Serial.println("50");
        }
        if (pulse == 2) {
          Serial.println("20");
        }
        if (pulse == 1) {
          Serial.println("10");
        }
        pulse = 0;  // clear for next time
      }

    }

---

(Edited to add)

Even then your test for 1/2/3 might fail if the coin acceptor sends the pulses twice. Then you might get 2/4/6 pulses. You probably need to display something if there is another count, eg.

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

      if (pulse == 3) {
        Serial.println("50");
      }
      else if (pulse == 2) {
        Serial.println("20");
      }
      else if (pulse == 1) {
        Serial.println("10");
      }
      else {
         Serial.print ("Unexpected number of pulses: ");
         Serial.println (pulse);
      }


body:
First of all you said

> So when I insert coin 1 then the output should be 10, for coin 2 the
> output should be 20 and for coin 3 the output should be 50.

Yes coin 3 would be 50 but it does not means that coin 3 has 3 impulses(he will have 5 impulse), I recommend to you always use this formula:

> Coin_Value = Pulse_Count * Denomination.

I don't recommend to you use 3 Impulses from coin acceptor Because you don't have 15 cent and 30 cent coins. In most cases Coin acceptors have:

> 1/4 1/2 1 2 4 5 8 10 impulses

Generally I prefer to save all data in variables

So lets get to variables for code

    const int coinIntPin = 2;          //interruptPin 0 is digital pin 2
    volatile boolean newCoin = false;
    volatile int pulseCount;          //counts pulse for
    volatile int timeOut = 0;         //counts timeout after last coin inserted
    float coinType;
    float denomination = 0.50;         // in my case 1 Pulse = 0.50 $
    int max_impulse = 4;              // this is the maximum impulses I use
    volatile long timeFPulse = 0;     // to determine when First impulse was interrupted
    volatile long interval;           // to determine interval from first and last impulse

And always use attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); [It is recommended by Arduino][1]  as below:

  [1]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

    void setup(){
        Serial.begin(9600);
        attachInterrupt(digitalPinToInterrupt(coinIntPin), coinInserted, FALLING);

    }

And I will give you rest of code:

    void coinInserted(){
        newCoin = true;
        timeFPulse = millis();
        pulseCount++;
    }

    void loop()
    {

         while (newCoin == true)
        {
                interval = millis() - timeFPulse;  //interval from first and last impulse
                if(pulseCount == max_impulse || (interval > 500 && pulseCount > 0)) //Max_impulse will avoid any extra impulses for any reason.
                {
    // This is the reason why I recommended to you use 1 2 4 5 10 20 Impulses instead of 3 7 9 etc...
                  coinType = pulseCount * denomination;
                  newCoin = false;
                  sendData();
                  delay(5);

                 }

        }
    }

    void sendData(){
      Serial.print("Do what ever you want. Inserted Money = ");
      Serial.println(coinType);
      coinType = 0;  // remove if you want to save Coins and print sum of inserted coins
      pulseCount = 0;  // remove if you want to save impulses determined by coin acceptor
    }

And Finally look at ( interval > 500 ) If you have different max impulses you must change 500 to (impulse length * Max impulses + 100); so if you have max 10 impulses you must enter 1100 and not 500 (in my case);


message:
How can i stop a loop after 1 minute?

This is my first Arduino project, and I would like to stop my servo's loop after 1 minute. Can someone help me?

    #include <Servo.h>
    Servo myservo;

    void setup()
    {
      myservo.attach(5);
    }

    void loop()
    {
      myservo.write(45);
      delay(1000);
      myservo.write(125);
      delay(1000);
    }

Thanks!

body:
To answer your question as asked, add this to `loop()`:

    if (millis() >= 60000) exit(0);

However, I would suggest you seriously consider Jot's comment: simply
stopping `loop()` from running is most of the time _not_ what you may
want to do.


body:
As suggested by Jot in a comment, one way would be to simply do what you want (which takes roughly two seconds per iteration) in a loop, like this:

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

    #include <Servo.h>
    Servo myservo;

    void setup()
    {
      myservo.attach(5);

      for (int i = 0; i < 30; i++)
        {
        myservo.write(45);
        delay(1000);
        myservo.write(125);
        delay(1000);
        }
    }

    void loop()
    {
    }

---

The problem with that is it relies upon knowing how long your delays are, and assumes that the `myservo.write()` functions take no time. A better method is:

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

    #include <Servo.h>
    Servo myservo;

    void setup()
    {
      myservo.attach(5);

      unsigned long start = millis ();

      while (millis () - start <= 60000)  // for 60 seconds
        {
        myservo.write(45);
        delay(1000);
        myservo.write(125);
        delay(1000);
        }
    }

    void loop()
    {
    }

This uses the `millis()` function call to find out how much time has elapsed, and wait for 60000 milliseconds (60 seconds).

---

I've put the code into `setup` because that is where you put things you want done once.


body:
Another way to handle this is to use a variable endTime to tell the loop when to stop moving the servo:

    unsigned long endTime;

    void setup()
    {
      myservo.attach(5);
      endTime = millis() + 60000;
    }

    void loop()
    {
      if (millis() <= endTime) {
        myservo.write(45);
        delay(1000);
        myservo.write(125);
        delay(1000);
      } else {
        //code to run once the servo is done running
      }
    }

This code will move the servo back and forth for about 1 minute, then stop. It's set up so you can do something else once the loop has completed.

Note that by using a variable endTime and leaving your servo code in the loop() function, you can have your program start doing something else once the motor motion is completed. You can also add code to set up a new value in EndTime, at which point the servo will start moving back and forth again.

Also note that using delay is bad practice. When you do that you bring the arduino to a full stop while the delay code is running. You can't be doing something else. Say, for example, you wanted to move 2 different servos at different time intervals.

Instead of using delays you should track the end time for each phase of your loop, and execute your code once that end time passes.


message:
Detect DS18B20 sensors and correctly assign them to relays

I'm relatively new to microcontroller programming, so please excuse me if my question is dumb. I've created a simple device that allows me to control 4 relays based on temperature. I bought four DS18B20 sensors, 4 relay board and Wemos D1. Everything works fine - I'm able to read the temperature of each sensor based on their address.

But I started wondering how I can replace a single DS18B20 without recompiling the code; currently this isn't possible. After searching a bit I found a couple of questions about the order of 1Wire sensors. For example, [this one.][1] I have no control over the order in which sensors are detected.

Is there a best practice when it comes to configuring DS18B20 sensors?
I would like to set up my device. By set up, I mean that I would like to assign a specific DS18B20 to a specific relay.

I imagine it like so:

 1. Take a new DS18B20, connect it to a device and power the device.
 2. The device should scan for DS18B20 sensors. If it finds one then it should assign it to relay 1 and store its address in EEPROM.
 3. Then unplug the device from power, plug the second DS18B20 and power the device again.
 4. The device again scans for DS18B20 sensors. It finds 2 devices. The first one is known (the address was stored in EEPROM) so it is skipped. The second is assigned to relay 2 and the address is stored in EEPROM.
 5. The same procedure is applied to the third and fourth sensors.
 6. If four sensors are connected (the addresses are from EEPROM), then the device can run.
 7. When the user wants to replace a non-functioning sensor, the same procedure can be used.

As I wrote, I'm new to microcontroller programming, so if there is a better way please let me know. I'm mostly learning by following examples and tutorials, so if anyone knows of an example showing such a configuration procedure I'll be grateful for any materials.

  [1]: https://arduino.stackexchange.com/questions/34104/ds18b20-order-of-sensors-on-a-cable

body:
If you can easily disconnect the sensors one at a time then your way is fine.

If you can't easily disconnect them then you can maybe use readings to set the order, although this depends on the environment. If, for example, all the sensors are generally room temperature then you have the code check the temp of all the sensors at start up. If it finds one sensor at less than 0C then assign that sensor to the least-recently-replaced relay index (also stored in EEPROM).

Then when you want to put a sensor into the working set, hold an ice cube on it for a few seconds before powering up the controller. There are other combinations of this technique you can imagine that use a button or jumper wires to specifically set the index of the out-of-range-at-startup sensor.

Alternately if you have an extra pin on the Arduino, then you can make a procedure where you connect a new sensor to that pin before attaching it to the string. You can make a rule like "if you ever see a sensor on pin X then remember its device ID and assign it to relay Y". There are lots of UI ways to pick Y. Note that [you do not even need any extra hardware for this][1].

  [1]: https://wp.josh.com/2014/06/23/no-external-pull-up-needed-for-ds18b20-temp-sensor/


message:
Lowest latency triggering multiple Arduinos using NRF24L01+

I'm building a rig with multiple DSLR cameras.  I need to synchronize the cameras to take a photos with lowest possible latency.  The only constraint is we want the ability to address each camera individually if needed.

I've seen in other posts:
https://arduino.stackexchange.com/questions/13233/choosing-wireless-tech-for-lowest-possible-lag

NRF24L01+ seems to be a good choice.  An answer on that post states:
sending a 32 byte payload...283µs on 2Mbps mode.

Given the  esp8266 has a clock speed of 80MHz/160MHz I'm not too concerned about the lag involved in processing the signals.

Most multi-cast information out there is for sensor arrays, so multiple out single in.  I'm after resources on single out multiple in for NRF24L01+ networks.

Added bonus of esp8266 is that non timing critical tasks such as logging and error checking could be performed over wifi so NRF24L01+ would be purely for one -way triggering.

If each camera had it's own esp8266 based board with attached NRF24L01+ hardware and was given an address in software from 0-255, is it possible to broadcast a single 32 byte packet of data where each bit would represent a camera address and have all receiver devices receive the same signal, do an AND against it's address and trigger if needed?

body:
Yes, that should work, however also think about the following issues:

- What if one (or more) camera does not receive the signal? You might need to add an ACK signal, but of course this will reduce the latency (a lot). If you don't want an ACK signal
- To prevent an ACK, you can send the signal many times (and cameras who already processed the signal not react for a fixed amount of time). Of course it will received by the other cameras (at least) 283 us later.
- If reliability is important, you could try using a less high speed, the latency will go up, but reality too.

Also you probably can fire the cameras even faster, if you first send the address bytes (4 bytes). And than send the shoot signal which can be in principle 1 bit. You can use one of the bits for that in case 128 cameras would suffice. Or send one byte extra which contains the signal to shoot.


message:
Arduino Micro draws too much power from iPhone. How can I change that?

I'm building a USB keyboard that has two buttons - space and enter. The plan is to use this USB keyboard (with an Apple Lightning connector to USB) with the built in iOS switch control. I bought the lightning to USB dongle, and hooked it up to a normal keyboard, and it works fine.

Next, I took an Arduino Micro (ATMEGA32u4) and programed it to act as a keyboard with the two keys I need (space and enter). On a PC, it works just fine, but when I hook it up to my iPhone, I get the message:

    Arduino Micro: The connected device requires too much power.
I've done quite a bit of research on this, and I found [this][1] post. In a nutshell, that post said that when you connect a device to an iOS device, one of the first things it does is tell the iDevice how much current it *could potentially* draw. This number (about 200mA for the Arduino Micro) is what decides whether the iDevice will support the device or not, when in truth, the device will not come close to its max current draw, at least not in my case.

I hooked up a meter to the normal keyboard, and it draws just over 4mA. When I hook up the Arduino, it is drawing almost 40mA. While the Arduino is drawing much more than the keyboard, it should be okay, because when I plugged in a flash drive, it was drawing 50mA, but the iPhone didn't complain.

There is my story, here is my question:

Is there any way to change it so that the Arduino Micro doesn't request so much power? In other words, is there a way to reset the value that is causing the iPhone to not use the device?

----------

  [1]: https://arduino.stackexchange.com/questions/37343/high-power-consumption-of-atmega32u4-when-connected-to-ios-device

body:
Yes, but it requires manual modification of the Arduino core software.

1. Find the file `USBCore.h` within your AVR boards installation (it could be in the data storage folder wherever that is on your OS, or within the actual IDE software)
2. Look for the line `#define D_CONFIG(_totalLength,_interfaces) \`
3. The *next* line has the power setting.  Change `USB_CONFIG_POWER_MA(500)` to what you require (for example `USB_CONFIG_POWER_MA(50)`


body:
The power consumption is part of the exchange with the PC when it is plugged in. You can change that. Find the file `USBCore.h` in your Arduino install directory. In my case (under Linux) it was:

    ./hardware/arduino/avr/cores/arduino/USBCore.h

Inside that file, at around line 269 (depending on the distribution) you should see these lines:

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

    #define D_CONFIG(_totalLength,_interfaces) \
     { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

On the right of the second line is the requested power consumption in milliamps (currently 500). Change that to (say) 100:

That is, change `USB_CONFIG_POWER_MA(500)` to `USB_CONFIG_POWER_MA(100)`.

Save and recompile.

You may find that the bootloader initially requests 500 mA even with this change (as it initially runs the bootloader). However when the sketch starts it should re-establish a USB connection and only request 100 mA. To fix that you would need to recompile the bootloader with the same fix, and reinstall it, a somewhat more complex task.

Another possible approach would be to tweak the fuses so that it doesn't run the bootloader, if you have finished debugging your code. Only do that if you are confident with playing with the fuses.


message:
Splitting a Serial.readString into string array

I am working on a project where I need to split incoming data from serial (time to be exact, so aa:bb:cc) and need to split it into aa then bb and cc, ideally into  an array. I know I could use readStringUntil and make 3 separate variables, but I would prefer it is in arrays. Here is the code that supposed to do this. It works with predefined string (eg. 00:00:00), but with reading serial it says that the initializer fails to determine size of "input".
Thank you in advance for helpful suggestions.

Here is the code:

    void setup() {
     FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      Serial.begin(9600);
      while(!Serial.available()){} //wait until Serial data received
      String vst = Serial.readString();
      char buf[vst.length()+1];
      vst.toCharArray(buf, vst.length());
      char input[] = vst;
      char delic[] = ":";
      char* sub = strtok(input, delic);
      while(sub != NULL){
       Serial.println(ptr);
        sub = strtok(NULL, delic);
      }
}

body:
Your main problem is this:

    char buf[vst.length()+1];

You can't initialize an array with the return value of a function.

Instead you would need to use `alloca` to perform the same function:

    char *buf = alloca(vst.length()+1);

However, the way you're doing it is wasteful. You don't need `buf` at all.  You can directly access and manipulate the internal `char` buffer inside the string using `vst.c_str();`.

For convenience you can point `buf` at it:

    char *buf = vst.c_str();

To complete the picture here's a routine that takes the string and gives you three integers. Since we expect a specific format with only 3 sections to it we don't really need a loop.

    // Use readStringUntil to avoid the 1 second delay.
    String vst = Serial.readStringUntil('\n');
    char *buf = vst.c_str();

    char *hourString = strtok(buf, ":");
    char *minuteString = strtok(NULL, ":");
    char *secondString = strtok(NULL, ":");

    if (secondString != NULL) { // Will only be true if we have two colons
        int hours = atoi(hourString);
        int minutes = atoi(minuteString);
        int seconds = atoi(secondString);

        Serial.print("It is ");
        Serial.print(minutes);
        Serial.print(" and ");
        Serial.print(seconds);
        Serial.print(" seconds past ");
        Serial.println(hours);
    } else {
        Serial.println("Invalid time format");
    }


message:
Memory problem? dtostr() and strcat()

I've been dealing with this for quite a while now and searching all over for answers.. I'm trying to put together two floats into a char*. Separated by a ",".
This is the code I'm working with.
<!-- language-all: lang-cpp -->

    #include <DHT.h>
    #include <RH_ASK.h>
    #include <SPI.h>

    #define DHT_pin 10
    #define DHT_type DHT11

    DHT dht(DHT_pin, DHT_type);
    RH_ASK rf_driver;

    float temp;
    float hum;

    char ch_temp[6];
    char ch_hum[6];
    char msg_out[12] = "";

    void setup() {
      Serial.begin (115200);
      dht.begin();
      if (rf_driver.init()) {
        Serial.println("Radio transmitter initiated..");
      }
      else {
        Serial.println("Radio transmitter failed to initiate..");
        delay(1000);
      }
    }
    void loop() {
      temp = dht.readTemperature();
      hum = dht.readHumidity();

      dtostrf(temp, 5, 2, ch_temp);
      dtostrf(hum, 5, 2, ch_hum);
      strcat(msg_out, ch_temp);
      strcat(msg_out, ",");
      strcat(msg_out, ch_hum);

      Serial.println(msg_out);
      rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
      rf_driver.waitPacketSent();
      Serial.print("data sent, package size: ");
      Serial.println(strlen(msg_out));
      delay(1000);

    }

I have tried using different sizes of the char arrays, but it just goes crazy.
This is the console output:

    Radio transmitter initiated..
    22.00,34.00
    data sent, package size: 11
    ⸮⸮Radio transmitter initiated..
    22.00,34.00
    data sent, package size: 11

So on its way through the second loop it fails, restarts and then on its third way through it just gives up... What am I doing wrong? :( Really sad over this.

body:
If you remove the RF and sensor code, the sketch seems to work correctly when printing to the serial monitor. The first time you call `rf_driver.send()` in the loop, it works. The second time through the loop, and every time there after, it starts printing corrupted data. I don't have a definitive answer why this is happening, but I do have a way to "fix" it (or a "hack", if you prefer to call it that).

Using `memset()` to set the `msg_out` char array to all 0's **before** you use it seems to fix the problem. Here is a test sketch which is very similar to yours. I'm using some hard coded values for the sensor data because I don't have one of those sensors.

    #include <RH_ASK.h>
    #include <SPI.h>
    RH_ASK rf_driver;

    float temp;
    float hum;

    char ch_temp[6];
    char ch_hum[6];
    char msg_out[12] = "";

    void setup() {
      Serial.begin (9600);
      if (rf_driver.init()) {
        Serial.println("Radio transmitter initiated..");
      }
      else {
        Serial.println("Radio transmitter failed to initiate..");
        delay(1000);
      }
    }
    void loop() {

      // Set the buffer contents to all 0's
      memset(msg_out, 0, sizeof(msg_out));

      temp = 12.345;
      hum = 67.890;

      dtostrf(temp, 5, 2, ch_temp);
      dtostrf(hum, 5, 2, ch_hum);
      strcat(msg_out, ch_temp);
      strcat(msg_out, ",");
      strcat(msg_out, ch_hum);

      Serial.println(msg_out);
      rf_driver.send((uint8_t *)msg_out, strlen(msg_out));
      rf_driver.waitPacketSent();
      Serial.print("data sent, package size: ");
      Serial.println(strlen(msg_out));
      delay(1000);
    }


body:
Your sketch is running on borrowed memory.
Every time the loop function runs, the new text is concatenated with `strcat()` and the buffer `msg_out` is never reset.
The first time 12 bytes are used, the second time 23 bytes, the third time 34, and so on.

The solution in the answer by @VE7JRO will fix that, but I prefer not to use `dtostrf()` and transmit binary data.

I see a few other problems as well:

 - Why do you want to transmit readable ASCII text? Use binary data.
   Either float numbers or integers. For example an integer in 1/100 degrees.
 - The RadioHead library uses a lot of memory. You can not use an other
   library that uses also a lot of memory.
 - The value of '5' for dtostrf is the **minimal** width,
   so you better make those arrays for example 20 bytes.
   I prefer to put those arrays temporarily on the stack.
 - The DHT11 is not accurate. If you upgrade to a better sensor with I2C,
   then you need more libraries (the Wire library and a sensor library),
   and you might run out of sram memory.
 - When using the RadioHead library in default mode, it uses three
   pins (rxPin=11, txPin=12, pttPin=10). You better add a comment
   section to your sketch to explain that you should not use those pins.
   You have already a
   conflict at pin 10 for the DHT sensor and the pttPin.

----------

The old and no longer supported VirtualWire library has some bugs, but it uses less memory than the RadioHead library. The RadioHead library is not optimized for Arduino boards like the Uno, Nano, Leonardo, and others. It even requires to `#include <SPI.h>` because that is often used with transceivers, even if the SPI bus is not used in RH_ASK mode (thanks to @VE7JRO for explaining this in the comment below).

----------

**The easiest way** to transmit more than one value is with an array.

    float myData[2];
    myData[0] = 23.456;
    myData[1] = 68.0;
    rf_driver.send((uint8_t *)myData, sizeof(myData));

The `sizeof()` is not a real function, it tells the compiler to fill in the size of that variable. Since a `float` is 4 bytes, you may also fill in the number 8 for the second parameter.

There are a number of solutions for the receiver. I like to use a pointer to the buffer, but perhaps it is easier to copy them to variables with `memcpy()`.

    float myData[2];
    if (driver.recv(buf, &buflen)) {
      if (buflen == sizeof(myData) {  // extra check
        memcpy((uint_8 *)myData, buf, sizeof(myData));
        Serial.println(myData[0]);
        Serial.println(myData[1]);
      }
    }

When the receiver is also an Arduino board, then there should be no problem. When the receiver is something else, you might have to check if the [byte-order][1] is the same. The `float` variable of a Arduino is 100% IEEE compatible, but sometimes it is easier to use only integers.

**The most common way** is to use a `struct`. A `struct` is a package that can hold all sorts of data (integers, bytes, arrays, and so on). The receiver and the sender should have exactly the same definition for the `struct` of course.

  [1]: https://en.wikipedia.org/wiki/Endianness


body:
I'm late to the party, but here goes:

`msg_out[]` is a global but it doesn't need to be. Move it's definition and initialization into loop(), the only function that uses it. Then it gets initialized at every entry to loop() rather than just once at program initialization. There's no need to clear the array; just zeroing the zero-th element of it initializes it for character-string use, and that is what your initializer now does (but only once).


message:
Stuttering motor using rf module

I am trying to control a stepper motor wirelessly with a button. I am using the 433MHZ rf module and the Virtualwire library.

the code is working, the receiver is getting the messages from the transmitter, but the problem is the messages are sent extremely slowly, so much so that the receiver circuit led is flashing on and off instead of staying in the on position when the transmitter button is being held down. consequently the stepper motor stutters instead of moving smoothly.

I have tried increasing the bits per second in the vw_setup but that just makes the led flash faster and not stay in the on position. it also makes the stepper vibrate more.

how do i make the stepper motor move smoothly wirelessly over rf?

transmitter code:

    #include <VirtualWire.h>

    int currentlocation = 0;
    const int stepPin = 3;
    const int dirPin = 4;
    int active = 0;
    const int ledPin =  13;      // the number of the LED pin
    String dataout;
    char buffer[1];
    int idx=0;

    class Button {

      public:

        int pin;
        int state;
        int location;
        int Speed;
        int Direction;
        int active;
        int prevstate;

        Button(int pin1, int state1, int location1, int active1, int previousState)
        {
          pin = pin1;
          state = state1;
          location = location1;
          active = active1;
          prevstate = previousState;
        }

        Button(int pin1, int state1, int speed1, int direction1)
        {
          pin = pin1;
          state = state1;
          Speed = speed1;
          Direction = direction1;
        }

        Show(){
          if (digitalRead(pin) == HIGH){
              digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
        }
    };

    Button button(7,0,0,0,0);
    Button button2(8,0,30,0,0);
    Button Movebutton1(5,0,500,HIGH);
    Button Movebutton2(6,0,500,LOW);
    Button buttons[2] = {button, button2};
    Button Movebuttons[2] = {Movebutton1, Movebutton2};

    void setup() {
          vw_setup(2000);
          pinMode(stepPin,OUTPUT);
          pinMode(dirPin,OUTPUT);
          pinMode(ledPin, OUTPUT);
          Serial.begin(9600);      // open the serial port at 9600 bps:
    }

    void loop() {
        for (int i = 0; i<2; i++){
          buttons[i].Show();
          if (digitalRead(buttons[i].pin) == HIGH){
          sprintf(buffer, "%d", i);
          vw_send((uint8_t *)buffer, strlen(buffer));
          vw_wait_tx();
          }
        }
        for (int i = 0; i<2; i++){
          Movebuttons[i].Show();
          if (digitalRead(Movebuttons[i].pin) == HIGH){
          sprintf(buffer, "%d", i+2);
          vw_send((uint8_t *)buffer, strlen(buffer));
          vw_wait_tx();
          }
        }
    }

Receiver code:

    #include <VirtualWire.h>

    char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
    byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
    int last_idx = 0;

    int currentlocation = 0;
    const int stepPin = 3;
    const int dirPin = 4;
    int active = 0;
    const int ledPin =  13;      // the number of the LED pin
    String str_out;

    class Button {

      public:

        int pin;
        int state;
        int location;
        int Speed;
        int Direction;
        int active;
        int prevstate;

        Button(int pin1, int state1, int location1, int active1, int previousState)
        {
          pin = pin1;
          state = state1;
          location = location1;
          active = active1;
          prevstate = previousState;
        }

        Button(int pin1, int state1, int speed1, int direction1)
        {
          pin = pin1;
          state = state1;
          Speed = speed1;
          Direction = direction1;
        }

        Relocate(){
          int shift = location - currentlocation;
          if (shift > 0){
            Direction = 0;
          }
          else{
            Direction = 1;
          }
          shift = abs(shift);
          digitalWrite(dirPin,Direction); // Enables the motor to move in a particular direction
          // Makes 200 pulses for making one full cycle rotation
          for(int x = 0; x < shift; x++) {
            digitalWrite(stepPin,HIGH);
            delayMicroseconds(500);
            digitalWrite(stepPin,LOW);
            delayMicroseconds(500);
          }
          currentlocation = location;
        }

        Move(){
          digitalWrite(dirPin,Direction); // Enables the motor to move in a particular direction
          // Makes 200 pulses for making one full cycle rotation
            digitalWrite(stepPin,HIGH);
            delayMicroseconds(Speed);
            digitalWrite(stepPin,LOW);
            delayMicroseconds(Speed);
          if (Direction == 1){
          currentlocation -= 1;
          }
          else{
          currentlocation += 1;
          }
        }

        Show(){
          if (vw_get_message(message, &messageLength)){
              digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
        }
    };

    Button button(7,0,0,0,0);
    Button button2(8,0,30,0,0);
    Button Movebutton1(5,0,500,HIGH);
    Button Movebutton2(6,0,500,LOW);
    Button buttons[2] = {button, button2};
    Button Movebuttons[2] = {Movebutton1, Movebutton2};

    void setup() {
            // Initialize the IO and ISR
          vw_setup(2000); // Bits per sec
          vw_rx_start(); // Start the receiver
          Serial.begin(9600);
          pinMode(stepPin,OUTPUT);
          pinMode(dirPin,OUTPUT);
          pinMode(ledPin, OUTPUT);
    }

    void loop() {

          // Set buffer to size of expected message
        if (vw_get_message(message, &messageLength)){
        int idx=atoi(message);
        Serial.print(message);
        for (int i = 0; i<2; i++){
          buttons[i].Show();
          if (idx == i){
          buttons[i].Relocate();
          active = i;
          //buttons[i].location = currentlocation;
          }
        }
        for (int i = 2; i<4; i++){
          Movebuttons[i-2].Show();
          if (idx == i){
          Movebuttons[i-2].Move();
          buttons[active].location = currentlocation;
          }
        }
        }
    }

body: What is the incoming message interval (1/incomingMessageFrequency)? Whenever the receiving end receives a "button-down" message, it should activate the motor for that interval + long enough to receive or not receive the next "button-down". Once the next "button-down" should have been received and has been missed, that's when you should stop the motor.


message:
Can not print an element in an specific position in an arduino list

I have been tying to print an element of a list with the same position as the number that it matches, but it does not seem to work and I can not figure out if I made some mistake, could someone please check it? Would really appreciate it

Here are the list declarations:

    int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    char *users[10] = {"Josh", "John", "Frederic", "Mikael", "Anthony", "Charles", "Tom", "Chris", "Steve", "Mike" };

And this is what I am using to print the name I need:

    if (attempt != FINGERPRINT_OK) return -1;
 Serial.println ("Belongs to: ");
 if(data.fingerID == names[n]) {
  Serial.print(users[n]);
 }

Complete Code:

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3);
    pinMode (12, OUTPUT);
    pinMode (13, OUTPUT);

    Adafruit_Fingerprint data = Adafruit_Fingerprint(&mySerial);

    int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    char *users[10] = {"Josh", "John", "Frederic", "Mikael", "Anthony",
    "Charles", "Tom", "Chris", "Steve", "Mike" };

    void setup() {
      Serial.begin(9600);
      while (!Serial);
      data.begin(57600);
      if (data.verifyPassword()) {
       Serial.println("Verified connection");
    }

      else {
     Serial.println("Unnable to verify connection, try again");
     while (1) { delay(2500); }
    }

    data.getTemplateCount();
    Serial.print("Waiting for one of the:"); Serial.print(data.templateCount);
    Serial.println("valid fingerprint");

    int getFingerprintIDez();
    uint8_t getFingerprintID();

    void loop() {
    for ( int i = 0; i <= 10; i++) {
     uint8_t attempt = data.getImage();
      switch (attempt) {
       case FINGERPRINT_OK:
       break;
     delay (2500);
    }

    attempt = data.image2Tz();
      switch (attempt) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
        break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
        return attempt;
      }

     attempt = data.fingerFastSearch();
       if (attempt == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
        digitalWrite (13, HIGH);
        delay(1250 );
        digitalWrite (13, LOW);
      }
       else if (attempt == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    digitalWrite (12, HIGH);
    delay(1250 );
    digitalWrite (12, LOW);
    return attempt;
      }
    Serial.print("Found ID #"); Serial.print(data.fingerID);
    Serial.print(" with confidence of "); Serial.println(data.confidence);
    return data.fingerID;

    uint8_t attempt2 = data.getImage();
    if (attempt2 != FINGERPRINT_OK) return -1;
  attempt2 = data.image2Tz();
    if (attempt2 != FINGERPRINT_OK) return -1;
  attempt2 = data.fingerFastSearch();
    if (attempt2 != FINGERPRINT_OK) return -1;
  Serial.println ("Presents: ");
 if(data.fingerID == names[n]) {
  Serial.print(users[n]);
 }
    }
    }

I am attempting that when a fingerprint is verified, the position that matches it out of all the stored fingerprints gets stored as n so I can later print the name asigned to that same position. Thanks

body:
How about you completely delete

    int names[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

and instead do:

    if (attempt != FINGERPRINT_OK)
        return -1;

    Serial.println ("Belongs to: ");
    Serial.print(users[data.fingerID - 1]);


message:
Trying to Pulse an LED a number of times outside of the main loop

I'm trying to call a class function that pulses an LED "x" number of times. I dont want to use a delay, which is making it tough. If I use a while loop, the LED just stays on. I attach an interrupt in the `begin()` - the location of the LED is pin `13`

I call the following in my sketch like so:

    robot.lights.pulse(0, 2000, 10000, 500); //in milliseconds

My goal is to pulse an LED "x" number of time at a rate I specify.

This is the code inside my class:

    void StatusLights::begin(int locations[]){
        for(int i=0;i<NUM_OF_LIGHTS;i++){
      this->locations[i]=locations[i];
      pinMode(locations[i], OUTPUT);
     }

        ledState = LOW;
        previousMillis = 0;
        attachInterrupt(0, pulse_ISR, RISING);

    };

    void StatusLights::pulse(int location, int interval, int count, int speed){

        int value = 0;
        previousMillis = 0;
        // while(pulsecnt<count) {
            long currentMillis = millis();

            if (currentMillis - previousMillis >= interval) {
                previousMillis = currentMillis;
                value = 128+127*cos(2*PI/interval*(speed-currentMillis));
                analogWrite(locations[location], value);
            };
        // };
        // digitalWrite(locations[location], LOW);
    };

    void pulse_ISR() {
        pulsecnt++;
    };

This is my first time using interrupts to do this - I'm really trying to avoid delays since i need other things to happen synchronously.

Thanks!

body:
You'll want a class function that decides whether 'now' is time to toggle the LED or not, and returns quickly. Call that function frequently from your loop function. Your other class functions will set or clear the whether the LED is to toggled, and when, how many times, etc.  Something like the following pseudo-code, which is not a full solution but should point out the essential details:

    void loop()
    {
       myStatusLights.updateLED();     // call this frequently
    }

    ...

    void StatusLights::updateLED(){
      if LED_active,
         if it's time to change the LED,
            toggle LED on/off;
            if LED has toggled enough times,
               set LED_active false;
            endif;
         endif;
      endif;
    }

Update:

>How would you refresh the count, track the pulses, and refresh the state of the status light without any parameters?

Some class-function must initiate the blinking, whether it knows to do it itself or it is called from your application code. That class-function will need to set those parameters. If it to be called from outside, perhaps the outside sets them - ? Only you know that. Either way, they will need to get saved in the class' private data so the .updateLED() function can have access to them. The .updateLED() function will, for instance, count down the remaining number blinks to display, keep track of whether the LED is on or off, actually turn it on or off, etc., until there is nothing left for it to do. In that case it just quickly returns without doing anything.


message:
How to publish on Pubnub with node mcu?

I have node mcu and i am trying to use the example code on github and pubnub blog to send a msg as an experiment but can't figure how to do it.

I used 2 example as the reference - https://github.com/pubnub/arduino , https://www.pubnub.com/docs/arduino/data-streams-publish-and-subscribe

Here is the code which i have. I modified it to include some libraries and my API keys. Let me know what changes i have to make:-

    #include <ESP8266WiFi.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

    #include <PubNub.h>

    String pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
    String subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";
    String pubchannel = "sec-c-NmFiYjliODYtMTc3Mi00YTMzLTg0OWMtMDgzYjE2ZGUwNzg5";

    void setup() {
        /* For debugging, set to speed of your choice */
        Serial.begin(9600);

        /* Start the Pubnub library by giving it a publish and subscribe
           keys */
        PubNub.begin(pubkey, subkey);
    }

    void loop() {
        /* Maintain DHCP lease. For other HW, you may need to do
           something else here, or maybe nothing at all. */

        /* Publish message. You could use `auto` here... */
        PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
        if (!pclient) return;
        PublishCracker cheez;
        cheez.read_and_parse(pclient);
        /** You're mostly interested in `outcome()`, and,
            if it's "failed", then `description()`.
        */
        Serial.print("Outcome: "); Serial.print(cheez.outcome());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
        Serial.print("description: "); Serial.println(cheez.description());
        Serial.print("timestamp: "); Serial.println(cheez.timestamp());
        Serial.print("state: "); Serial.print(cheez.state());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
        pclient->stop();

        /* Wait for news. */
        PubSubClient *sclient = PubNub.subscribe(subchannel);
        if (!sclient) return; // error
        String msg;
        SubscribeCracker ritz(sclient);
        while (!ritz.finished()) {
            ritz.get(msg);
            if (msg.length() > 0) {
                Serial.print("Received: "); Serial.println(msg);
            }
        }
        sclient->stop();

        delay(1000);
    }

    Error:-
    node_mcu_test_code:44:46: error: 'subchannel' was not declared in this scope

         PubSubClient *sclient = PubNub.subscribe(subchannel);

                                                  ^

    node_mcu_test_code:54:14: error: 'class PubSubClient' has no member named 'stop'

         sclient->stop();

                  ^

    exit status 1
    no matching function for call to 'PubNub::begin(String&, String&)'

body:
The pubchannel and subchannel can be defined as any values in char variable.

Here is the right code:-

    const char * pubkey = "publisher key from your account";
    const char * subkey = "subscriber key from your account";

    const char * pubchannel = "demo_keyset";
    const char * subchannel = "demo_keyset";

Then the error disappeared


message:
RFID-RC522 not working with Arduino Uno clone

I am using this library https://github.com/miguelbalboa/rfid, and using **DumpInfo.ino** from it:

    /*
     * --------------------------------------------------------------------------------------------------------------------
     * Example sketch/program showing how to read data from a PICC to serial.
     * --------------------------------------------------------------------------------------------------------------------
     * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
     *
     * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
     * Reader on the Arduino SPI interface.
     *
     * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
     * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
     * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
     * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
     * when removing the PICC from reading distance too early.
     *
     * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
     * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
     * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
     * keep the PICCs at reading distance until complete.
     *
     * @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>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         // Configurable, see typical pin layout above

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

    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
     mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

    void loop() {
     // Look for new cards
     if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
     }

     // Select one of the cards
     if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
     }

     // Dump debug info about the card; PICC_HaltA() is automatically called
     mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    }

When I connect everything correctly and upload that sketch, this shows up in my Serial Monitor: [![serial monitor not working rfid][1]][1]

I have tried this with another cheap Arduino Uno, I connected it exactly the same and scanned one card, everything works perfectly fine: [![serial monitor working rfid][2]][2]

So I guess RC522 module is working fine, and there is probably issue with that Arduino Uno board.

What I tried next without any success is:

 - Copy bootloader from working Arduino Uno to this Arduino Uno that is not working.
 - Switch ATMEGA328P from working Arduino Uno to this Arduino Uno that is not working.

I tested all pins (on board that is not working) for PWM and Digital Output functionality with [Firmata Test][3], and everything is fine in this test.

You can take a look on images of this Arduino Uno board [here][4].

**So my question is: something is wrong with the board itself or I am doing something wrong?**

Thanks!

  [1]: https://i.stack.imgur.com/SSrvT.png
  [2]: https://i.stack.imgur.com/PazAD.png
  [3]: http://firmata.org/wiki/Main_Page#Firmata_Test_Program
  [4]: https://i.stack.imgur.com/NQMDS.jpg

body:
Try using this code:

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

    #define SS_PIN 10
    #define RST_PIN 9

    #define SERVO_PIN 3
    Servo myservo;

    #define ACCESS_DELAY 2000
    #define DENIED_DELAY 1000
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    void setup()
    {
      Serial.begin(9600);   // Initiate a serial communication
      SPI.begin();          // Initiate  SPI bus
      mfrc522.PCD_Init();   // Initiate MFRC522

      myservo.attach(SERVO_PIN);
      myservo.write( 70 );
      delay(7500);
      myservo.write( 0 );
      Serial.println("Put your card to the reader...");
      Serial.println();

    }
    void loop()
    {
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content= "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++)
      {
         Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
         Serial.print(mfrc522.uid.uidByte[i], HEX);
         content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
         content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      if (content.substring(1) == "69 C8 E2 2A") //change here the UID of the card
      {
        Serial.println("Authorized access");
        Serial.println();
       myservo.write( 70 );
     delay(7500);
      myservo.write( 0 );

      }

     else   {
        Serial.println(" Access denied");

        delay(DENIED_DELAY);

      }
    }


message:
Can you save data to heap section in Arduino memory?

On normal computers, heap will be cleaned as you close the program, but can I save data to Arduino's heap with `malloc` function. And will it be cleaned after I power off the Arduino?

body:
Yes, you can use `malloc()` on the Arduino - however it is not something I would recommend you use since memory is at a premium and excessive use of `malloc()` and `free()` causes heap fragmentation which can eat your memory up and cause random crashes (`String` is the biggest culprit of this).

I am not sure what you mean by "clean" the memory.  When power is removed the content of the memory is lost. The whole of the SRAM forgets its contents if there is no power to maintain that state.  A bit like when you unplug your computer it "forgets" that Windows is loaded.

If you want to retain information with the power removed you need to use the [EEPROM](https://www.arduino.cc/en/Reference/EEPROM).


message:
Using Arduino as ISP and SoftwareSerial at the same time

I'm trying to use my Arduino Uno as an ISP to program an ATTiny85 and at the same time check my board by using the SoftwareSerial library to output the values I'm getting from my sensor.

Is this actually possible? Or does it require 2 different setups? Because I found a lot of tutorials and threads about one or the other, but never both. Which I find odd because once you send your program to the chip you might want to test it as well (or debug it).

Many thanks for your help and input! :)

body: I'm not really sure, but in the Arduino ISP example there is an if that looks if the ISP is in program-mode. You could try adding in the else statement of that if the Software Serial part.


message:
Arduino Nano, Uno and Mega - XBee connection difference

I have a simple sketch working on arduino Uno and Nano sending data using an XBee.
However, if I run the project on an Arduino Mega it does not work.

What differences between Uno/Nano and the Mega could be causing issues?

Connection:  I just connect 3.3V->3.3V, Gnd->Gnd, and have tried various ports for DIN and DOUT (normally pins 2/4, but have tried A0/A1, 22/23 etc..).

Sketch: [pastebin][1]

Have brought a second Mega in case of hardware faults, but the problem persists.  Have stripped anything which might be tying up a timer.  Am choosing the right board type in the arduino IDE.

  [1]: https://pastebin.com/fKdK1r76

body:
Not all arduino Mega pins support 'change interrupts', which is needed for Software Serial.  Only the following can be used for RX:

10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).


message:
ESP8266 TCP/IP communication

So I'm looking into having a TCP communication between 1 ESP8266 Chip (Station) and 2 ESP8266 (Clients) connected to that station. Every time I find a code including the TCP, they only include things like client.print(). But how can I write a message to a certain IP address in that network.

When I do client.print() it sends the message to ALL the clients. But I want to be able to do something like client1.print() and client2.print()

body:
WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

    if (client.connect(serverIP, PORT)) {
      client.print("request\n");
      String response = client.readStringUntil('\n');
      Serial.println(response);
      client.stop();
    }

server side

    WiFiClient client = server.available();
    if (client && client.connected()) {
      String request = client.readStringUntil('\n');
      Serial.println(request);
      client.print("response\n");
      client.stop();
    }


message:
How to program an Arduino pro mini using native serial port (on my mainboard)

How can I program my Pro Mini using the native RS232 Serial port on my Mainboard (aka com1).

Google-ing did not really help and a quick search here for "pro mini programming com1" did not deliver _any_ results.

I already have a MAX232 module connected between the Pro Mini and the PC.

I have already tested the com1 port for function by sending stuff to an Arduino mega via its usb-to-serial port and echo-ing that to com1.

Which succeeded (at least sort-of [receiving some random clutter in between characters or missing some characters at all])

I did try the obvious (i.e. selecting pro mini from the board menu and then selecting the com1 port and hit upload).

But that did just produce a timeout-error…

An Option to set the programmer to simple Serial Connection or something similar does not exist to my knowledge (well it does but only if we're talking about STM32 based boards like the blue pill).

body:
To upload a hex file to Arduino over Serial interface, the bootloader must be active. The bootloader is active after reset. It waits a short time if a new application is uploaded. If not, it jumps to existing application.

To reset the MCU on Arduino boards with independent USB chip a circuit connected to DTR line of serial is used.

On a board like the Pro Mini there is no chip for USB neither an auto reset circuit. You must reset the board with the reset button right before avrdude sends the hex file. avrdude tries ten times, so you have 10 chances to time it right after you hit the Upload button.

Some USB-to-TTL-Serial adapters (or RS232 adapters) have the DTR line and it can be used to reset the board.

Or use ISP flashing over the ICSP header with a programmer or other board as programmer.


body:
Open the IDE, select File:Preferences and turn on Verbose Outputs.
Press & Hold Reset on the Promini.
Start the download. At the end of compilation you will see something like

>Sketch uses 960 bytes (2%) of program storage space. Maximum is 32256 bytes.

Then the IDE will try and download 3 times.

Release Reset when you see the line above - it may take a few tries to get the release timing correct.


message:
Can you current-limit Arduino 101 GPIO pins?

A number of questions ask about max possible in/out current on a GPIO pin, that's not my question here. I'm asking if it's possible to set a maximum current limit on a GPIO pin, such that any attempts to draw more than that current would result in the Arduino entering a constant current mode e.g. reducing the pin voltage?

I've read [this][1], [this][2], [this][3], and skimmed the [Curie datasheet][4], but I don't see a feature like this mentioned anywhere.

The only half-answer I have seen is on the [Ruggeduino website][5], which explains that they have added a fuse to each GPIO pin to avoid overcurrent draws due to short circuits.

For context - I have an external sensor that claims to be more reliable with a small amount of constant current. I didn't know if I could easily add that limitation (e.g. max 15mA at 3.3V) into the GPIO pin as a safety measure, so I went on a search to find out which has eventually led me here

  [1]: https://arduino.stackexchange.com/questions/38939/arduino-101-i-o-voltage-levels
  [2]: http://syncchannel.blogspot.com/2016/01/exploring-io-performance-of-arduino-101.html
  [3]: https://arduino.stackexchange.com/questions/21939/the-importance-of-i-o-pin-dc-current
  [4]: https://www.intel.com/content/dam/support/us/en/documents/boardsandkits/curie/intel-curie-module-datasheet.pdf
  [5]: https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/

body:
No. I have never heard of a microcontroller with constant current or current limiting on the GPIO pins.

You may get a *drive strength* on the pins of an FPGA, but I have never seen such a thing on a microcontroller.

In general, if you have a need to reduce the voltage as the current increases you would just slip a resistor in the circuit. Or for more precise control using the GPIO pin to control a *constant current source* or *constant current sink* is the normal way of doing it.

GPIO pins are generally designed for communicating with other logic level devices. They require minimal current. Some microcontrollers provide a higher drive strength to work with larger *fanouts* (lots of devices connected to one pin, such as in SPI buses), but they are not intended for providing power to a device or giving control over their current.


body:
Typically port pins do have some current limiting inherent in the design of the chip. But it isn't something that should be used as protection. More line a fact that should be taken into account when implementing a design.

Say a 3.3 volt processor has a maximum rating of 12mA. With a 5 mA draw from the pin the high output voltage might be 3.0 volts. When 12mA is drawn from the chip the output voltage might only be 2.5 volts. It is important to check the data sheet to determine what you will get under the expected conditions.

A port with an internal pull up option may be considered more like (but not like) a constant current source. But that's stretching things a bit.


message:
Is my board broken by soldering?

I've soldered a featherwing on my feather, then unsoldered it because it had stopped working: after the soldering of the featherwing, I was unable to upload new software to the board.

But now that the featherwing was removed, I still can't upload a software onto the board.

Here's the complete log I get:

    $ ~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/arduino_build_190205/Blink.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
             User configuration file is "~/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

    avrdude done.  Thank you.

I used to have this error from time to time before, but I always was able to make it work, either by using another USB port, choosing the right port for the arduino or rebooting Linux, but now nothing I do works.

So, I think I might have broken the board because of the soldering/unsoldering.

I attached the pictures of both sides of the board.

[![board top][1]][1]
[![board bottom][2]][2]

Three LEDs continue to blink: the red one when I connect the board to the USB, the battery one and the RX one when there is an attempt at transmission.

Can you tell me whether the board looks damage?

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

body:
It looks like you have soldering paste all over the circuit board. If enough paste bridges a gap between the ceramic resonator and the IC, it can attenuate the oscillator signal to the point where the board won't work.

I use an old tooth brush and Isopropyl alcohol to clean excess soldering paste. As the alcohol evaporates, a lot of moisture forms on the circuit board, so it's important to ensure it's completely dry before you power it up.

Try cleaning the circuit board and see if that fixes the problem.

**EDIT:**

I would like to show you how much soldering paste it takes to stop a 328P from working. The following image shows the bottom of a perfboard with 0.1" hole spacing. You can see the soldering paste bridging the gap between pins 8, 9, and 10 of a Atmega328P DIP IC. Pin 8 is ground, and pins 9 and 10 are connected to the crystal / capacitors. All three pins are connected together via the paste, and since I forgot to clean the board before "final assembly", it's possible other pins are connected together via the paste.

[![Excess soldering paste][1]][1]

The circuit board is from a "kitchen clock project", and was taken the day it stopped working. There are no mechanical connections to this circuit board except for the 328P's IC socket. This clock worked for 3 months, then it quit suddenly. I re-booted it once, it worked for an hour, then it quit again. The only factor that changed after the first three months was a change of seasons (the ambient temperature in the kitchen was reaching 90+ degrees F during the day). I don't know if the "blobs" of paste were touching each other when I assembled it, but they were when it failed. How does thick soldering paste start moving around on it's own? With some heat and [Capillary action][2] of course :)

Cleaning the board with Isopropyl alcohol fixed the problem, and the clock has been running for the past 6 months without issue.

**EDIT 2**

When I monitor pin 9 of a 328P on a 5V Arduino Uno, this is the waveform I see.

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

You can see the small amount of voltage change the oscillator has to make for the 328P to sense it, and function correctly (800mV peak to peak). If the soldering paste is conductive, capacitive or perhaps both, connecting this signal through the paste to ground, power or several other pins can disrupt the signal to the point where the IC fails to operate.

  [1]: https://i.stack.imgur.com/MjEUj.png
  [2]: https://en.wikipedia.org/wiki/Capillary_action
  [3]: https://i.stack.imgur.com/QwG7d.png


body:
There is flux on the board and that is **not** going to cause the problems you are seeing. At worst the flux may have an affect on the ability to get a proper lock at 2.5GHz, and that is unlikely.

Clean the board and use magnification to look for damage to the copper foil on the board and inside the plated holes. That will most likely be the problem.

This was from a question regarding no-clean fluxes but the information also applies to the use of regular flux as well.

> Today, one of the most common reasons to remove no-clean fluxes is to
> prevent malfunctions in circuits with clock speeds over 1 gigahertz.
> "When you get above 1 gigahertz, the electronscan conducted on the
> outer surface of the conductor. If you have flux on those conductors
> that have those high clock speeds, it can interfere with these fast
> signals."
http://www.circuitnet.com/experts/73284.html

Most electronics are not cleaned after soldering. The company I work for went to a no clean process 20 years ago.


message:
Esp8266-01 AT Commands returns partially

Im trying to get html response from server via esp01 module

when using the serial monitor in arduino studio everything works fine

here is the serial monitor output

    AT+CIPSTART="TCP","aaaa.aaaa",80

    CONNECT

    OK
    AT+CIPSEND=43

    OK
    >
    Recv 43 bytes

    SEND OK

    +IPD,227:HTTP/1.1 200 OK
    Date: Sat, 19 Jan 2019 18:42:58 GMT
    Server: Apache
    X-Powered-By: PHP/7.2.11
    Vary: Accept-Encoding,User-Agent
    Transfer-Encoding: chunked
    Content-Type: text/html; charset=UTF-8

    10
    Hello from server

    0

    CLOSED

but when im trying to do the same from the sketch my response is returned partially

    AT+CIPSTART="TCP","aaaa.aaaa",80

    CONNECT

    OK
    AT+CIPSEND=43

    OK
    >
    Recv 43 bytes

    SEND OK

    +IPD,227:HTTP/1.1 200 OK
    Date: S

it ends on the first letter of date for some reason

here is my sketch

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX //serial for comunication with esp
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.setTimeout(5000);//dont know if i need this

      delay(10000);

      //check wifi module
      mySerial.println("AT");
      delay(1000);
      if(mySerial.find("OK"))
      {
        Serial.println("Initializing");
      }else{
        Serial.println("Error initializing");
      }
    }

    void loop() { // run over and over

      Serial.println("go");
    mySerial.println("AT+CIPSTART=\"TCP\",\"aaaa.aaaa\",80");
    delay(1000);
        while(mySerial.available()){
        Serial.write(mySerial.read());
         delay(1);
      }
    mySerial.println("AT+CIPSEND=43");
    delay(1000);
        while(mySerial.available()){
        Serial.write(mySerial.read());
         delay(1);
      }
    mySerial.println("GET /load.php HTTP/1.1");
    delay(100);
        while(mySerial.available()){
        Serial.write(mySerial.read());
         delay(1);
      }
    mySerial.println("Host: aaaa.aaaa");
    delay(100);
        while(mySerial.available()){
        Serial.write(mySerial.read());
         delay(1);
      }
    mySerial.println("");
    delay(2000);

        while(mySerial.available()){
        Serial.write(mySerial.read());
         //delay(100);
      }

    delay(5000);

    }

what is the reason for this behavior?
how can i fix this?

body:
found the solution
i had t wait for serial input without delay function

    String sendCommand(String command, const int timeout)
    {
      String res = "";
      mySerial.println(command); // send the read character to the wifi
      long int time = millis();
      while( (time+timeout) > millis())
      {
        while(mySerial.available())
        {
          // The esp has data so display its output to the serial window
          char c = mySerial.read(); // read the next character.
          res+=c;
        }
      }
      //Serial.print(response);
      return res;
    }


message:
Strange values on Serial Monitor even with matched baud rate

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

I am using the Adafruit Flora, connected with a Max 4466 microphone sensor. When I read values from the pin numbered 12 (which is marked as a11 for analog input on the schematic of the flora) I get random characters in the serial monitor as shown in the attached image, with my code. Trying to read other pins that are connected to nothing doesn't read any information. My baud rate in the serial monitor and the code are the same as you can see in the image.

Looking at the max 4466 explanation on the Adafruit website it says you don't need a capacitor or anything and can just directly plug the out pin on the MAX 4466 to the analog pin on an Arduino. I'm not sure if a different protocol has to be followed for a Flora instead of an Arduino. It also says to convert the information to an actual signal I need to use the FFT libraries, but I don't think this input being read is even correct.

If the FFT library is the problem here, I would need help on how to use it because there is no clear value being read in the example code. I had to set up a delay in the code otherwise the IDE would crash from all the info.Additionally, the VCC on the max is connected to 3.3V, the GND to GND, and the OUT to the #12 pin on the Flora.

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

body:
You can't concatenate string and value inside `Serial.println()`.

Print them using two different `Serial.println()`.

    int pin12;
    int A12 = A12;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pin12 = analogRead(A11);

      Serial.print("pin 12 is ");
      Serial.println(pin12);

      delay(5000);
    }


message:
Problem “Didn't find PN53x board” Arduino NFC Card Reader

i am using the elechouse PN532 RFID Module with an Wemos D1 mini in the Arduino IDE.
I use the ISO1443a_uid example from the elechouse library. All works fine if i plug the USB Cable into the wemos and the demo runs. But if i press the reset button on the Wemos D1 mini then the Serial brings this output:

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v0fd86a07
    ~ld
    Hello!
    Didn't find PN53x board

Sometimes it works fine but mostly comes this error.

Here is the sample code (i am using the I2C Mode):

    * When the number after #if set as 1, it will be switch to SPI Mode*/
    if 0
     #include <SPI.h>
     #include <PN532_SPI.h>
     #include "PN532.h"

     PN532_SPI pn532spi(SPI, 10);
     PN532 nfc(pn532spi);

    * When the number after #elif set as 1, it will be switch to HSU Mode*/
    elif 0
     #include <PN532_HSU.h>
     #include <PN532.h>

     PN532_HSU pn532hsu(Serial1);
     PN532 nfc(pn532hsu);

    * When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
    else
     #include <Wire.h>
     #include <PN532_I2C.h>
     #include <PN532.h>
     #include <NfcAdapter.h>

     PN532_I2C pn532i2c(Wire);
     PN532 nfc(pn532i2c);
    endif

    oid setup(void) {
     Serial.begin(115200);
     Serial.println("Hello!");
     pinMode(D2,INPUT_PULLUP);
     pinMode(D1,INPUT_PULLUP);
     nfc.begin();

     uint32_t versiondata = nfc.getFirmwareVersion();
     if (! versiondata) {
       Serial.print("Didn't find PN53x board");
       while (1); // halt
     }

     // Got ok data, print it out!
     Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
     Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
     Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

     // Set the max number of retry attempts to read from a card
     // This prevents us from waiting forever for a card, which is
     // the default behaviour of the PN532.
     nfc.setPassiveActivationRetries(0xFF);

     // configure board to read RFID tags
     nfc.SAMConfig();

     Serial.println("Waiting for an ISO14443A card");

    oid loop(void) {
     boolean success;
     uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
     uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

     // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
     // 'uid' will be populated with the UID, and uidLength will indicate
     // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
     success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

     if (success) {
       Serial.println("Found a card!");
       Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
       Serial.print("UID Value: ");
       for (uint8_t i=0; i < uidLength; i++)
       {
         Serial.print(" 0x");Serial.print(uid[i], HEX);
       }
       Serial.println("");
       // Wait 1 second before continuing
       delay(1000);
     }
     else
     {
       // PN532 probably timed out waiting for a card
       Serial.println("Timed out waiting for a card");
     }

What is wrong? why is it not alltimes working after a reset?

body:
EDIT:
Try using [Elechouse library][1], it worked better for me.

---

This might be irrelevant, but I wanted to share.

I had a similar issue, not related to the sketch code.

So make sure:

1. Connect wires to the NFC module at **90 degrees** - there should be angular headers included. Also the wires should be **above the antenna** - the white strip.

2. There shouldn't be any wires underneath the NFC module or they should on significant distance.

3. Soldered wires work better on the NFC module.

[![Stable working condition][2]][2]

  [1]: https://github.com/elechouse/PN532
  [2]: https://i.stack.imgur.com/YUf8q.jpg


message:
Badly formatted characters using JDY-30 bluetooth module

I have a JDY-30 bluetooth module and have it wired like this (except using an Arduino Uno): [![enter image description here][1]][1]

It is working, but I need to use it with a 115200 baud rate instead of the default one of 9600.
I also got that working.
Here is the code:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial (2, 3); // RX, TX

    // state | RXD | TXD | GND | VCC | EN

    void setup () {
      mySerial.begin(115200);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
    }

    void loop() {

      while (mySerial.available()) {
        delay(10);
        Serial.write(mySerial.read());
        delay(10);
      }

      while (Serial.available()) {
        mySerial.write(Serial.read());
      }

    }

But when I type things I often get badly formatted characters.

Some examples:

> 16:32:33.212 -> +VERSION=Firmware V3.0.6,Bluetooth V4.0 L⸮
>
> 16:32:38.990 -> +VERSION=Firmware V3.0.6,Bluetooth V4.0 LE

more:

> 16:33:27.144 -> +NAME=CC61-A
>
> 16:33:30.054 -> +NAME=CC41-A

If I also use 115200 baud rate for the Arduino, then it gets really worse.

Is there a solution for this?

See more about the JDY-30 here:
http://myosuploads3.banggood.com/products/20181203/20181203214419JDY-30-SPP-Bluetooth-Module.pdf

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

body:
As @Majenko pointed out:

> It is impossible to reliably receive using SoftwareSerial at 115200
> baud. The UNO is just too slow for that.

I got results that where a lot better by first making a string when reading and then once we have a string send that. Instead of sending what we read all the time.
For example, when I tried `AT+VERSION` now it took me 16 attempts to get a wrong one, and only one character out of 42 was wrong that time.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial (2, 3); // RX, TX

    // state | RXD | TXD | GND | VCC | EN

    void setup () {
      mySerial.begin(115200);
      Serial.begin(115200);
      Serial.println("Enter AT commands:");
    }

    void loop() {

      String input_string = "";

      while (mySerial.available()) {
        input_string += (char)mySerial.read();
      }

      if (input_string != "") {
        Serial.write(input_string.c_str());
      }

      while (Serial.available()) {
        mySerial.write(Serial.read());
      }

    }


message:
What am I missing? Send data from Matlab to Arduino to Micro SD

First off. This is not in any way a class assignment. This is my own personal work and research. I just want to get that out of the way.

I am learning how to use Matlab with various Arduino projects. I am a seasoned Matlab user but I am fairly new to the entire Arduino space.

I am trying to send some numerical data from Matlab (via a GUI) to my Arduino Uno and have the Arduino write it to my micro SC card. This is a temporary step to my larger project. However, there is no need to go into those specifics as they are outside of the scope of my issues.

I am fairly confident that the Matlab code works and the Arduino code is slightly modified from another project I did where I wrote and read random numbers from my micro SD card.

However, as I run the Matlab code, the Arduino blinks as if it is receiving the data but after I check the micro SD card it remains blank.

I am confident that my Arduino is wired correctly to my micro SD card adapter since this remains the same from my prior project.

Therefore, I am sure I am missing something trivial to get it to work.

I have researched several websites on the subject and their method and mine seem to align very well.

I am fairly certain the problem is in the conditional statement:

    if (Serial.available() > 0) {

As you will see.

The Matlab code is below:

    arduinoCom = serial('COM3', 'BaudRate', 115200);
    sendData = 5;
    fopen(arduinoCom);
    fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino
    fclose(arduinoCom);
    delete(arduinoCom);

The Arduino code is as follows:

    #include <SD.h> // load SD library

    int chipSelect = 4;  // Chip select pin for the MicroSD Card Adapter
    int incomingByte = 0; // for incoming serial data.
    File SDF; // Serial data received is saved here.

    void setup() {
         Serial.begin(115200); // start serial connection to print out debug messages and data
         pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
         if (!SD.begin(chipSelect)) { // Initialize SD card
            Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
         }
         while (!Serial) {
         }
    }

    void loop() {
            // Open file, Write data, Close file only when you receive data
            if (Serial.available() > 0) {
               incomingByte = Serial.read();
               SDF = SD.open("SerialDataFile.txt", FILE_WRITE); // open "SerialDataFile.txt" to write data
               SDF.println(incomingByte, DEC); // write ASCII-encoded decimal number to file
               SDF.close(); // close file
               }
    }

The expected result would be a file "SerialDataFile.txt" stored on my micro SD card with the value 5.

Thank you for your help!

body: The board resets on new USB connection with fopen. Wait 2 secs between fopen and fprintf in Mathlab code.


message:
Arduino Driving Pump via MOSFET

I want to turn on a pump that is running 12V and draws a current of max 1.7A with my Arduino Uno.

To do this, I bought the RFP30N06LE MOSFET and followed [these] instructions to wire it all up.

I connected the red wire from the pump to VIN of the Arduino and plugged a 12V 2A power brick into the Arduino. However, when I put the output pin to HIGH, the pump only pumps weakly and the MOSFET gets very hot.

When I connect the pump straight to VIN and GND, it works as expected, so the Arduino is able to provide the required current. I'm thinking that there is something to the MOSFET that I am not understanding correctly. I measured VGS at 4.5V, so the MOSFET should be able to handle the current. Is there anything I am missing?

  [these]: http://bildr.org/2012/03/rfp30n06le-arduino/

This is the wiring:
[![enter image description here][1]][1]

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

This is the (very simple) sketch I'm using to test it all:

    #define PIN_PUMP_ON 7

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

    void loop() {
      digitalWrite(PIN_PUMP_ON, HIGH);
      delay(1000);
    }

body:
Rewire the motor power so that it is not using any Arduino Power or GND pins.  Only connect the MOSFET gate to an Arduino pin using a suitable resistor.  The MOSFET drain needs to go directly to your power supply ground.  This way you're not cooking your Arduino.  A relay instead of the MOSFET would prevent the MOSFET resistance from reducing the power of your motor.

The 3 big pins under the Arduino's power connector (2 GND and 1 +V) can be used to power your motor, just solder directly to them for Motor +V and GND for MOSFET drain.  This bypasses the Arduino's diode.


body:
Vin is only rated to supply at most 1A due to the reverse polarity protection diode in series from the barrel jack to the Vin pin.  You try and draw 1.7A thru that and you may smoke it.
The Vin header is also only rated for 1A.

Connect the motor to the supply directly. The Arduino Gnd must also connect to the supply.
R2 limits Arduino IO pin current to a safe level. R1 keeps the MOSFET off while the Arduino boots up. Diode dissipates motor generated current when the MOSFET goes from On to Off. The RFP30N06LE looks to be rated for full turn on with Vgs of 5V, and Rds of 47milliohm, that part should be ok to use.

Powering the Arduino from the same source as the motor may cause issues. If you can power the Arduino from USB or a seperate battery pack and not the same 12V that powers the motor, that will probably yield better results, especially if the 12V droops at all under heavy loads from the motor. That could cause Arduino resets.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/tM1Vh.png)

<!-- End schematic -->


body:
Under no circumstances should you connect the motor to VIN on the Arduino. A motor draws far too much current.

You want to have the ground on the arduino connected to the ground for the motor, but you want different positive supplies for the 2 different devices. You also need to make sure you have a properly sized protection diode wired in parallel with the motor, but pointing against the flow of current.


message:
Print Byte Array in Serial monitor screen of Arduino IDE

I need to print mentioned below byte array on the serial monitor screen of Arduino IDE

    char b[]= {'0x7E', '0x00', '0x1C','0x90', '0x00', '0x13', '0XA2', '0x00', '0x41', '0x58', '0x1C', '0xCB', '0xFF', '0xFE', '0xC1', '0x7C', '0x00','0x0F', '0x00', '0x01', '0x00', '0x00', '0x37', '0x46', '0x46', '0x46', '0x00', '0x00', '0x00', '0xE7' };
    void setup() {
    Serial.begin(9600);
    }

    void loop() {
    Serial.println(b[]);
    delay(500);
    }

But whenever I am trying a print, the error problem was there which was not resolved which is

    C:\Users\Misha\Desktop\test\Test_2\Test_2.ino: In function 'void loop()':

    Test_2:8:18: error: expected primary-expression before ']' token

     Serial.println(b[]);

                      ^

    exit status 1
    expected primary-expression before ']' token

Any suggestions on this will be great help.

body:
You can’t print an array in that way.

If you want to print an array of hexadecimal value (with two digits), you have to use `sprintf` function and change declaration of `b` array.

    uint8_t b[]= {0x7E, 0x00, 0x1C, 0x90, 0x00, 0x13, 0XA2, 0x00,
                  0x41, 0x58, 0x1C, 0xCB, 0xFF, 0xFE, 0xC1, 0x7C,
                  0x00, 0x0F, 0x00, 0x01, 0x00, 0x00, 0x37, 0x46,
                  0x46, 0x46, 0x00, 0x00, 0x00, 0xE7};
    int i;

    void printHex(uint8_t num) {
      char hexCar[2];

      sprintf(hexCar, "X", num);
      Serial.print(hexCar);
    }

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

    void loop() {
      for(i=0; i<sizeof(b); i++){
        printHex(b[i]);
     }

     Serial.println();
     delay(500);
    }

The output produced is:

> 7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
> 7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
> 7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7


message:
ESP8266 EEPROM seems not working, saved data are different when I try to read them

I'm working on project which require to save some data into the EEPROM.
As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call `EEPROM.commit()`. You also have to call `EEPROM.begin(size)` (I used size = 512) before start to use it.

I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with

    EEPROM.write(..)
    ...
    EEPROM.read(..)

and with

    EEPROM.put(..)
    ...
    EEPROM.get(..)

but nothing change.

Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?

EDIT: here's the code

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

     EEPROM.begin(512);
     EEPROM.write(0, 62);
     EEPROM.write(10, 103);
     //EEPROM.commit();
     EEPROM.end();
     Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
     Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
    }
I always read 0 in the output.

body:
You can read the emulated EEPROM only between `begin` and `end`. It works with memory image.

 - `begin` allocates the in-memory image.
 - `commit` writes it to flash.
 - `end` commits and deletes the memory image.