text:
Garage Door Opener RFID failing after a period
I've been building an add on to my garage door opener that will allow it to be opened from the outside with a valid RFID token or from inside using push buttons.
This works as expected when first plugged in, but then after a few hours, the RFID component stops responding to swipes. The push buttons continue to allow the door to be opened, closed or halted during an action.
I'm not sure if this is  an electrical hardware issue or a code based bug, but any help is appreciated.

#include <AddicoreRFID.h>
#include <SPI.h>

#define  uchar unsigned char
#define uint  unsigned int

uchar fifobytes;
uchar fifoValue;

AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module

// ------------
// Open / Close Garage Door
// ------------

/*-------------

Every program based on Wiring (programming language used by Arduino, and Particle devices) has two essential parts:
setup - runs once at the beginning of your program
loop - runs continuously over and over

-------------*/

// First, we're going to make some variables.
// This is our "shorthand" that we'll use throughout the program:

int re1 = 8                                                                                ; // Relay IN1 Blue
int re2 = 7; // Relay IN2 Purple
int re3 = 6; // Relay IN3 Orange
int re4 = 5; // Relay IN4 Yellow
int btn1 = 3;
int btn2 = 4;
int btn3 = 2;

int OpenButtonState = 0;
int CloseButtonState = 0;
int StopButtonState = 0;

int doorstate = 0; // 0 = "Closed", 1 = "Open"

//--Pins for RFID

const int chipSelectPin = 10;
const int NRSTPD = 9;

//Maximum length of the array
#define MAX_LEN 16

//End of RFID Pin Config

void setup() {

  Serial.begin(9600);      // open the serial port at 9600 bps:
//setup the pins to output voltage
  pinMode(re1, OUTPUT);
  pinMode(re2, OUTPUT);
  pinMode(re3, OUTPUT);
  pinMode(re4, OUTPUT);
  pinMode(btn1, INPUT);
  pinMode(btn2, INPUT);
  pinMode(btn3, INPUT);

   // start the SPI library:
  SPI.begin();

  pinMode(chipSelectPin,OUTPUT);              // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
    digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
  pinMode(NRSTPD,OUTPUT);                     // Set digital pin 9 , Not Reset and Power-down
    digitalWrite(NRSTPD, HIGH);

  myRFID.AddicoreRFID_Init();

//setup web call functions

//Particle.function("netopen", R1ON);
//Particle.function("netclose", R2ON);
//Particle.function("netstop", R3ON);

  digitalWrite(re1, HIGH); //turn off relay
  digitalWrite(re2, HIGH); //turn off relay
  digitalWrite(re3, HIGH); //turn off relay
  digitalWrite(re4, HIGH); //turn off relay

}

// This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called.
// Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection).  The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them.

void loop() {

//Loop for RFID ----------------------------------------------------------------------

uchar i, tmp, checksum1;
  uchar status;
        uchar str[MAX_LEN];
        uchar RC_size;
        uchar blockAddr;  //Selection operation block address 0 to 63
        String mynum = "";

        str[1] = 0x4400;
  //Find tags, return tag type
  status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
  if (status == MI_OK)
  {
          Serial.println("RFID tag detected");
                 }

  //Anti-collision, return tag serial number 4 bytes
  status = myRFID.AddicoreRFID_Anticoll(str);
  if (status == MI_OK)
  {
          checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
          Serial.print("The tag's number is:\t");
          Serial.print(str[0]);
            Serial.print(" , ");
          Serial.print(str[1]);
            Serial.print(" , ");
          Serial.print(str[2]);
            Serial.print(" , ");
          Serial.println(str[3]);

//check if valid card combination
            if((str[0] == 333) && (str[1] == 444) && (str[2] == 555) && (str[3] == 666) )                   //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
            {
                Serial.println("\nKey fob identifed - Josh\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(""); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(""); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }

            } else if((str[0] == 111) && (str[1] == 2222) && (str[2] == 333) && (str[3] == 444) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                Serial.println("\nCar Charge Card Identified - Josh\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(""); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(""); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }
            } else if((str[0] == 000) && (str[1] == 11) && (str[2] == 22) && (str[3] == 333) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                Serial.println("\nCar Garage Card Identified - Charlotte\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(""); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(""); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }
            }
            Serial.println();
            delay(1000);
  }

        myRFID.AddicoreRFID_Halt();      //Command tag into hibernation

   //End Loop For RFID  ----------------------------------------------------------------------

OpenButtonState = digitalRead(btn1);
CloseButtonState = digitalRead(btn2);
StopButtonState = digitalRead(btn3);

if (OpenButtonState == HIGH) {

  Serial.print("Open State Button HIGH - Opening Garage Door")  ;
  Serial.println("");
    //Open Garage Door
  R1ON(""); //turn on relay
  doorstate = 1;
  Serial.print("Relay 1 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R1OFF(); //turn off relay
  Serial.print("Relay 1 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
  Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
  Serial.println("");
  }

if (CloseButtonState == HIGH) {

  Serial.print("Close State Button HIGH - Closing Garage Door") ;
  Serial.println("");
    // Close Garage Door
  R2ON(""); //turn on relay
  doorstate = 0;
  Serial.print("Relay 2 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R2OFF(); //turn off relay
  Serial.print("Relay 2 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
    Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
  Serial.println("");

  }

if (StopButtonState == HIGH) {

 Serial.print("Stop State Button HIGH - Stopping Garage Door")  ;
 Serial.println("");
 // Stop
  R3ON(""); //turn on relay
  doorstate = 1;
  Serial.print("Relay 3 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R3OFF(); //turn off relay
  Serial.print("Relay 3 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
      Serial.print("Stop State Button HIGH - Finished Stopping Garage Door")    ;
  Serial.println("");

  }

  // And repeat!
}

int R1ON(String command) {

    digitalWrite(re1, LOW); //turn on relay
    //Particle.publish("Relay 1 on - Door Open");
    delay(1000); // wait 1 second
    digitalWrite(re1, HIGH); //turn off relay
    //Particle.publish("Relay 1 off");
}

void R1OFF() {
  digitalWrite(re1, HIGH); //turn off relay
    //delay(1000); // wait 1 second
}

int R2ON(String command) {

    digitalWrite(re2, LOW); //turn on relay
    //Particle.publish("Relay 2 on - Door Closing");
    delay(1000); // wait 1 second
    digitalWrite(re2, HIGH); //turn off relay
    //Particle.publish("Relay 2 off");
}

void R2OFF() {

    digitalWrite(re2, HIGH); //turn on relay
    //delay(1000); // wait 1 second
}

int R3ON(String command) {

    digitalWrite(re3, LOW); //turn on relay
    //Particle.publish("Relay 3 on - Door Stopped");
    delay(1000); // wait 1 second
    digitalWrite(re3, HIGH); //turn off relay
    //Particle.publish("Relay 3 off");
}

void R3OFF() {

    digitalWrite(re3, HIGH); //turn on relay
    //delay(1000); // wait 1 second
}

void R4ON() {

    digitalWrite(re4, LOW); //turn on relay
    //delay(1000); // wait 1 second
}

void R4OFF() {

    digitalWrite(re4, HIGH); //turn on relay
    //delay(1000); // wait 1 second
}

Updated Code 7/7/19 @20:53
#include <AddicoreRFID.h>
#include <SPI.h>

//#define  unsigned char unsigned char
#define uint  unsigned int

unsigned char fifobytes;
unsigned char fifoValue;

AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module

// ------------
// Open / Close Garage Door
// ------------

/*-------------

Every program based on Wiring (programming language used by Arduino, and Particle devices) has two essential parts:
setup - runs once at the beginning of your program
loop - runs continuously over and over

-------------*/

// First, we're going to make some variables.
// This is our "shorthand" that we'll use throughout the program:

int re1 = 8                                                                                ; // Relay IN1 Blue
int re2 = 7; // Relay IN2 Purple
int re3 = 6; // Relay IN3 Orange
int re4 = 5; // Relay IN4 Yellow
int btn1 = 3;
int btn2 = 4;
int btn3 = 2;

int OpenButtonState = 0;
int CloseButtonState = 0;
int StopButtonState = 0;

int doorstate = 0; // 0 = "Closed", 1 = "Open"

//--Pins for RFID

const int chipSelectPin = 10;
const int NRSTPD = 9;

//Maximum length of the array
#define MAX_LEN 16

//End of RFID Pin Config

void setup() {

  Serial.begin(9600);      // open the serial port at 9600 bps:
//setup the pins to output voltage
  pinMode(re1, OUTPUT);
  pinMode(re2, OUTPUT);
  pinMode(re3, OUTPUT);
  pinMode(re4, OUTPUT);
  pinMode(btn1, INPUT);
  pinMode(btn2, INPUT);
  pinMode(btn3, INPUT);

   // start the SPI library:
  SPI.begin();

  pinMode(chipSelectPin,OUTPUT);              // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
    digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
  pinMode(NRSTPD,OUTPUT);                     // Set digital pin 9 , Not Reset and Power-down
    digitalWrite(NRSTPD, HIGH);

  myRFID.AddicoreRFID_Init();

//setup web call functions

//Particle.function("netopen", R1ON);
//Particle.function("netclose", R2ON);
//Particle.function("netstop", R3ON);

  digitalWrite(re1, HIGH); //turn off relay
  digitalWrite(re2, HIGH); //turn off relay
  digitalWrite(re3, HIGH); //turn off relay
  digitalWrite(re4, HIGH); //turn off relay

}

// This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called.
// Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection).  The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them.

void loop() {

//Loop for RFID ----------------------------------------------------------------------

//unsigned char checksum1;
  unsigned char status;
        unsigned char str[MAX_LEN];
        //unsigned char RC_size;
        //unsigned char blockAddr;  //Selection operation block address 0 to 63
        //String mynum = "";

        str[1] = 0x4400;
  //Find tags, return tag type
  status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
  if (status == MI_OK)
  {
          Serial.println("RFID tag detected");
                 }

  //Anti-collision, return tag serial number 4 bytes
  status = myRFID.AddicoreRFID_Anticoll(str);
  if (status == MI_OK)
  {
//          checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
          Serial.print("The tag's number is:\t");
          Serial.print(str[0]);
            Serial.print(" , ");
          Serial.print(str[1]);
            Serial.print(" , ");
          Serial.print(str[2]);
            Serial.print(" , ");
          Serial.println(str[3]);

//check if valid card combination
            if((str[0] == 333) && (str[1] == 444) && (str[2] == 555) && (str[3] == 666) )                   //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
            {
                Serial.println("\nKey fob identifed - Josh\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }

            } else if((str[0] == 222) && (str[1] == 333) && (str[2] == 444) && (str[3] == 555) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                Serial.println("\nCar Charge Card Identided - Josh\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }
            } else if((str[0] == 111) && (str[1] == 222 && (str[2] == 333) && (str[3] == 444) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                Serial.println("\nCar Garage Card Identided - Charlotte\n");

                if(doorstate == 1) {
                  //door is already open so close
                    // Close Garage Door
                    R2ON(); //turn on relay
                    doorstate = 0;
                    Serial.print("Relay 2 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R2OFF(); //turn off relay
                    Serial.print("Relay 2 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                      Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                    Serial.println("");

                } else {
                  //door is closed so open

                    //Open Garage Door
                    R1ON(); //turn on relay
                    doorstate = 1;
                    Serial.print("Relay 1 on") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    R1OFF(); //turn off relay
                    Serial.print("Relay 1 off") ;
                    Serial.println("");
                    delay(1000); // wait 1 second
                    Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                    Serial.println("");
                }
            }
            Serial.println();
            delay(1000);
  }

        myRFID.AddicoreRFID_Halt();      //Command tag into hibernation

   //End Loop For RFID  ----------------------------------------------------------------------

OpenButtonState = digitalRead(btn1);
CloseButtonState = digitalRead(btn2);
StopButtonState = digitalRead(btn3);

if (OpenButtonState == HIGH) {

  Serial.print("Open State Button HIGH - Opening Garage Door")  ;
  Serial.println("");
    //Open Garage Door
  R1ON(); //turn on relay
  doorstate = 1;
  Serial.print("Relay 1 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R1OFF(); //turn off relay
  Serial.print("Relay 1 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
  Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
  Serial.println("");
  }

if (CloseButtonState == HIGH) {

  Serial.print("Close State Button HIGH - Closing Garage Door") ;
  Serial.println("");
    // Close Garage Door
  R2ON(); //turn on relay
  doorstate = 0;
  Serial.print("Relay 2 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R2OFF(); //turn off relay
  Serial.print("Relay 2 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
    Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
  Serial.println("");

  }

if (StopButtonState == HIGH) {

 Serial.print("Stop State Button HIGH - Stopping Garage Door")  ;
 Serial.println("");
 // Stop
  R3ON(); //turn on relay
  doorstate = 1;
  Serial.print("Relay 3 on") ;
  Serial.println("");
  delay(1000); // wait 1 second
  R3OFF(); //turn off relay
  Serial.print("Relay 3 off") ;
  Serial.println("");
  delay(1000); // wait 1 second
      Serial.print("Stop State Button HIGH - Finished Stopping Garage Door")    ;
  Serial.println("");

  }

  // And repeat!
}

void R1ON() {

    digitalWrite(re1, LOW); //turn on relay
    //Particle.publish("Relay 1 on - Door Open");
    delay(1000); // wait 1 second
    digitalWrite(re1, HIGH); //turn off relay
    //Particle.publish("Relay 1 off");

}

void R1OFF() {
  digitalWrite(re1, HIGH); //turn off relay
    //delay(1000); // wait 1 second

}

void R2ON() {

    digitalWrite(re2, LOW); //turn on relay
    //Particle.publish("Relay 2 on - Door Closing");
    delay(1000); // wait 1 second
    digitalWrite(re2, HIGH); //turn off relay
    //Particle.publish("Relay 2 off");

}

void R2OFF() {

    digitalWrite(re2, HIGH); //turn on relay
    //delay(1000); // wait 1 second

}

void R3ON() {

    digitalWrite(re3, LOW); //turn on relay
    //Particle.publish("Relay 3 on - Door Stopped");
    delay(1000); // wait 1 second
    digitalWrite(re3, HIGH); //turn off relay
    //Particle.publish("Relay 3 off");

}

void R3OFF() {

    digitalWrite(re3, HIGH); //turn on relay
    //delay(1000); // wait 1 second

}

void R4ON() {

    digitalWrite(re4, LOW); //turn on relay
    //delay(1000); // wait 1 second

}

void R4OFF() {

    digitalWrite(re4, HIGH); //turn on relay
    //delay(1000); // wait 1 second

}

What should the line str[1] = 0x4400; do? It currently just don't make sense

Welcome to C++. That out of the way, looks like you wanted to made a call to fuction AddicoreRFID_Request(int,unsigned int). But instead made a call to AddicoreRFID_Request(int,unsigned char). See the difference? The compiler did. This is call Overloaded in C++. Going on, do clean up your code. But my bet is that you have a memory leak.

Re 0x4400 line I'm not entirely sure, it was from the RFID sample code and I think may have something to do with FRAM via the included libraries. But not sure!

reduce your code to only read the RFID tag and print out that it has been detected .... if that continues to work, then add code to print out data from the card and test again .... keep adding code  and testing

Can you provide a link to the sample code? Writing an int to a char does not make sense, so there is definitely something wrong there. You can try another compatible RFID library. like this one which was linked at the manufacturers site.

In 50+ years of dealing with hardware/software issues, I've found that the culprit is almost never the hardware. So, your problem is most likely the software.
To start with, there are several major problems with your code:

You are using an unsigned char type to represent integer values > 256; this will not work.  When I tried to compile your code, one of the many error messages was "StackOvrFl.ino: 107:8: warning: large integer implicitly truncated to unsigned type [-Woverflow]" on the line 'str[1] = 0x4400;' You need to declare 'str' as 'unsigned int str[MAX_LEN];'.
It's really bad form to use 'nicknames' ('uchar') for types; If someone else needs to maintain or modify your code (or help you with it as in this case), they are going to trip over that and emit 4-letter words in your direction.
Turn on compiler warnings and errors, and don't stop debugging until all such warnings/errors are cleared.  The compiler is your friend; let it help you.
If you had turned on compiler warnings/errors, you would have found that the identifier 'MI_OK' was never declared, and so can have ANY VALUE when you check it.

The combination of the integer overflow and undeclared symbol problems will almost undoubtedly cause undefined behavior, but there may be other issues as well.  Clean up your code, pay attention to compiler warnings, and then see what happens.
Good luck!
Frank

Thanks for your response Frank. I took the code used in that section from the manufacturers example, so had trusted that it would be suitable. #2 I've removed the short hand as you suggested. #3 I've set the compiler to show 'more' in the preferences. #4 Again this came from the example, but I tried to declare it and then the compile failed. Is it possible this is declared within the includes?  #1 I tried to change to your suggestion and this then threw up:

no matching function for call to 'AddicoreRFID::AddicoreRFID_Request(int, unsigned int [16])'

This error says that the call to 'AddicoreRFID_Request(int, unsigned int [16])' in your code has an argument list that isn't EXACTLY the same as the argument list for the definition of that function.  Compare them very carefully and you'll find the problem

Presumably because the type has changed from char to int in the calling code but not in the function it calls? I guess that means updating the function and anything it does too. Would it be useful to post the code from the include here too?

I didn't spend much time looking at the code closely after noting the type definition and undeclared variable issues.  I think you need to work your way through the code carefully, fixing ALL the issues before proceeding.  You might consider radically simplifying the code to start with, and only adding functionality when what you have works as intended

Consider removing the type String from the code including removing where String is used in passing formal values to some functions.  It appears to do nothing.  And if the compiler does not optimize it out, could actually be consuming what little RAM the embedded processor contains.
The type String loads in all kinds of help you may or may not need.  Generally String is a bad idea for embedded processors because Sting consumes a large amount of resources to support all of String's features. And sometimes those resources are not given back.  This is generally referred to as a memory leak. Briefly, this is when the RAM in an embedded processor is considered used by the program, but is not actually being used by the programmer.

Thanks I've made some combined amendments and have re flashed the code... I'll test in the morning and let you all know if it worked :)

I'm curious.  Does the RFID stop working after a fixed time?  Or after a fixed number of garage-door-operations?

I've not been able to identify the exact point at which it stops, but can confirm it has stopped again. I'll paste the revised code below. jotola may be right though that I may need to break it down to work out whats causing the issue.

I've edited the question to show the revisions thus far.

You still have some weird stuff going on.  You say you copied the code from a working project?  But I see stuff like "unsigned char str[MAX_LEN];" followed by "str[1] = 0x4400;".  But, normally, an unsigned char is 8 bits large.  That's 2^8 or a maximum of 256 or 0x00FF.  But 0x4400 is way bigger than that.  So that's not going to work.

https://www.addicore.com/v/vspfiles/downloadables/Product%20Downloadables/RFID_RC522/AddicoreRFID.zip

Yes, I did find the code on the Net and was confused by it as well.  I don't have time now.  I might look at it later.  In the meantime it would be good for you to follow  jsotola's suggestion and reduce your code to simpler components or start over but only add one feature at a time.  And don't add anything you do not understand.  That should keep stuff you don't need like "String" out of your final effort.


text:
Using the YS-IRTM with an Arduino Uno
Picked up a YS-IRTM IR Transmitter/Receiver module to do some testing for a project. There's not a lot of details on it but eventually came across two very important sources:
Translated Module Datasheet: https://docplayer.net/101050357-Nec-infrared-codec-module-ver1-0-ys-irtm.html
Examples: https://forum.arduino.cc/index.php?topic=359707.msg2861077#msg2861077
I've been trying to get this working for a few days and so far haven't gotten anything. Need to reach out before I pull out whatever hair I have left.
BTW, new to this and may have easily missed something.
Wiring Diagram
Arduino Uno    YS-IRTM
5v          -> 5v
GND         -> GND
0 RX        -> TXD
1 TX        -> RXD

Code
int icb = 0;
SoftwareSerial ir_mod(0, 1);

void setup(){
  Serial.begin(115200);
  while(!Serial){}
  Serial.println("Setup IR Serial");
  ir_mod.begin(9600);
  while(!ir_mod){}
  Serial.println("IR Serial Ready");
}

void loop(){
  if(ir_mod.available() > 0){
    icb = ir_mod.read();
    Serial.print(" 0x");
    Serial.println(icb, HEX);
  }
}

Current Output
Setup IR Serial
IR Serial Ready

Nothing will happen if I try to interact with the Receiver with any IR Transmitter (like a TV/AC Remote) but if I disconnect and reconnect the power, I get " 0xFFFFFFFF". Then nothing.

edit your question so that it says that ... right now your question is still unclear ... then delete your comment

I found these links:
https://www.cnx-software.com/2017/04/20/karls-home-automation-project-part-4-mqtt-bridge-updated-to-use-ys-irtm-ir-receiver-transmitter-with-nodemcu/
https://stackoverflow.com/questions/63401838/ir-tx-rx-issues-for-ys-irtm-receiver-transmitter

English-translated datasheet: https://forum.arduino.cc/uploads/short-url/4AdsX6NynXYzUdRjr7Vp3g7xLpF.pdf ... original Chinese datasheet: https://c1555f5ec9.clvaw-cdnwnd.com/34662fcf1f1e607c561442431023ac8e/200006816-5a9e05b919/Infrared%20decoding%20module%20manual.pdf ... schematics: https://c1555f5ec9.clvaw-cdnwnd.com/34662fcf1f1e607c561442431023ac8e/200006817-29e642ae0c/Infrared%20decoding%20module%20SCH.pdf ... open source project "micropython-ys-irtm" at GitHub: https://github.com/mcauser/micropython-ys-irtm

I am also new to this but if I am not mistaken, you seem to have connected the IR module to Arduino Hardware Serial while trying to communicate with the module via SoftwareSerial. Try using Arduino pins 2 and 3 for the SoftwareSerial instead of pins 0 and 1. Forgive me if I got it all wrong.

Thanks. I did think of that so during my testing, I had used other pins, such as 8 and 9 but no change.

Default baud for module is 9600 unless you previous set it diffrent as per the datasheet A1 F3 ## 00 00 I believe

I did play with the baud rate. I reset the device to set it back to default which meant it was reset to 9600. That means the baud rate to the device is 9600 and the rate to the monitor is 115200.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
I want to code a depth sensor for arduino
I want to code a depth sensor for a little sub that i am working on. I want it to submerge to a any certain depth  for example 2ft. The speed of the motor is to increase by 5 until it reaches the set point given. The problem that I am facing is: whenever it reaches the set example point of 2ft the motor turns off and the sub resurfaces to the top and doesn't hold the depth .
What I want is that for whatever speed the motor is at for 2ft depth, to maintain its speed and keep the sub submerge at 2ft.
#include <MS5837.h>
#include <Wire.h>
#include "MS5837.h"
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster;

float x;
float error;
int pwm = 1525;
float currentdepth = sensor.depth();
float recquireddepth = -0.4;  //  set depth u wish to maintain in meters

void setup() {
      Serial.begin(9600);
     vertical_thruster.attach(6);
     vertical_thruster.writeMicroseconds(1500);
 /////////////////////////////////////////////Bar 30 Configuration ////////////////////////////////////////
  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
    Serial.println("Init failed!");
    Serial.println("Are SDA/SCL connected correctly?");
    Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
    Serial.println("\n\n");
    delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

  sensor.read();
  Serial.print("Depth: ");
  Serial.print(currentdepth);
  Serial.println("m");
error = (currentdepth) - (recquireddepth) ;

if ( error!=0)
  { pwm +=5;
    vertical_thruster.writeMicroseconds(pwm+=5);
    Serial.println( pwm+=5);
    Serial.print ( " Submerging ");
  }
if ( error=0){
  vertical_thruster.writeMicroseconds(pwm);
  Serial.print ( "  At Depth");
}
else if ( error >-0){
  vertical_thruster.writeMicroseconds(1400);
  Serial.print ( "resurfacing");
  delay(1000);
}
}

Help with what? What is not working as expected and what is the expected result? Are you getting any errors or is something else happening?

The code compiles and work yes but when it reaches its set value it dont hold the speed to keep it at the depth set

Please, edit the question to add all the relevant information. One should not need to read all the comments to understand a question. Re “it dont hold the speed”: what does it do instead? You should try to give a complete description of the problem.

question has been edited.

#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>

MS5837 sensor;
Servo vertical_thruster;

// Variables

float current_depth ;
float set_depth = 0.30 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
float pwmvertical_thruster;
int PID_value = 0;
int PID_p = 0;
int PID_i = 0;
int PID_d = 0;

//PID constants
float kp = 4.1;
float ki = 0.03;
float kd = 1.8;

void setup() {
  Serial.begin(9600);
 vertical_thruster.attach(6);
 Time = millis ();
 vertical_thruster.writeMicroseconds(1500);

///Bar 30 Configuration

 Serial.println("Starting");
 Wire.begin();
while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
 }
 sensor.setModel(MS5837::MS5837_30BA);
 sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
PID_error =  set_depth - current_depth ;

// Calculate the P Value
 PID_p = kp * PID_error;

// Calculate the i value in a range on +-0.3

 if (-0.3 < PID_error < 0.3 )
  {
  PID_i = PID_i + (ki * PID_error);
  }

// Calculate the d value
PID_d = kd*((PID_error - previous_error)/elapsedTime);
// The total PID value
PID_value = PID_p + PID_i + PID_d;

// range for the blue robotics esc

 if ( PID_value < -400)
 {
 PID_value = -400;
  }
  if( PID_value >400)
  {
 PID_value = 400;
  }
// calcualte the pwm
 pwmvertical_thruster = (1500 + PID_value) || ( 1500 - PID_value);
if(pwmvertical_thruster < 1500)
 {
  pwmvertical_thruster= 1500;
  }
 if(pwmvertical_thruster > 1900)
  {
   pwmvertical_thruster=1900;
   }
    Serial.print("Depth: ");
    Serial.print(sensor.depth());
    Serial.println(" m");
    vertical_thruster.writeMicroseconds(pwmvertical_thruster);
    Serial. println ( "t\t");
    Serial. println ( pwmvertical_thruster);
     previous_error = PID_error;

   }`

Is this the working code? Is it behaving correctly? (Since you now marked it as correct answer)

@chrisl it works but I need to get my values right the esc correct . The esc that I am using has 2 Maximum with 1500 equals to stop . 1500 -1900 is Min to Max clockwise and 1500-1100 is min to max counter clockwise.

Your code has several problems:

You are including the MS5837 library twice. That just doesn't pose a problem, because the library has include guards, that make sure it is only included once.
At global scope you use float currentdepth = sensor.depth();, which calls the function sensor.depth(). This will be done before the setup() function, so at that time the sensor library does not have any valid depth data. So it's useless. You can just set it to zero.
In your loop() you are doing sensor.read(), but then you are never actually getting the new depth value from the library. You are just again using currentdepth without changing it ever. You should set the variable to the new value by using currentdepth = sensor.depth(); after the sensor.read().
You are using the statement if ( error=0). Using only a single = means an assigment. So here the variable error get's set to zero and the if statement will not compare it so zero. You have to use a double =: if(error == 0).
if( error >-0): Why are you checking for error being greater than MINUS ZERO. Sure, -0 is a valid integer, but mostly senseless. Also it is questionable, if the logic is correct here, since first you check for error being different than zero. Then you check for it being zero and then (if it is not equal zero) you check for it being greater than zero. If error really happens to be greater than zero, you will first write pwm to the servo and then directly 1400, which is submerging and resurfacing directly after another in only one loop.
The whole if structure seems quite off. You should rethink the logic of the program.

That said, for reaching a set point of whatever kind it is good to use a PID controller, that will get you to the setpoint rather fast and will keep you there. A PID controller can be done in hardware or software. For implementing a software PID controller on Arduino you can use one of the various PID libraries, for example this one. Most libraries also contain examples, that show how to use them.

Good, through answer. (Voted) I was going to suggest a PID also. You need something that will "hone in on" the target depth and then keep it there. You'll have to tune the PID with the right control values though.

@chrisl @ Duncan C  I have updated and fixed the code. can you take a look at it ?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Controlling an analog potentiometer using an Arduino
I want to be able to control an analog potentiometer. I'd like to be able to go from the minimum range to the maximum range possibly using an Arduino and a motor/servo. I want to be able to control vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending  a (MIDI) signal.How would I go about doing this?

Hello and welcome to Arduino StackExchange! Just a small question, why not just use a digital potentiometer?

I want to be able to control  vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending  a (MIDI) signal.

I think what you are looking for is a motorized fader.

Ideally I'd like to use the original pot and have the servo/whatever the solution is inside the case so that you can't tell a mod was made.

Add a pulley wheel to the shaft of the pot and drive it with a DC motor and a rubber belt? Like a belt drive from an old tape deck. You may be able to fit it on the inside of the housing.

Like this but with the gubbins on the inside of the case, not the outside.

That works, but I would need it on multiple pots and on the inside. Maybe I'm looking for motorized potentiometers?

The first problem we have is that replacing the original potentiometer might be wrong thing to do. Analog audio hardware is usually nonlinear, because the volume of the sound is actually a logarithmic function. So the potentiometers might be fine tuned specifically for particular device, and impossible to acquire today since it's vintage.
I suggest a different approach. Connect the knobs to rotary encoders, or cheap linear potentiometers. That way you will receive data about what the user is doing, and what setting does he want to change. They usually are small and you might even fit an extra el-cheapo 28BYJ485V stepper motor to move the knobs to provide feedback. (It can be modified doubling it's torque)
Move all the audio potentiometers inside the case of the device and connect them directly to a stepper motor or a servo to move them only with Arduino.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Temperature control using a DHT11
I am trying to do a project on temperature control and found an example but cannot get the code to work. I have read forums and tried to fix the issue which is below the code.
Code:
#include<DHT.h>      // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#define dht11dpin 12
DHT11;
#define pwm 9
#byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

#void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Circuit Digest ");
  delay(2000);
}

void loop()
  DHT11.read(DHT11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF            ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

Error:
In file included from C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:2:0:
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected unqualified-id before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:6:1: note: in expansion of macro 'DHT11'
 DHT11;
 ^
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected initializer before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:35:1: note: in expansion of macro 'DHT11'
 DHT11.read(DHT11pin);
 ^
sketch_jan20b:36: error: request for member 'temperature' in '11', which is of non-class type 'int'
 int temp=DHT11.temperature;
                ^
sketch_jan20b:37: error: 'lcd' does not name a type
   lcd.setCursor(0,0);
   ^
sketch_jan20b:38: error: 'lcd' does not name a type
   lcd.print("Temperature:");
   ^
sketch_jan20b:39: error: 'lcd' does not name a type
   lcd.print(temp);   // Printing temperature on LCD
   ^
sketch_jan20b:40: error: 'lcd' does not name a type
   lcd.write(1);
   ^
sketch_jan20b:41: error: 'lcd' does not name a type
   lcd.print("C");
   ^
sketch_jan20b:42: error: 'lcd' does not name a type
   lcd.setCursor(0,1);
   ^
sketch_jan20b:43: error: expected unqualified-id before 'if'
   if(temp <26 )
   ^
sketch_jan20b:50: error: expected unqualified-id before 'else'
     else if(temp==26)
     ^
sketch_jan20b:57: error: expected unqualified-id before 'else'
      else if(temp==27)
      ^
sketch_jan20b:64: error: expected unqualified-id before 'else'
      else if(temp==28)
      ^
sketch_jan20b:71: error: expected unqualified-id before 'else'
     else if(temp==29)
     ^
sketch_jan20b:77: error: expected unqualified-id before 'else'
      else if(temp>29)
      ^
sketch_jan20b:83: error: expected constructor, destructor, or type conversion before '(' token
   delay(3000);
        ^
sketch_jan20b:84: error: expected declaration before '}' token
 }
 ^
exit status 1
request for member 'temperature' in '11', which is of non-class type

Are you mixing 2 libraries? Code seems like https://playground.arduino.cc/Main/DHT11Lib but you seem ot be using the Adafruit library https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino ? Can you tell us whhich library installed test with above example instead? Also why are there # in #byte degree[8] and #void setup()?

It's a bit hard to see, but
DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like
DHT11 dht;

where dht is an instance and you can use that.
Than in
DHT11.read(DHT11pin);

you should replace it by
dht.read(DHT11pin);

so got past that bit but getting issue with the line lcd.createChar(1, degree);
saying degree was not declared in sope

degree should be a variable, which you haven't declared (unless it's global and you didn't post it).

Several variable declarations and the setup definition are prefixed by #.  Those will prevent the line from being processed correctly. degree is one of those with that error.

It seems the code has been changed since my comment.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Does a pin (input pin Arduino) still float when connected to GPIO on RPI?
I am currently testing my application on an Arduino, and I experience floating pin issues. My program reads the pin status of input pins, which are configured as
pinMode(5, INPUT);
digitalWrite(5, HIGH);

but still they tend to float sometimes.
Will this be solved when I connect the pin directly to a GPIO pin on a RPI? Specifically when the application running on the RPI is not active yet (thus the GPIO pin will not actively high or low yet).
Both the PI and and Arduino will be powered at the same time, but the application on the Arduino will be active much faster than the application on the RPI.
So my concern is that while the RPI is still booting and loading the app, the Arduino might still 'suffer' from floating pins, which gives undesirable output to the things my Arduino controls.
Or, will the fact that the RPI and Arduino both have power, share the same ground, will result in a stable input on the Arduino?
PS: not an expert on electronics, hence the question. I can't test this yet as I don't have all the hardware of this project.

You need to enable the internal pull-up resistors which are designed to prevent undefined input states on unconnected inputs.
Change
pinMode(5, INPUT);

to
pinMode(5, INPUT_PULLUP);

For more information on this see Arduino digital pins.

I would add, for OP's sake, that what they are doing used to be the way to configure internal pull up prior to arduino 1.0.1 , but this does not work in newer versions of the SDK which added the INPUT_PULLUP configuration. There are probably many tutorials and example projects still using the old pattern.

Thanks. I don't know if I ever knew that.

Thanks for the correct way of doing this. I the meantime I learned that I can also create a pulldown resistor incredibly easy! I connected a 22k resistor to ground and connected the input on my arduino to that resistor. I also connected my RPI output to that resistor. That works perfectly, no floating behavior at all. I will also give your solution a try as it even simpler. So thanks for helping out!

Good work. Most designs use the internal pull-ups as it saves the additional components. Some micros have the option of a pull-down as well. Thanks for the feedback.


text:
ESP8266 is not responding
I have ESP8266, FTD232 UART, Linux mint 17.3 OS, Arduino IDE 1.6.7,
Following are the connections:
External Power source  ESP8266
  3.3 V                  VCC
  GND                    GND
  3.3 V                  CHPD
  3.3 V                  GPIO0

FTD232 UART  ESP8266
    RX         TX
    TX         RX

Plus FTD232 GND and Power Source GND are connected to make sure that there is a common reference.
I open the Arduino IDE and select Generic ESP 8266 board.
Open Serial Monitor:
AT command, no response..?
I have tried lots of different things found from web, even a new ESP8266, but no response.
Can anybody provide help...?

Is your serial monitor set to BOTH NL & CR?

Which model ESP8266?

Yeah Both NL & CR And Baud Rate 9600,
ESP8266-01 Model, the one with 8 pins and 2 GPIO.

Dont select 'Generic ESP8266'; leave the default IDE settings. Simply connect the ESP, open the serial monitor, and try sending commands at 9600 or 115200. Or you can use minicom to send the commands directly without the IDE

1.What firmware ? AT commands do not work in nodeMcu firmware.
Usually the AT firmware work to 115200 bps.
2.If your FTD232 works at 5V, you will need resistor between Arduino TX and ESP RX. ESP8266 only works at 3.3V.
3.Try esplorer - is a very nice tool to test ESP8266:
http://esp8266.ru/esplorer/

The ESP8266-01 will boot and show some boot up messages at baud rate 76800 before switching to the default configured baud rate of 9600 or 115200.
Try setting the baud rate to 76800 and reset the ESP8266 to see if you can see the boot up messages first to determine if your circuit is working. You might see something like this:

ets Jan 8 2013,rst cause:4, boot mode:(3,7)

Just a note on the "initial" baud rate of these devices ... many ESP8266's use a 26MHz rather than 40MHz crystal - this apparently does not change the  clock rate of the MCU, but it does effect the boot loader baud rate ... what should be 115200 becomes 74880 (not a conventional rate, but is supported by arduino ide at least) the reason for this oddball rate ... 115200 * 26 / 40 = 74880 - I guess the boot loader is setting the uart for what it thinks is 115200 before the necessary "adjustments" for 26 vs 40MHz crystal is taken into consideration.


text:
Use Adafruit Colorsensor to distinguish between green and red
I am using the Adafruit TCS34725 to sense color. I have used the Colorview code example to set it up to sense all colors, works great. The thing I want is for it to tell me if it is seeing either green or red, I don't care about the other colors.
Can anyone suggest what I can do?

if(r>200&&g<200&&b<200){println("RED!");}else if(r<200&&g>200&&b<200){println("GREEN!");}  ?

Okay, it seems you have 16-bit values, but don't make it too hard. As long as there is way more red as green/blue, you can say it's red.

Based on what I could find, you will have to calibrate the sensor to recognize these colours. First, run the Colourview code. Take down the raw RGB and CLEAR values obtained for an object you consider green and another you consider red. Find out if these values are consistent, each time you power down the sensor and turn it on again. If they aren't, record how much dead zone there is i.e. the maximum difference in readings (between resets) that you get for the same colour. Then using the values you get, try this code:
#include <Wire.h>
#include "Adafruit_TCS34725.h"

#define MAX_OFFSET 50  // the maximum diff you found between readings

typedef struct {  // struct to hold raw color data
   uint16_t red;
   uint16_t green;
   uint16_t blue;
   uint16_t clear;
} Color;

Color my_red = {3344, 3333, 23444, 3333}; //here you enter your minimum recorded values for red in the order of the struct members above
Color my_green = {22222, 4444, 5555, 3333}; //the same for green

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }
}

void loop() {
  uint16_t clear, red, green, blue;

  tcs.setInterrupt(false);      // turn on LED

  delay(60);  // takes 50ms to read

  tcs.getRawData(&red, &green, &blue, &clear);

  tcs.setInterrupt(true);  // turn off LED
  if (compare_colour(&my_red, red, green, blue, clear)){
      Serial.println("I see red.");
  }
  else if (compare_colour(&my_green, red, green, blue, clear)){
      Serial.println("I see green.");
  }
}

boolean compare_color(Color * std, uint16_t r, uint16_t g, uint16_t b, uint16_c){
if ((r - std.red <= MAX_OFFSET) && (r - std.red >= 0) &&
      (g - std.green <= MAX_OFFSET) && (g - std.green >= 0) &&
      (b - std.blue <= MAX_OFFSET) && (b - std.blue >= 0) &&
      (c - std.clear <= MAX_OFFSET) && (c - std.clear >= 0))
  {
      return true;
  }
  return false;
}

You can use this code directly after you have gotten the sensor readings for red and green objects.

Where should I substitute it? Not really sure where I should put this

Replace the colorview setup() and loop() with mine. Also copy all the extra stuff in my code (before my setup()), into the colorview code, at the same position. In the colorview code, get rid of any code at the top, concerning the RGB LEDs since you won't be using them (like the #define green_pin and so on), though this really isnt necessary. Make sure to get rid of the gammaTable created at the top though, to save memory.

I appreciate your time and answers, I have tried this with no luck.... I guess I am doing something wrong. Could you insert and replace the necessary parts of code so that I can see if this will work as I need it to?

@DanWilkes Ok. First tell me...have you gotten the readings for a red and a green object? Using the original Colorview code?

I have edited the code. You can use it as is. Only after you have gotten the the readings though. I cant tell you the values the sensor will return for a red/green object. You must run the colorview code (no need for the RGB LEDs) and take at least 10 separate readings and then select the minimum for each colour and the also obtain the maximum difference between the maximum and minimum readings for any colour and set the MAX_OFFSET variable to this difference.


text:
Communication between Arduino and XBee
I have two XBee Pro S2Bs: one is plugged in to a USB explorer, and; the other is plugged into an Arduino Wireless Protoshield, which is connected to an Arduino Uno.
My XBee connected to the explorer is configured as the coordinator in AT mode, and the XBee connected to the Arduino is configured as a router in AT mode. As a side note, I tested the network with a second USB explorer, and I was able to communicate between both XBees.
I uploaded the following code to the Arduino (which is just a sample I pulled off the internet somewhere):
char rx_byte;

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

void loop()
{
    if (Serial.available() > 0)
    {
        rx_byte = Serial.read();
        Serial.print("You Typed: ");
        Serial.println(rx_byte);
    }
}

Once I upload the code and turn on the serial monitor for the Arduino (using either the Arduino IDE or Visual Micro, with the Arduino plugged in via USB), and turn on the serial monitor on for the XBee connected to the USB explorer (using the serial monitor in XCTU), I get the following results:

If the wireless proto shield has its switch set to USB mode, then I can send data from the Arduino serial monitor to the serial monitor in XCTU, but the Arduino serial monitor doesn't receive data that is typed into the XCTU serial monitor.
If the wireless proto shield has its switch set to Micro mode, then I get mostly the opposite result.  I can send data from XCTU serial monitor to the Arduino serial monitor, which the result is returned to the XCTU serial monitor, e.g., if I type "X" in XCTU serial monitor, both serial monitors say "You Typed: X".  However, if I try to send data through the Arduino's serial monitor, neither serial monitor displays anything.

What I would like to do is be able to type in either serial monitor and have the data displayed in both serial monitors, like you would expect in a simple chat program.
Can someone see where I have gone wrong and/or how to get to the correct result?

Check out https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test
Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time.


text:
Speed Control L298 motors
Proceeding is the relevant part of the code for the problem I'm asking assistance with.  I'm attempting to vary the speed of the robots motors with PWM. The left motor speed can be varied numerical. The right motor fails to move. Any ideas is appreciated. The motor speed code is at the end of the sketch.
Any assistance is greatly appreciated.
//Below are the symbolic constants. Instead of having to type in a non-sensical pin number each time we want to do something we can write an easy to understand name which represents the pin, the compiler will then replace the names with the numbers
 #define LeftMotorForward 8
 #define LeftMotorBackward 9
 #define LeftMotorSpeed 10
 #define RightMotorForward 6
 #define RightMotorBackward 7
 #define RightMotorSpeed 5
 #define USTrigger 3
 #define USEcho 2
 #define MaxDistance 100
 #define LED 13

//Here we have created two 'objects', one for the servo and one for the ultrasonic sensor
 Servo servo;
 NewPing sonar(USTrigger, USEcho, MaxDistance);

//Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values
 unsigned int duration;
 unsigned int distance;
 unsigned int FrontDistance;
 unsigned int LeftDistance;
 unsigned int RightDistance;
 unsigned int Time;
 unsigned int CollisionCounter;

 void setup()                                            //This block happens once on startup
 {
  Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

  //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(LeftMotorSpeed, OUTPUT);
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);
  pinMode(RightMotorSpeed, OUTPUT);
  pinMode(LED, OUTPUT);
  servo.attach(11);                                    //The servo is attached to pin 4
 }

 void loop()                                           //This block repeats itself while the Arduino is turned on
 {
  servo.write(90);                                    //Rotate the servo to face the front
  scan();                                             //Go to the scan function
  FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function
  Serial.println("Front distance = ");
  Serial.print(distance);
  if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...
  {
   moveForward();                                     //Go to the moveForward function
  }
  else                                                //Else (if there is something infront of the robot within 40cm) then...
  {
    CollisionCounter = CollisionCounter + 1;
    moveStop();                                       //Go to the moveStop function
    navigate();
  }
 }

 void moveForward()                                    //This function tells the robot to go forward
 {

  Serial.println("");
  Serial.println("Moving forward");
  //Turn on left motor
  digitalWrite (LeftMotorBackward, LOW);
  digitalWrite(LeftMotorForward, HIGH);
  //set speed
  analogWrite(LeftMotorSpeed, 100);

 // turn on right motor
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(RightMotorForward, HIGH);
// set speed
   analogWrite (RightMotorSpeed, 75);

Also asked here

You are not sending a speed command to the motor, you are sending it an analog voltage with the analogWrite. If that voltage is too low, the motor will stall. A higher value should make it spin faster. If you want the speed to be more tightly controlled, you will need encoders on the motors to sense how fast they are spinning, or use stepper motors.

First try commenting out the
 Servo servo;

line, and all other bits using the servo.  If it works then there's your problem - use the Mega possibly as this allows more PWM outputs.
If it doesn't work with the Servo bits removed, then report back and include the Arduino model you're using.
Good luck!

int value;
for(value = 0 ; value <= 75; value+=5)//if value is <=50 left motor does not spin. >75 both motors turn
Serial.println("");
Serial.println("Moving forward");
analogWrite(LeftMotorSpeed, value);//int value has no effect on speed
analogWrite (RightMotorSpeed, value);// same as LeftMotor)

Thanks Andy. I'm getting a Mega board and using pin 11 on the Uno, to avoid the servo conflict.

I commented all references to servo, the same results. Comment out the servo code doesn't seem to make a difference. What's going on is when the speed is numerically controlled the motor speed varies. At 50 the right motors slows down and the left motor HALTS, Not sure what's going on.
//This function tells the robot to go forward
int value;
for(value = 0 ; value <= 75; value+=5)
    //if value is <=50 left motor does not spin. >75 both motors turn
    Serial.println("");
    Serial.println("Moving forward");
    analogWrite(LeftMotorSpeed, value);//int value has no effect on speed
    analogWrite(RightMotorSpeed, value);// same as LeftMotor)

    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(RightMotorBackward, LOW);
    digitalWrite(RightMotorForward, HIGH);

Now you've got both motors running, but they don't run at the same speed?  A common problem - possibly not enough current getting through from the battery. See Jim's answer.


text:
Sharing a Digital Pin / What to do when two components need a specific Digital Pin?
I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.
Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.
The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).

Which hardware (components)? Which libraries?

It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See How do you use SPI on an Arduino?
You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need separate slave select pins. Often D10 (digital pin 10) is used as a default for slave select.
Another possible solution is to use "bit-banged" SPI for one device. I have a page on my forum about SPI which includes a bit-banged software implementation.
The library is at https://github.com/nickgammon/bitBangedSPI and is quite short.

Hey Nick first and foremost thanks for the time to help! I have added which libraries and components I am trying to use!


text:
Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code
I am making a learning toy which kids can play with and learn basics of programming. But i am tired of keep replacing the AA batteries as they run out in few days. So i am thinking of using rechargeable battery. But i am very worried to use it considering it is kids toy and people says lipo and li ion battery can explode. There are dangers or over charge and heat etc.
Is it safe to use them? Which one to use?
I am using Arduino pro mini 3.3v and some times 5v.
I was planning to use: XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420
I think some users have misunderstood the question and have voted this question to be closed. This questions is very much to deal with programming also apologies if i have not made it clear.

We can get the battery level in the code, but is there any way in code we can some how turn off the charging when the battery has been fully charged.
I am under impression (might be wrong, you can correct me), normal
battery single AA cell dies after some time on heavy use (using dc motor etc). But
rechargeable batteries are bigger with multiple cells in it they will
last longer. So if i am running some code in a loop for long time
will the battery get over heated will it be a problem.

I am voting to close this because as the question stands, it is off topic since it's about batteries and the fact there is an Arduino involved is irrelevant. A question about how to reduce the power consumption of your Pro Mini would be on-topic. However, I would recommend that you search for previous questions as that is likely to have been asked already.

If it's in a sturdy container and has protection circuitry there will be no issues.

It depends how old the children are and if they are supervised sufficiently.  Why not use a wall wart?  Why not use rechargeable NiCad batteries?  OK Cadmium gas can be released and that could cause blindness, disability, etc, but AA batteries can be made to explode.  You need to risk assess your solution based on the users, no one here can tell you its safe.

no common commercial batt will overheat from just running code w/o other hardware.

Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).
They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.
If I'm allowed to give you a tip, you could eventually pick one of these here, they are pretty good in my opinion.

Of course there are a ton of others around, so you can just pick one which fit your needs.
On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).

I don't think battery banks, even good ones, can be considered perfectly safe. In fact if you look at the safety guidelines for these things, they will specifically tell you to keep them away from children. Reason being, kids can poke things into the USB outlets, and cause them to short-circuit, and potentially explode.

@user1751825 They shut down if kids poke things in and short the circuit. It's really hard for brand name battery packs to explode. I've had a lot of them and since today no single one failed, nor have I heard of one failing in such a way. And, let's be honest: It's a lot safer than someone building his own power bank (OP wanted to build his own and even handle to his kids - bad idea)

Does the voltage output matter, when using one of these power banks, or will the Arduino just draw whatever current it needs for its power usage regardless of the voltage?

@StevenHolt Those powerbanks are all 5V, only the A changes between them. The example above has 2 ports, 1 being 1A and the other 2A (for tablets that demand more current). The Arduino will draw what he needs and nothing more, probably about 0.02 A. It will run for ages with that battery.


text:
NFC wont send URL to mobile phone
I'm using  nfc 2 click (NT3H2111), I tried via arduino to send data to my mobile phone using this code :
#include <Wire.h>

int i = 0;
int j = 0;

uint8_t NDEF_DATA[] = { 0x03, // NDEF Message
15, // Message size
0xD1, // Record header
1, // Type Length - 1 byte
11, // Payload Length - 11 bytes
'U', // Type / URI
0x01, // Payload
'm', 'i', 'k', 'r', 'o', 'e', '.', 'c', 'o', 'm',
0xFE
}; // NDEF Message End Mark

void setup()
{

delay(5000);
Wire.begin();
// initialisation de la liaison I2C
Serial.begin(9600);
// initialisation de la liaison série vers la console

Wipe_Tag() ;

Wire.beginTransmission(0x55);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(0x55, 7);
Serial.println("UUID:");
while(Wire.available())
{
Serial.print(Wire.read(),HEX);
}

delay(1000);
Serial.println();

Serial.println("Start wrting");
Wire.beginTransmission(0x55);
Wire.write(0x01);

for (i = 0; i < 16; i++)
{
Wire.write(NDEF_DATA[i]); //Fill Block with Data
}
Wire.endTransmission();
delay(50);

Wire.beginTransmission(0x55);
Wire.write(0x02);

for (i = 16; i < 32; i++)
{
Wire.write(NDEF_DATA[i]); //Fill Block with Data
}
Wire.endTransmission();
delay(50);

Serial.println("Start wrting");

}
void loop()
{

}

void Wipe_Tag()
{
for (i = 1; i < 50; i++)
{
Wire.beginTransmission(0x55);
Wire.write(i);
for (j = 0; j < 16; j++)
{
Wire.write(0x00); //Fill Block with Zeros
}
Wire.endTransmission();
delay(50); //Delay 50 ms

}
}

All I get is the right UUID than nothing happened, if I try to put my phone I can't read nothing ( it should send me to mikroe website).
As I'm using the nfc 2 click from mikroe.
Thanks for reading.

I don't know, wild shot in the dark, but which of the fields count towards the message size parameter, but you might want to check it has the right value.
Also do you need a null at the end of the text?

Also, in the loops you are sending 16 bytes, but the NEF_DATA contains 18 bytes.

Hi there, thank you for your help, in fact each register has 16 bits, this is why I divided the data into two registers


text:
Infrared distance sensor picks up distances that are not there
I have connected an Infrared sensor to my Arduino Uno and I've set this code up to blink whenever a distance of less than 50 cm is picked up. If there is an object less than 50 cm away, it does pick it up. However, with nothing in front of it it still blinks at random intervals. The sensor is new. Where do you think the problem is?
int sensorPin = 0;
int ledPin = 13;

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

void loop() {
  float distance = 12343.85 * pow(analogRead(sensorPin),-1.15);
  if(distance < 50){
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  delay(50);
}

Maybe some specks of dust, or just electrical noise. You could try averaging the measured value. What I generally do is take 10% of the current value, and 90% of the old averaged value.

Have you read this reference? http://bildr.org/2011/03/various-proximity-sensors-arduino/. It explains some of the issues with this sensor. It is great for a closed box with no "extra light". It is easy to disturb the sensor with IR from a remote or just sun light.

I see one problem with your code and how it relates to this device.
The output from the sensor is not the monotomic function you describe; not over its entire range.  Your conversion function describes only a section of the response.  The device is only intended to be used when an object is in range 10-80 cm.
You should check that the voltage at the analog input is valid before performing the math:
int v;

v = analogRead(sensorPin);
// sensor is valid in range 0.4 to 2.5 V
if((82 < v) && (v < 512)) {
  // voltage is in usable range, can convert
  distance = 12343.85 * pow(v,-1.15);
  if(distance < 50) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
}
else {
  // no valid reading - probably just skip and try again on next loop
}

With that the false triggers may be eliminated.

Scaling to voltage is unfortunately missing; float voltage = sensorValue * (5.0 / 1023.0); https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage

I am presuming that OP's formula does convert ADC counts to distance.  But I have corrected that the conditional is in counts.

Looks to me like there could be a signficant figures issue. Arduino can really only handle 7 digits of precision. You hit that right at your first constant in your distance variable, then you multiply by an integer to a power of -1.15. It's likely there are errors there that trip to less than 50, which would give you false positives.
As for the Sharp IR sensors, just buy an IR photodiode and LED for less than $1 USD and build and calibrate your own IR detector. You can calibrate it to a range of about 1 m. That's my recommendation. I did something similar after being frustrated by the cost of the Sharp IR Detectors. Wrote about it on my blog, if you're interested:
https://engineersportal.com/blog/2018/1/17/infrared-obstacle-detector-for-less-than-1


text:
Arduino Servo Free Rotation
I have a project where I use 22 servos. I attach all 22 of the servos in the setup and in the loop, I use myservo.write() command to make a particular servo move to a particular position.
The problem here is that, all the other servos become stiff at this point of time, even though I am not writing any value to those servos. By stiff I mean that the servo is holding at a particular random value. Which for most of the 22 servos is at or near 90°.
My question is how can I make a particular servo move, while allowing all the other servos to freely rotate. I think that when I attach a servo the program prevents the free rotation of the servo.
I was wondering if the signal to one of the servos is leaking to other servos because of an issue with wiring, but this is not the case. The other servos become stiff only when I attach them to the pins which have been "attached" as a servo in the program.

When you attach a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you write to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated.  That is how servos work.  They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven.
Depending on the servo you might actually damage the mechanics by driving it backwards like that.
The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.


text:
How to run background music while the code for a game is executed
I have some background music. If I put it at the top of the void loop(), it'll first play the music and then execute the game code afterwards.
How do I have the code run while the background music is playing?

Interleave the music and game code. Do not delay when playing music or in the game code. Alternatively use threads.

Use a couple of Finite State Machines to play both the music an the game together.

I would set time to minimal note lenght and set PWM to play next tone/pause from music array inside the iterrupt. It would be so fast, that the game probabelly would not notice, it is interrupted on the background each beat time (few per sec) for just couple of cycles (1/16.000.000 sec each)

It all depends on the architecture of your game. The first games probably interleaved their music and gameplay, as the comment above says. This is probably the level of complexity you are looking for, on an Arduino.
First you need to pick some "framerate" that the game advances with. You could, for example, play 4 frames of music for every video frame, or something like that. It also depends how you are playing music. If you are just playing notes with the analog out, this approach would work. Here is some pseudocode that updates the PWM output 4 times faster than the game code:
set n = 0
set quit = false

// main game loop
while !quit
    // set music output pwm here
    if n % 4 == 0
        // advance game here
    endif
    n++
endwhile

If you are playing music from something like an SD card, you are constrained by the bit rate of the music.
Also, here is an article on Arduino protothreading that might interest you. https://create.arduino.cc/projecthub/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37. My suggestion is to look at how the old game systems implemented their state machines.

Run the music through a time Interrupt.


text:
WS2812B strip stopped responding to control
I have a WS2812B LED strip (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.
It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.
I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.
I'm kind of lost as to what could be wrong here.

Does it work if you connect data line to another pin, changing sketch to match?  Is ground still connected?

I have tried multiple pins, and yes - have ensured power, data and ground connections are solid. Very unusual.

Do you have a way to detach a front segment of LEDs, ie, attach to data a little ways into the strip?  And what was the name or nature of the  “something more custom” ?

Can you check the voltage at the end of the strip? And can you look with an oscilloscope the data line after a couple of leds?

If I was the kind of person who has an oscilloscope I suspect I wouldn't have managed to destroy this strip. :)
Good troubleshooting info though.

I'm in the same situation, so what happened?

@AkınCanŞENOL: the most common error could be to have 2 separate power suppy (one for the Arduino or Arduino over USB and one for the strip) and not connect together the ground

Did you follow the Adafruit NeoPixels best practices guide?
You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.
I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.

Uh, no. I have never seen that page before. As noted, I got these from eBay and instructions were not something they came with. Good to know! I'll try bypassing the first LED and using the instructions listed and get back to this question when I determine if that was it...


text:
How can I know how far a button is pressed?
I want to make a system that can count coins. The problem that I know have is that I need a way to detect the size of the coin.
The idea that I have is a beam that becomes smaller if you a inject a coin. The size of the beam depends than on the size coin. See it as a button that you can press a little bit or very deep.
But how can I know far the button (beam) is pressed?

First of all, you should ask the question that needs to be asked. Now you are asking something else. Could you describe what it is about ? Perhaps with a drawing of the beam and the coins. Is a Coin Acceptor possible ? https://www.sparkfun.com/products/11719 Maybe a beam on one side and a number of light sensitive sensors in a single line on the other side.

You cannot, to all intents and purposes, know how far a normal button is pressed - they only signal on/off.  I think your analogy of beam===button is so flawed as to be useless.

Why don't you just weight the coins, yes putting muck on the coins, or fakes can defeat it, but so can damaged coins if you are measuring by size.

Following on from Mark's comment, I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.
The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.
An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.
What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is at least the same as that detector's distance from the base.

These optical detectors are then connected to a series of digital inputs, i.e. D5, D6, D7 and D8, and a series of if statements would enable your code to determine the size of the coin.
Assuming that the broken light beam results in a low, then the pseudo code would be something like this:
if D5 = low & D6 = high
 then coin is a cent
if D5 = low & D6 = low & D7 is high
 then coin is a nickle
if D5 = low & D6 = low & D7 = low & D8 = high
 then coin is a dime
if D5 = low & D6 = low & D7 = low & D8 = low
 then coin is a quarter

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the correct time, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

* I have just realised that this is exactly what Jot described in his comment.


text:
Lag in fetching serial data from Arduino
I am working on a project based on Arduino and python3.6,two HC-SR04 sense the distance of palms and process the data using Arduino and send it through serial port to python3.6 ,python3.6 with the help of pyserial ,pyautogui based on data from arduino controls a game named supertuxcart,a racing game,basically the thought behind this is  controlling game with palms instead of keyboard or mouse .But the problem am facing is Arduino takes the distance measurement data from two HC-SR04(one for each hand) ultrasonic sensors, processes according and sends processed data through serial port to python3.6 ,there while running the my python script i open the game to check if its working ,it works, but there is lag in data received from arduino thus turn the game messy.
here is arduino code am using with NewPing library
#include <NewPing.h>
int trig1=9;
int echo1=6;
int trig2=7;
int echo2=5;
int R;
int L;
NewPing right(9,6,100);
NewPing left(7,5,100);
void setup() {

  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(6,INPUT);
  pinMode(5,INPUT);

}

void loop() {
  Serial.begin(9600);
  //Serial.println("hi,am arduino");
  R=right.ping_cm();
  L=left.ping_cm();
  //Serial.println(R);
  //Serial.println(L);
  delay(0000);
 if (R==0 && L==0){
    Serial.println('0');
  }
  else if(R<L&&L-R>5){
    Serial.println('1');
  }
  else if(R>L&&R-L>5){
    Serial.println('2');

delay(3000);

  }

}

Here is python3.6 code am using
import serial
import pyautogui
import time

Arduino = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(0)
print(Arduino.readline())
pyautogui.keyDown('up')
while 1:
    Data = Arduino.readline()
    print(Arduino.readline())

    if Data == b'0\r\n':
        pyautogui.keyUp('up')
        pyautogui.keyUp('right')
        pyautogui.keyUp('left')
        break
    elif Data == b'1\r\n':
        pyautogui.keyUp('left')
        pyautogui.keyDown('right')
    elif Data == b'2\r\n':
        pyautogui.keyUp('right')
        pyautogui.keyDown('left')

You could try using a higher baudrate, instead of just 9600.

Possible explanation for the lag. Since serial data is being buffered; if you send data faster, than the serial connection can handle, you'd get lag. As the latest data has to wait in line to be send. Using a tiny delay, or better Serial.flush(), or Majenko's #3 suggestion would eliminate the lag caused by buffering.

NewPing right(9,6,100);
NewPing left(7,5,100); Is the 100 the timeout for no return? Can you make that shorter?

its maximum distance ,100cm

Don't edit the question and invalidate an existing answer.

A couple of things jump out at me:

You only need to run Serial.begin(9600) once in setup() - never in loop() like that.
Your delay(3000) will be causing a 3 second delay when R>L&&R-L>5.
You don't need to constantly send the data over and over again. You just need to send it once and once only when the state changes.

At the moment you're sending something like:
0000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000002222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000

when all you really need to do is send 01020. Remember what the state is and only send anything when that state changes from one iteration to the next. And never ever use delay().

The code is using Serial.println, so it's more like 0\r\n0\r\n1\r\n1\r\n. So three bytes, for every byte of actual data.

Yeah, but still it's overkill.  And I didn't want to make my post 6 miles long to illustrate a point...


text:
Fading red to white to blue continuous loop on ws2812 LED strip
I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.
I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.
I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.
Can someone point me in the right direction?
#include "FastLED.h"
#define NUM_LEDS 30
#define DATA_PIN D4
#define COLOUR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {

    FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

    //start from red
    for( int colorStep=0; colorStep <= 255; colorStep++ ) {

        int r = 255;
        int g = 0;
        int b = colorStep;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }

    //into blue
    for( int colorStep=255; colorStep >= 0; colorStep-- ) {

        int r = colorStep;
        int g = 0;
        int b = 255;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }
}

If you correct your spelling and add some punctuation, to make it easier to read, you may get an answer.

Also, post what code you have.

Have you managed to make it turn white on its own, no fading.

Here is a sketch i got and im unsure how to add the white although i can get it to white on its own using a sketch i found using rgb code.

not sure how to import sketch to this as im new but i edited my question sorry abut the font change

https://arduino.stackexchange.com/editing-help

Also check a FastLED example.

Thank you for your help i should be able to sort it now gre_gor much apreciated

Think of a color as a point in 3d as defined by its r g b attributes
Think of two points here, one is your starting color in that 3d space, and another your ending color.
Figure out the path you want to take from the starting color to the ending cokor.
Chop it up in a few steps and use your code to walk the path.
Done


text:
maximum interrupt-based PWM frequency at 500 Hz
I need to control a 24 kHz ultrasonic transducer and decided to use an arduino uno I have lying around.
Using tone() or the atmega's hardware pwm is not very suitable because I need two 50/50 square waves with a phase difference of pi (which is equal to two XOR'ed pins) to switch the output polarity of the h-bridge synchronously. As the uC dosen't have anything else to do I wrote the following sketch where I just wait for an interrupt and toggle pins 2&3:
bool do_task=false;
void timer_init () {
  TCCR0A |= (1 << WGM01);
  OCR0A = 83;
  TIMSK0 |= (1 << OCIE0A);
  TCCR0B |= (1 << CS01);
}
ISR (TIMER0_COMPA_vect) {
  do_task=true;
}

bool state=false;
void toggle() {
  state=!state;
  digitalWrite(2,state);
  digitalWrite(3,!state);

}

void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  timer_init();
}

void loop() {
  if(do_task) {
    do_task=false;
    toggle();
  }
}

I expected the output to have a frequency of ~24 kHz, but it is 500 Hz instead.
From my understanding:

16 MHz CPU frequency
timer0 prescaler is 8 (TCCR0B |= (1 << CS01))
output compare value (OCR0A) is 83

would result in a frequency of 16 MHz / 8 / 83 = 24096,4 kHz -but as I mentioned- it's 500 Hz and doesn't seem to depend on the prescaler.

Thw calls to digitalWrite() are taking to long. It`s a rather big function. Use direct portmanipulation

you should delete the previous timer settings. Arduino core initializes the timers for PWM and you do |=

Why don't you do the toggling in the ISR? The time it takes the loop function to find the flag has changed won't be trivial.

@chrisl in the end I decided not to use the arduino core, things behave so weired... what exactly is it that makes a simple function like digitalWrite() so damn slow??! Why isn't it just a wrapper function for direct port manipulation?

@NickGammon I started to reduce the code and it just remained there. How much cycles does such a boolean comparison actually take? Initially, I planned to read the frequency from a potentiometer after each interrupt, wouldn't this be easily possible in 8×83=664 cycles?

@Juraj right! I now decided not to use the arduino core...

what exactly is it that makes a simple function like digitalWrite() so damn slow??! Why isn't it just a wrapper function for direct port manipulation?

Well, it can take a variable as an argument. And the contents of the variable have to be looked up in a table to see which port and which bit.
If you use the DigitalWriteFast library then that turns your writes into direct port manipulation providing you use constants.
So you can use:
digitalWriteFast(2,HIGH);  // or LOW

But not:
digitalWriteFast(myPort,someState);  // assuming they are not constants

In fact you can send variables, but it degrades into the same slow calls that digitalWrite uses.

I now decided not to use the arduino core

The core is absolutely fine. However you need to understand what it is doing. To be nice to newbies things like digitalWrite can take variables as arguments, so this sort of thing is possible:
for (int i = 0; i < 13; i++)
  digitalWrite (i, HIGH);

As I hinted in a comment, you could do it all in the ISR:
ISR (TIMER0_COMPA_vect) {
  static bool state;
  if (state)
    {
    digitalWriteFast(2,HIGH);
    digitalWriteFast(3,LOW);
    state = false;
    }
  else
    {
    digitalWriteFast(2,LOW);
    digitalWriteFast(3,HIGH);
    state = true;
    }
}  // end of TIMER0_COMPA_vect

Initially, I planned to read the frequency from a potentiometer after each interrupt, wouldn't this be easily possible in 8×83=664 cycles?

Analog reads (reads from the ADC) take around 104µs using the default ADC prescaler. That is, 1664 clock cycles. So, no, you can't read in that time. That is a hardware limitation. You can reduce the prescaler without losing much accuracy.
See my page about the ADC. Making the prescaler 16 rather than 128 will significantly increase speed with minimal accuracy loss.
To do that on the Uno:
ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
ADCSRA |= bit (ADPS2);                               //  16

I'm not that new to uC programming, I just tend to use programing registers directly rather than using the arduino environment. I thought this little program might be faster to implement  using the arduino core without having to look up things in the datasheet, but now I did so anyway. Concerning the adc: if it is in free-running mode, the hardware is doing the conversion in parallel. So if I only check the status bit for a completed conversion, this shouldn't be a problem and the actual time needed to handle the analog value would decrease a lot. Isn't that true?

I only need the analog value every 100ms and I'm not doing very much processing with it...

You wrote:

Using [...] the atmega's hardware pwm is not very suitable because I
  need two 50/50 square waves with a phase difference of pi

I believe hardware PWM is the best solution to your problem. The PWM
outputs can be set to either “inverting” or “non-inverting” mode.
Set the two channels of a single timer to the same duty cycle, with one
in non-inverting mode and the other one in inverting mode, and you have
your complementary outputs.
Example using Timer 1:
const float SIGNAL_FREQUENCY = 24e3;
const uint16_t HALF_PERIOD = round(F_CPU / SIGNAL_FREQUENCY / 2);
const uint16_t PERIOD = 2 * HALF_PERIOD;

int main()
{
    /* Set the PWM pins as outputs. */
    DDRB |= _BV(PB1);  // digital  9 = PB1 = OC1A
    DDRB |= _BV(PB2);  // digital 10 = PB2 = OC1B

    /* Configure Timer 1. */
    ICR1   = PERIOD   - 1;
    OCR1A  = PERIOD/2 - 1;
    OCR1B  = PERIOD/2 - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)  // ditto
           | _BV(WGM13)  // ditto
           | _BV(CS10);  // clock at F_CPU, start timer
}

Thanks for your answer! Yes, I know the inverting mode, but I will soon have to be able to also change the frequency in a little range. I'm now doing direct port manipulation and it works fine so far. But a question: what is this _BV() you are using?

@SimSon: _BV(n) is a macro for (1<<(n)), from avr-libc. I guess it stands for “byte value”. I like to use it when writing AVR-idiomatic code.