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:
DC motors only run in one direction
I'm quite new to Arduino and am making my first proper project, an obstacle avoiding robot.
I'm using an Arduino Uno and a motor shield compatible with the Adafruit motor driver library. I'm trying to run the example code from here: https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors, but with both motors running at once. This should run the motors forward for 1 sec, backward for 1 sec and then pause for 1 sec.
I'm getting inconsistent behaviour when I run the code. When I only connect 1 motor, it works fine. When the Arduino is connected to my laptop via USB, it works fine. However, when I use the 6V external power supply and both motors, they will only move in 1 direction and remain still during the second movement period. When I set them to move forward-backward-stationary, they only move forwards. When I set them to backward-forward-stationary, they only move backwards.
Any ideas what might be causing this / how I could fix it? Like I said, I'm pretty new to this so might be making a simple mistake.
Here's my setup:

I have 2 DC motors, one attached to port 1 and the other to port 4 on the motor shield. The power supply is 4 AA batteries (which I think is 6V?), which is also connected to the motor shield.
And here's my code:
#include <AFMotor.h>

AF_DCMotor leftMotor(1, MOTOR12_1KHZ);
AF_DCMotor rightMotor(4, MOTOR12_1KHZ);

void setup() {
  leftMotor.setSpeed(255);
  rightMotor.setSpeed(255);
}

void loop() {
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
  delay(1000);

  leftMotor.run(BACKWARD);
  rightMotor.run(BACKWARD);
  delay(1000);

  leftMotor.run(RELEASE);
  rightMotor.run(RELEASE);
  delay(1000);
}

Any help is much appreciated!

Possible hardware solution:
Consider using 2 battery packs.  One connected to the Arduino and the other connected to the motor drive board.  Remember to connect the grounds of the 2 battery packs together.
Possible software solution:
Software is often over looked when solving what appears to be a hardware issue.  Consider introducing a short pause between motor direction changes.  It may be that the power required to reverse the direction of a motor exceeds the capacity of the battery pack.  Likely it will take less power to first stop the motor, pause then start the motor in the opposite direction.

Your code looks pretty straightforward, and the fact that everything works properly with the laptop-USB connector makes me suspect that your problem lies with the battery pack.
When you said "When the Arduino is connected to my laptop via USB, it works fine.", did you mean that the 4-cell battery pack is still connected to the motor shield as shown, but the Arduino is being powered from the laptop via USB?
I suspect that what is going on is that during the transition from one direction to the other, the battery voltage temporarily drops below the Arduino's low-voltage cutoff point and everything stops, EXCEPT, when the Arduino is connected to the laptop via USB, the USB connection continues to power the Arduino through the dropout period and everything works.
Since you are starting to work with electronics and Arduino, you might want to consider getting a basic DVM (Digital Volt-AmpMeter) and a basic lab power supply. These two items would allow you to easily troubleshoot this problem.  A common desktop PC power supply with 5, 12 and (sometimes) 24V DC output makes a good bench power supply and are widely available and cheap.
Hope this helps,
Frank

4 AA batteries is 6 volts, which is the right amount of voltage for 2 DC motors. Like all the other answers on this page, the problem most likely has to do with your battery pack, although I am not sure how that would affect your motors. I can't really tell from the picture, but the problem would have to be with the wiring from your battery pack. If you have wires that go from the battery pack, to the motors, you should check to make sure that those are properly wired, as that would be a problem.
I hope this information helps, and the rest of your projects with Arduino go very smoothly!
-Simon

source: Stack Exchange

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

sort: votes


text:
Stepper Motor Code. Delay or Millis
i will be designing a robot with multiple stepper motor. is it advisable to use millis instead of delay here or not?
right now im testing if Millis() would work but still having a hard time programming this.

Depends on what you need to do. delay is a blocking call, while if you use millis you can do other things between checks for time. This may not be important if you are using a multi-core arduino or it may mean the difference between responsiveness and sluggishness.

This is a poor way to control stepper that requires acceleration, velocity limits and deacceleration to target position.  Get a CNC shield and FET driver bridge and do it right with GRBL Panel,software to Uno uC interface on USB

I use 10us step pulses using Arduino + CNC Shield + GRBL PANEL s/w over Windows via USB and get excellent servo speeds, home button (auto-cal) Jog buttons with tuned g,v, max constants and optimum step rates. Bit banging is so archaic.

Arduino function delay() which pauses the program for an amount of milliseconds specified as parameter.
millis(), on the other hand, is a function that returns the amount of milliseconds that have passed since program start.
Just like delay() has a microsecond-version called delayMicroseconds(), millis() has micros(). If you need better resolution, micros() may be the way to go.
However, be aware that micros() will overflow after approximately 70 minutes, compared to millis()‘s 50 days. This means that the functions’ return values will start all over from zero.

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


text:
MPU6050/DMP Intermittent bad data output?
I have a DFRobots MPU6050 module wired to SCL/SDA/Pin 2 on a Mega 2560 board, using Jeff Rowberg's I2CDev/MPU6050_6Axis_MotionApps libraries.  I have 2.2K pullups on the MPU6050 module, tied to +5V, as shown in the following photo.

I used a modified version of the code from Jeff's example to retrieve heading values from the MPU6050, as shown below

bool GetIMUHeadingDeg() //08/28/18 chg to bool return

{
//Purpose:  Encapsulate everything needed to acquire a yaw value
//Inputs:
//  global_yawval = float variable defined at global scope
//  fifocount = uint8_t variable defined at global scope
//  packetsize = uint8_t variable defined at global scope
//  mpuIntStatus = uint8_t variable defined at global scope
//  whilecount = long variable defined at global scope
//  resetcount = int variable defined at global scope
//Outputs:
//  global_yawval filled with latest yaw value from sensor
//  true = success, false = failure
//Notes:
//  08/13/18 now returns global_yawval to calling routine
//  08/28/18 chg return to bool so can return success/failure

// if programming failed, don't try to do anything
//if (!dmpReady) return;
//if (!dmpReady) false;

bool result = false; //added 01/16/19 to supress warnings

// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < DMPpacketSize)
{
    whilecount++;
    delay(10);
    delay(10);

    if (mpuInterrupt)
    {
        fifoCount = mpu.getFIFOCount();
        mySerial.printf("%ld\t%d\n", whilecount, fifoCount);
        whilecount = 0;
        break;
    }
}

// reset interrupt flag and get INT_STATUS byte
mpuIntStatus = mpu.getIntStatus();
mpuInterrupt = false;

// get current FIFO count
fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024)//0x10 is mask for MPU6050_INTERRUPT_FIFO_OFLOW_BIT
{
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
    result = false; //added 01/16/19 to supress warnings

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02)//0x02 is mask for MPU6050_INTERRUPT_DMP_INT_BIT
{
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < DMPpacketSize)
    {
        fifoCount = mpu.getFIFOCount();
        //mySerial.printf("fifo count = %d\n", fifoCount);
    }

    //07/08/18 added to watch for non-modulo FIFO counts
    if (fifoCount == 0 || fifoCount % DMPpacketSize != 0)
    {
        mpu.resetFIFO();
        FIFO_resetcount++;
    }
    else
    {
        //07/07/18 modified to read all outstanding packets
        // read a packet from FIFO
        while (fifoCount >= DMPpacketSize)
        {
            //mySerial.printf("fifo count = %d\n", fifoCount);
            mpu.getFIFOBytes(fifoBuffer, DMPpacketSize);
            fifoCount -= DMPpacketSize;
        }

        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        global_yawval = ypr[0] * 180 / M_PI;
        result = true; //added 01/16/19 to supress warnings
    }

    ////DEBUG!!
    //      mySerial.printf("yawdeg = %4.2f\n", global_yawval);
    //      mySerial.printf("time = %ld\tyawdeg = %6.2f\n", millis(), global_yawval);
    ////DEBUG!!
}

return result; //added 01/16/19 to surpress warnings

}
I have noticed occasional bad data points in the computed Heading values retrieved from the MPU6050, as shown in the attached plot. Any ideas what I can do about this?  Is bad value detection/removal an expected issue when dealing with IMU products like the MPU6050?

As an experiment, I excluded all points for which the rotation rate was unrealistically high, resulting in the 'Adj Hdg' line (gray line) in the plot below.  This (mostly) works, except for one instance where there were two bad values in a row.

TIA,
Frank

Looks like the major driver in the data 'noise' was the FIFO data rate, set via the MPU6050_DMP_FIFO_RATE_DIVISOR constant in MPU6050_6Axis_MotionApps20.h.  I changed the rate from 100Hz (0x01) to 20Hz (0x09) and got the following almost completely noiseless plot under the same conditions as before.  Note the vertical scale - only 6 deg total, and the one 'excursion' is only a 4 deg change. I also plotted the 3-point running average, which further reduces the excursion to less than 2 deg.
So, if you are looking for clean yaw (Heading) data from the MPU6050 DMP, consider changing the FIFO rate.
Frank


text:
Arduino Uno WiFi Rev2 "no socket available"
My Uno WiFi Rev2 outputs on the serial monitor after ~30 min "no socket available". Until that point everything works just fine, my requests run as expected. I use the .flush() and .stop() commands, as in several forums suggested. In the following my really messy code (sorry for that, but it's not optimized and only for testing some stuff):

#include <SPI.h>
#include <WiFiNINA.h>

//W-Lan Data
int status = WL_IDLE_STATUS;
char ssid[] = "**********";
char pass[] = "**********";

bool jsonBool;
char jsonChar;
int curlyBracket;
String jsonCode;
String json;

IPAddress HueBridge(10, 0, 0, 30);

WiFiClient WHTTP;

void setup() {
  while (status != WL_CONNECTED) {
    status = WiFi.begin(ssid, pass);
    delay(500);
  }
}

void loop() {
  jsonProcessing();
  httpRequest();

  bar1();

  delay(55);
}

void httpRequest() {
  WHTTP.flush();
  WHTTP.stop();
  if(WHTTP.connect(HueBridge, 80)) {
    WHTTP.println("GET /api/*************/lights/ HTTP/1.1");
    WHTTP.println("Host: 10.0.0.30");
    WHTTP.println("Connection: close");
    WHTTP.println();
  }
}

void jsonProcessing() {
  while(WHTTP.connected()) {
    if(WHTTP.available()) {
      curlyBracket = 7;
      while(WHTTP.available()) {
        jsonChar = WHTTP.read();
        if((jsonChar == '{') && (curlyBracket == 7)) {
          jsonBool = true;
          curlyBracket = 0;
        }
        if(jsonChar == '}') {
          jsonBool = false;
          jsonCode = jsonCode + '}';
          curlyBracket++;
        }
        if(jsonBool) {
          jsonCode = jsonCode + jsonChar;
        }
      }
    }
    WHTTP.flush();
    WHTTP.stop();
  }
  jsonBool = false;

  //processing jsonCode variable

  jsonCode = "";
}

void bar1() {
  //calculating stuff
}

If anything is unclear feel free to ask. This is not the whole code, just the WiFi relevant parts.
The main structure is copied from here https://www.arduino.cc/en/Tutorial/WiFiNINAWiFiWebClientRepeating
so it theoretically should work.
Thanks in advance.

do you have the newest version of the firmware and library?

@Juraj yes, I updated both yesterday but had no improvement.


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

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.

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.


text:
SPI: test by connecting MOSI to MISO
Is it possible to test a SPI connection by wiring the MISO directly to the MOSI pin?  I'm working on a low-level SPI implementation, and I want to check that the library is basically working.  It would be nice to be able to test the connection itself without additional hardware.

If you short MISO to MOSI, make sure there are no other devices connected to the bus.

Do you have an oscilloscope? This can be used to check whether SPI is working.

@EdgarBonet There are no other devices.

@MichaelT I don't unfortunately, might need to get one at some point.

For posterity, the reason my test wasn't working is because the MOSI pin was not set to output mode.

Yes, you can - and it's something I often do when doing low-level electrical testing an SPI interfacce.  For every clock that you send out the data presented on MOSI will get reflected on MISO.  So if you were to (using the Arduino SPI library) do:
uint8_t x = SPI.transfer(0x38);

then x should equal 0x38.
I find this especially useful on systems with remappable pins to confirm that the pins are configured correctly in the board configuration for proper SPI operation.

Great, thanks for confirming.  Based on reading the timing diagram it seemed like it should, but it's not for me.  Now I can know with more certainty that the problem must lie with my code, not with the concept.

Usually the SPI Master clocks data out while the Slave clocks data back in. So if you were sending and receiving 8 bits per transaction you can clock out 8 bits and at the same time clock in 8 bits for a total of 8 clocks.  This is described in this Wikipedia paragraph. That said, often the first 8 clocks are used to transmit a command and an additional 8 clocks are used to retrieve the result.
If you looped MOSI to MISO you would clock in what you clocked out. You would complete the entire transaction in 8 clocks. At a low level I'm thinking this does not matter. But at a higher level the software would have to be re-written to accommodate this weirdness.

Cool.  It won't matter for the higher level programming, I only care about running a very simple test to check that my library works (it currently doesn't, lol).

I find that what you say is a good approach.  That is, beyond the basics of sending / receiving bits of data, these simple serial interfaces such as SPI are often modified.  Some use 8 bit transactions.  Others use 12 or even 16 bits.  Some ignore the received data during transmission of a command.  Others clock in generic information unrelated to the command just to not let the bandwidth go to waste.


text:
ESP 01 lost its firmware when it disconnected

Hi I am using Arduino uno & ESP-01
ESP-01 is working well when I put firmware to ESP, for example, wifi spreading or AT command is okay.
but when I disconnect arduino from PC(disconnect USB connection)
ESP-01 suddenly do not work anything. no spread wifi, no AT command reaction..
so I always have to re-input the firmware to ESP again, for make it work again.
How can I make maintain ESP-01 's firmware?
picture is my connection status. thank you

You have io 0 puled LOW so the esp-01 firmware starts in flashing mode and the firmware starts immediately after flashing (no reset).
Remove io 0 to ground connection and add a pull-up for io 0 over a 10kOhm resistor if you want the esp-01 to start normally.
Note: powering the esp-01 from the 3.3 V pin of Uno (150mA max) could be insufficient for esp8266 WiFi operations at top transmit power (according to specs it can draw to 170 mA).


text:
Powering Arduino AND Relays
I have a 5V (5.3V) switching transformer that goes to a 7805 voltage regulator and powers Arduino, Arduino controls 4 relays using BJTs. those relays getting power directly from the same power source.
Arduino and it's modules + LCD uses ~40ma, each relay consumes 70ma. total current is around 350ma lets say 400ma.
The problem is 5V isn't enough to power Arduino, modules, sensors and relays. LCD gets very dim etc...
it works with 9V but 7805 gets really hot ~70 centigrade while having a heat sink on!
If i remove the 7805 and switching power burns or something bad happens then there's nothing in between to protect the Arduino!
What's the solution for this situation?

EDIT: for anyone who may have the same problem; I solved the problem with using a proper switching power salvaged from an old USB type-C charger and removed the 7805 voltage regulator, there's no heat anymore and it's working perfectly.

switching 5.3V to 5V seems not high enough. The regulator needs some headroom to convert the voltage.

@chrisl i know but i don't wanna remove the regulator for safety reasons, on the other hand increasing the voltage causes heat! what do i do!

Use a switching regulator and increase the incoming voltage.

@Majenko a LM2575T, thanks.

Personally I like to use pre-built modules from model aircraft stores (called a BEC, SBEC or UBEC depeding on who you talk to). Cheap and ready built.

@Majenko i already have a switching module, should i remove the 7805 and connect it directly to Arduino? it's a chinese one and i'm afraid something might happen to it and damage the arduino after some time... it's a 220 to 5V.

5.3V is within specification for the Arduino's 5V pin.

@Majenko my arduino is a standalone arduino and don't have the smd voltage regulator. are you sure it's safe?

The Absolute Maximum rating for Vcc on an ATMega328P is 6V.

You would have to check the datasheets for your other devices, but in general 5.3V is perfectly fine, since it's pretty much within the USB specification of 4.75V to 5.25V (just rounding will give you 5.3V).

Also, how have you determined that it is 5.3V?

@Majenko using a multi-meter, i connected the switching power LCD gets a little bit dim when all 4 relays are on but meh it's fine. but there's no protection for my arduino and modules now IF switching power burns out or idk something happens...

Did you have anything connected when you measured the voltage?

@Majenko no nothing, so after a few minutes the switching power gets a little bit hot too... is that normal?

With nothing attached you will be measuring the open circuit voltage. That will measure high. Measure the voltage with your circuit connected.

@Majenko it's 5V when connected to arduino and drops to 4.5 when all relays are on, i found a usb type C rapid charger which is 5V/3A can i use it for my project?

Yes, you can. What rating is your current 5V supply?

@Majenko i think it's 1A but it's a chinese one, i don't trust it wanna use the usb C charger module, check this out.

Linear regulators such as the 7805 operate by dissipating the additional voltage until their rated voltage remains.
This - as you noticed - requires a higher voltage  than the rated voltage.
Some variants, labeled as LDO for low drop-out, have reduced requirements for this, but normal 7805 usually require around 7 V to operate correctly.
The difference to the rated voltage is dissipated as heat as per P = U * I, with U being the voltage difference, and I the current pulled by your circuit.
You can use the switching power supply directly, or use a more advanced voltage regulator like the R-78E5.0 directly from 9 V, which has far lower losses.
Another option would be using the 5V from the switching transformer to drive the (less delicate) relays, and use the 7805 only for the MCU and display, but you would still want to use a heat sink in that case.


text:
Having problem in coding Arduino Uno
I'm making a timer program which takes the Time Duration as input from the user by two button switches (one for 'up' and one for 'down'), and after pressing an another button switch ('start'), the timer starts. During countdown, an LED glows, and after the end of the countdown, it turns off.
The elapsed time is displayed on a 7 seg. display, as a minute count.
#define segA 2
#define segB 3
#define segC 4
#define segD 5
#define segE 6
#define segF 7
#define segG 8
#define pinsig 0

const int buttonPinUp = 12;
const int buttonPinDown = 10;
const int buttonPinStart = 9;

int COUNT=0;
int buttonStateUp = 0;
int buttonStateDown = 0;
int buttonStateStart = 0;
int flag;

void setup()
{
    for (int i = 2; i < 9; i++)
    {
        pinMode(i, OUTPUT);
    }
    pinMode(pinsig, OUTPUT);
    pinMode(buttonPinUp, INPUT);
    pinMode(buttonPinDown, INPUT);
    pinMode(buttonPinStart, INPUT);
}

void loop()
{
    buttonStateUp = digitalRead(buttonPinUp);
    if (buttonStateUp == HIGH)
    {
        COUNT++;
        delay(200);
    }
    buttonStateDown = digitalRead(buttonPinDown);
    if (buttonStateDown == HIGH)
    {
        COUNT--;
        delay(200);
    }
    buttonStateStart = digitalRead(buttonPinStart);
    if (buttonStateStart == HIGH)
    {
        flag = HIGH;
    }

    if (flag == HIGH)
    {
        if (COUNT > 0)
        {
            digitalWrite(pinsig, HIGH);
            COUNT--;
            delay(2000);
        }
        if (COUNT == 0)
        {
            flag = LOW;
            digitalWrite(pinsig, LOW);
        }
    }

    switch (COUNT)
    {
        case 0:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 1:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, LOW);
            break;
        case 2:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, LOW);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 3:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 4:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 5:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 6:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 7:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 8:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 9:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
    }
}

But the program is not working as I expected.
I'm new in programming, so know a little basics. Can anyone help me in that ?

Have you tried to have a program to only light the LED for a hardcoded amount of time?

Yes. I've used 'delay' function to lit up an LED for a certain duration.

This will only run while you hold the start button, and will only update after each minute, but you won't see anything until you've held it down for a full minute.  Your program is full of oddly redundant statements.

You also need to describe exactly how the program is working...don't just say "not as I expected".

This code is messy with really bad indention. Are you sure you want a delay(60000)? You'll have to wait a minute before your code moves on. I think what you need to do here is create some type of state machine diagram. You're rushing the process of development of code and jump straight into writing a script. That's bad practice.

It is taking the 'Up' and 'Down' input. But, after pressing the 'Start ' button, after 1 minute the display counts just 1 minute. Nothing is happening after that.

see the BlinkWithoutDelay example in IDE Examples menu

what is the purpose of COUNT = COUNT;?

as chris mentioned it will only run when you hold the start button, you can define a boolean and when start button pressed change that to TRUE and IF that's true rest of your code will run, ELSE do something else... also change that 1 minute delay to 10 seconds for testing, you can increase it later on...

Thank you for the suggestions. I made some changes in my code. But, I didn't have the idea about defining a boolean, I used  an integer 'flag' (experimentally), which remains HIGH, even after releasing the Start button, until the countdown is completed. It served the purpose properly. Now the program is working as expected. Thank you for your help.

I re-indented your code in order to make it human-readable (we are humans here). In doing so, I noticed an extra closing brace. If your code doesn't compile, that's the reason. If it does compile, please, make sure that the code you post is the same as the one you are discussion in your question.

I properly didn't know the formatting code for uploading c++ programming code here. Thank you for editing that in a proper way, Mr. Edgar Bonet. Now it looks normal to me too. And yes, there was an unnecessary closing brace in the program. I deleted it from my program, after seeing the compilation error. I forgot to change it here. Sorry about that. But, the actual problem in the working of my project was for a different reason. I didn't use the 'flag' in the code (for keeping the switch case function running). Now, after using that 'flag', it is running properly.

To format your code, press Control-T in the IDE.  It handles all that infection for you and makes brave errors stick out like a sore thumb.


text:
NodeMCU keeps disconnecting
I have made a home automation system consisting of a NodeMCU, 4 channel relay board running on Blynk and IFTTT.
At the moment I'm only controlling a string of fairy lights and two LED strips from it, both connected to the relay of course.
The only code running on the NodeMCU is the Blynk ESP8266 Standalone code. Here it is (with the necessary changes of course) -

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
}

void loop()
{
  Blynk.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}

Now the thing is, the NodeMCU automatically disconnects from the WiFi randomly. Sometimes it reconnects immediately, sometimes it doesn't reconnect at all and I have to keep hitting the reset button to get it working again.
This is really annoying as everything I got connected to the NodeMCU also comes on all of a sudden and scares the hell out of me.
The code is all fine, the power supply is stable (5v 1A), all the cables are in place and the NodeMCU is tucked away in a corner where nobody touches it.
I can't seem to work out why is this happening.
Any fixes for this?

esp8266 core version? try 2.4.2 or 2.5.2. does it happen only on relay switching? is WiFi reception good at the location?

@Juraj The NodeMCU is literally like 10 cm from the router. And no, it happens randomly. There is no pattern or trigger whatsoever to the disconnection. Could you please elaborate on the ESP core thing?

@Juraj I've got 2.5.2.

I use Blynk almost 2 years now and yesterday it did suddenly disconnect for the first time. so it could be a temporary problem with Blynk cloud

@Juraj Nope. It has been happening to me. It happened in my previous project too

and did you try esp8266 package version 2.4.2?

in my projects with esp8266 I had problems only with servers on esp8266 (a known problem of SDK), but clients worked good

I had this same issue with an ESP8266 NodeMCU-12E using Cayenne in the past. It would drop connection for no apparent reason, but no matter what, most of the time it'd never reconnect until a reset. Here's what I did:
CAYENNE_DISCONNECTED(){
  Serial.println(F("Cayenne disconnected, rebooting..."));
  ESP.restart();
}

I've never used Blynk before, but after a quick look, this may do the same thing (untested):
if (! Blynk.connected){
  Serial.println(F("Blynk disconnected, rebooting..."));
  ESP.restart();
}

It effectively reboots the ESP unit if the connection to Blynk drops for any reason.

Just a side-note: In my case, my ESP was simply polling an Arduino Metro Mini over a serial connection (using a pair of Cat-5 Ethernet cable) inside of my water purification plant, then sending that data over wifi to my network inside my house. My point here is that I never had to worry about the pin state or anything after the reboot. More care may be needed if your ESP is in an important cycle doing sensor or other work, and not just relaying information or other basic/non-critical tasks

My ESP does automatically reboot after the connection drops. The problem is, whenever this, happens all the appliances connected to the ESP come on. Hence, I don't want it to drop connection at all


text:
What features of the Arduino framework will fail if I use my own infinite loop in favor of the standard loop()?
I have a strong urge to replace the framework-provided loop() function with my own like so:
__attribute__((always_inline)) inline void fastLoop()
{
}

void setup()
{
   // Performing setup here...
   Serial.begin(115200);

   // Now looping
   for(;;)
      fastLoop();
}

This way, my loop is inlined and I'm saving quite a few cycles - avoiding not only Arduino housekeeping costs, but also the function call cost which even for a void function has to be at least 6 cycles on AVR (>=2 for RCALL and 4 for RET).
This is the framework code for calling loop() from main():
for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

My question is: what does this serialEvent stuff do? What features of the framework will stop working properly with my own loop?
Assuming my loop has observable side effects as required by the C++ standard, of course (otherwise it can be optimized out).

It depends on which "Arduino" you are running it on.
On an Arduino Uno, for example, then the only thing that won't work is the SerialEvent system. Everything else that matters is interrupts.
Here is main() on the Arduino AVR core:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

As you can see, loop() is run just the same way as your fastLoop(), just not inline, and adding in a call to serialEventRun() if it has been defined.
If no serial event handlers have been defined, then it won't do anything there anyway.
To save clock cycles you would get more benefit (as long as you don't want to use millis(), delay(), serial communication, etc) from disabling interrupts.
However, on an ESP32 or ESP8266 you will find that your watchdog times out and resets the unit. This is because it relies on code being run regularly to manage the WiFi connection that keeps "kicking the dog". Without that being run (which can be called by calling the yield() function) the watchdog times out.

I don't see an edit on the question. but your answer looks like you didn't read it to end

@Juraj I had to go eat.


text:
Can I leave AVcc disconnected?
I am using ATmega8A standalone but analog pins (Port C) have not been use.
Due to ATmega8A does not have a PRR (Power Reduction Register) to disable ADC and TWI.
I would like to know, is it a work around solution to reduce the power consumption if AVcc is not connected?

You can disable the ADC on the ATMega8 the normal way. Though not the extra way that the PRR does. But I've found that the PRR doesn't do a whole lot. Disabling ADC, timers, and BOD and making the MCU sleep as much as possible is like 99%.

Unless the MCU allows you to apply power selectively (not the case of ATmega), failure to power some of the pins will result in some voltages applied in reverse internally, resulting in internal shorts.

No, the datasheet says power must be connected to Avcc. This is from the '328P, Atmega8A is similar but with less memory:
(Microchip is taking forever to open the Atmega8A datasheet for me).

5.2.7  AVCC
  AVCC is the supply voltage pin for the A/D Converter (ADC), PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter.

https://www.microchip.com/wwwproducts/en/ATmega8A

No. You must connect AVcc even if you're not using the ADC.  According to the datasheet:

AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that Port C (5:4) use digital supply voltage, VCC.


text:
Using SoftwareSerial.h in .cpp file
I am trying to modularize the different components in my arduino build by using objects, but am having trouble with the one controlling a wireless transceiver, which uses SoftwareSerial.h
I believe I am (generally) setting up the use of these objects correctly because I have other objects that build correctly in other files.
I think my issue is somehow part of SoftwareSerial.h, but I am not knowledgeable enough to get in and diagnose it... I think my core issue is that SoftwareSerial is not being brought in properly.
Transciever.cpp
/*
   This code controls the HC-12 transciever
*/
#include <Arduino.h>
#include <SoftwareSerial.h>

enum class TransReadStatus {
  RELAY_OFF,
  RELAY_ON,
  NO_DATA
};

class TranscieverHandler {
  public:
    TranscieverHandler(
      int txPinIn,
      int rxPinIn,
      int setPinIn,
      int baudRateIn
    ): txPin(txPinIn),
      rxPin(rxPinIn),
      setPin(setPinIn),
      baudRate(baudRateIn)
    {
      SoftwareSerial hc12(txPin, rxPin);
    }

    void init() {
      hc12.begin(baudRate);
      pinMode(setPin, OUTPUT);
      digitalWrite(setPin, HIGH);  // HC-12 normal, transparent mode
    }

    TransReadStatus checkForSignal() {
      while (hc12.available()) {             // If HC-12 has data
        incomingByte = hc12.read();          // Store each icoming byte from HC-12
        readBuffer += char(incomingByte);    // Add each byte to ReadBuffer string variable
      }
      delay(100);

      if (onBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_ON;
      } else if (offBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_OFF;
      }
      readBuffer = "";
      return TransReadStatus::NO_DATA;
    }

    TransReadStatus getLastRecievedStatus() {
      TransReadStatus newStatus = checkForSignal();

      if (newStatus == TransReadStatus::NO_DATA) {
        return lastStatus;
      }
      lastStatus = newStatus;
      return lastStatus;
    }

  protected:
    const int txPin;// = 10;
    const int rxPin;// = 11;
    const int setPin;// = 12;
    const int baudRate;// 9600
    /*
       Constants for signals
    */
    const String setOnBytes = String("SET RELAY ON");
    const String setOffBytes = String("SET RELAY OFF");
    const String onBytes = String("STATUS: RELAY IS ON");
    const String offBytes = String("STATUS: RELAY IS OFF");

    SoftwareSerial hc12;

    byte incomingByte;
    String readBuffer = "";
    TransReadStatus lastStatus = TransReadStatus::NO_DATA;
    unsigned long lastSendOnSignal = millis();

};

Output from failed compilation:
Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/greg/other/arduino-1.8.9/arduino-builder -dump-prefs -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
/home/greg/other/arduino-1.8.9/arduino-builder -compile -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
Using board 'uno' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Detecting libraries used...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Buttons.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/LEDs.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Switches.cpp
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.cpp -o /dev/null
Generating function prototypes...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
/home/greg/other/arduino-1.8.9/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
Using previously compiled file: /tmp/arduino_build_227628/sketch/Buttons.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/Switches.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /tmp/arduino_build_227628/sketch/Transciever.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/LEDs.cpp.o
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
Using library SoftwareSerial at version 1.0 in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial
exit status 1
no matching function for call to 'SoftwareSerial::SoftwareSerial()'

: hc12(txPin, rxPin),..

@Juraj I figured I was doing something simple wrong. If you make that an answer, I'll mark it as accepted

The member initialization is intended for objects construction. For ints you can do an assignment in the constructors body
TranscieverHandler(int txPinIn, int rxPinIn, int setPinIn, int baudRateIn)
    : hc12(txPin, rxPin) {
  txPin = txPinIn;
  rxPin = rxPinIn;
  setPin = setPinIn;
  baudRate = baudRateIn;
}

Good to know, it had been a while since I last touched real c++ code

https://www.learncpp.com/cpp-tutorial/8-5a-constructor-member-initializer-lists/


text:
Adafruit Feather M0 Basic Proto doesn't show up
I bought a Feather M0 basic from Amazon here. I installed all the board definitions and stuff from here I restarted the IDE and when I plugged it in, the Feather doesn't show up in ports or device manager. I am using a data cable that I verified. Debug is off and USB stack is Arduino.
I also tried following the instructions here but it didn't work.
When I double-clicked the reset button, the red LED didn't pulse.
Is there anything that am I missing?
Edit: Feather is supplying 3~ volts. USB is supplying 4.5~ volts.
Edit 2: Charing LED lights up when li-poly is plugged in.

it could be that you are missing the bootloader. I don't see SWD pins on this board. that would be the way to flash a bootloader. return it

there are swdio and swclk pads on the bottom of the feather.

ok. do you have a programmer or other SAMD board?

if it is possible to use an external programmer for the feather, i'll go for it.

it must support SWD

could i use an arduino uno as isp?

Let us continue this discussion in chat.

Why would you buy from that seller? The picture for the sale is for a mattress! What makes you think they have even the slightest clue what they are doing?

They changed the picture after I bought it


text:
How to code 4 relays to go off in intervals and not in sequence?
Code :
//FOR AEROPONIC SYSTEM WITH ROOM TEMPERATURE AND HUMIDITY SENSOR
//AND 4 GROW CHAMBERS WITH DIFFERENT SPRAYING TIME

// RELAY CONTROL
#define RELAY1_PIN 2
#define RELAY2_PIN 3
#define RELAY3_PIN 4
#define RELAY4_PIN 5

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 6
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//Variables
int chk;
float hum;
float temp;

void setup()
{
    Serial.begin(9600);
    Serial.println("SENSOR RUNNING");
    dht.begin();

    pinMode(RELAY1_PIN, OUTPUT);
    pinMode(RELAY2_PIN, OUTPUT);
    pinMode(RELAY3_PIN, OUTPUT);
    pinMode(RELAY4_PIN, OUTPUT);
}

void loop()
{
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t))
    {
        Serial.println("CONNECTION ERROR");
        return;
    }
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.println(" ");
    delay(2*1000);
    {
        // FOR RELAY
        digitalWrite(RELAY1_PIN, HIGH);
        delay(2*1000); // wait for 2 second ON
        digitalWrite(RELAY2_PIN, HIGH);
        delay(3*1000); // wait for 3 second ON
        digitalWrite(RELAY3_PIN, HIGH);
        delay(4*1000); // wait for 4 second ON
        digitalWrite(RELAY4_PIN, HIGH);
        delay(5*1000); // wait for 5 second ON

        digitalWrite(RELAY1_PIN, LOW);
        digitalWrite(RELAY2_PIN, LOW);
        digitalWrite(RELAY3_PIN, LOW);
        digitalWrite(RELAY4_PIN, LOW);
        delay(5*60*1000);
    }
}

This code doesn't do what I want. How do I make them independent?

Please post an actual question and not code. What do you want to actually achieve? I and many others will not bother to look at your code until we know what we need to answer. Clearly explaining your problem then asking a specific question will result likely in help.

Indent your code properly. As it is, there's no way it'll compile, and as you should be able to see, it's exceptionally difficult to follow the flow.

think about your title ... not in sequence requirement makes no sense ... what if in intervals happens to be in sequence ... do you want to prevent relay activation if that happens?

Although the question is far from clear, it looks like the answer may be for you to learn how to Blink Without Delay.

Here is some code that might help you; leaving out the temperature and humidity stuff:
// constants
// number or relays
const int relays = 4;

// pins for the relays
const int relayPins[] = {2, 3, 4, 5};

// relay cycle times
const unsigned long relayTimes[] = {
     5*60*1000, // 5 min
     60*60*1000, // 1 Hour
     2*60*60*1000, // 2 hours
     12*60*60*1000 // 12 hours
  };

// relay on durations
const unsigned long relayOntimes[] = {
    1000, // 1 second
    10*1000, // 10 seconds
    60*1000, // 1 minute
    60*60*1000 // 1 hour
  };

// timing for the relays
// storing the last time
unsigned long relayElapsed[] = {0, 0, 0, 0};

// state of each relay
int relaystate[] = {0, 0, 0, 0};

// helper function to process each relay
void relay_helper(unsigned long t, unsigned long &elapsed, int pin, int &state, unsigned long delta, unsigned long ontime)
{
  // depending on the state we do different things
  switch (state)
  {
  case 0: // state 0 is off, wait until time has passed
    if ((t-elapsed) > delta)
    {  // then
       state = 1; // set the state to on
       elapsed = t; // reset the time
       digitalWrite(pin, HIGH); // turn on
    }
    break;
  case 1: // state 1 is on, wait until time has passed
    if ((t-elapsed) > ontime)
    {  // then
       state = 0; // set the state to off
       elapsed = t; // reset the time
       digitalWrite(pin, LOW); // turn off
    }
    break;
  }
}

void setup()
{
  unsigned long start = millis();
  for(int i = 0; i < relays; i++) // for each pin
  {
    pinMode(relayPins[i], OUTPUT); // set it to output
    digitalWrite(relayPins[i], LOW); // and turn it off
    relayElapsed[i] = start;
  }
}

void loop()
{
  unsigned long tm = millis();
  for(int i = 0; i < relays; i++)
  {
    relay_helper(tm, relayElapsed[i], relayPins[i], relaystate[i], relayTimes[i], relayOnTimes[i]);
  }
  // do other loop stuff
}

The basic idea is that the only way to do thing simultaneously is to do things in sequence really fast, we can't use delay() because it is a busy loop, nothing else can happen during delay(), so we keep track of the time and when it is time to turn on the relay we turn it on, and when it is time to turn it off we turn if off.
Another option would be to write a class per relay:
class Relay
{
public:
  Relay(int pin, unsigned long delta, unsigned long ontime);
  ~Relay();

  process(unsigned long t);

private:
  unsigned long delta;
  unsigned long ontime;
  unsigned long last; // elapsed
  int pin;
};

Then one can create an array of these:
Relay[] relays = {
    Relay(2, 5*60000, 1000),
    Relay(3, 60*60000, 10000),
    Relay(4, 2*60*60000, 60000),
    Relay(5, 12*60*60000, 60*60000)
  };

put the code from setup into the constuctor, and the code from the helper into process, and finally call it in a loop in loop.
The first way shown is how one would do it without C++ classes, and the second way is with them!


text:
lcd.clear doesn't work with Serial.begin(9600) on Arduino Mega 2560
So I have a standard 16x2 LCD display with 16 pins. The LCD display works fine with every other aspect, however, the "lcd.clear" function doesn't work with "Serial.begin(ANY BAUD)". I have tried changing bauds and downgrading the board software but it still doesn't work.
Basically, instead of clearing the display like it should do, it displays a weird character with 4 horizontal lines (in one character space) and then continues to write stuff after it.
Here is my code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {
 pinMode(8, INPUT);
 lcd.begin(16,2);
 Serial.begin(9600);
}

void loop() {
 lcd.print("incorrect");
 delay(3000);
 lcd.clear();
 delay(100);
}

Whenever I delete the Serial.begin everything works fine, but when I add it the clear function doesn't work anymore.
So in this case, what happens is that the Arduino prints "incorrect", then instead of clearing the display, it prints out four horizontal lines, and then continues to print out "incorrect" infinitely.

You seem to use UART pins to connect your LCD.

Pins 0 and 1 are the hardware serial pins on the Mega.  If you're going to use Serial, then you can't connect your LCD to those pins or it won't work.  Even if you are only connected to Serial through the USB, pins 0 and 1 are still acting as Tx and Rx.

Right thank you so much!

Can you please mark the answer as accepted.

Buddy you are using those pins which are used for communication purpose that is pin No. 0 and 1 is for RXD and TXD


text:
Error "avr-g++: error: CreateProcess: No such file or directory" When Compiling Script
Whenever I try to compile a script, the Arduino IDE throws the error avr-g++: error: CreateProcess: No such file or directory. I've already tried reinstalling the IDE, changing the board version in the board manager to 1.6.21, and deleting the Arduino15 folder under AppData/Local/Arduino15.
This problem appeared suddenly - one compilation worked, and two minutes later, nothing would compile - and occurs across all scripts that I've tried.
I'm working from Windows 10 and compiling for an Arduino Uno.

Antivirus playing merry hell with your installation?

Just checked my activity log and that's exactly what's going on. Thank you!

Turns out that McAfee's Host Intrusion Prevention had decided to start blocking avr-g++.exe. Not sure why it did so all of a sudden, but it's an easy fix once you know where to look. Anyone finding this in the future should be sure to check their antivirus logs to see if the compiler's executable is being blocked.

I seem to be having this issue as well, but it's not clear to me what I should do about it. Do I disable McAfee and then reinstall? Do I set the executable as an exception? I've never modified anything in McAfee so I need more information for this easy fix. Much obliged!

Setting the executable sounds reasonable. This part is really more to do with McAfee. I would expect McAfee's documentation is sufficient to answer this, but if not https://superuser.com/ is probably the place to ask that sort of thing.


text:
LSM9DS1 breakout - How to increase speed
With regards to the Adafruit LSM9DS1 breakout:
enter link description here
And using the Library:
enter link description here
I am trying to increase the sample rate, or speed of this chip.
I am using a Sparkfun Pro Micro 5V
With the adafruit library, you need to request accelerometer, gyro, magnetometer and temperature at once, and all I need is the accelerometer values. I am hoping by figuring out how to request only the accel values it will speed up the loop. But also, there must be another setting that could speed up the sample rate?
Any help would be appreciated!
my code currently:

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LSM9DS1.h>
#include <Adafruit_Sensor.h>  // not used in this demo but required!
Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
#define LSM9DS1_SCK A5
#define LSM9DS1_MISO 12
#define LSM9DS1_MOSI A4
#define LSM9DS1_XGCS 6
#define LSM9DS1_MCS 5

void setupSensor()
{
  // 1.) Set the accelerometer range
  lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_2G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_4G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_8G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_16G);

  // 2.) Set the magnetometer sensitivity
  lsm.setupMag(lsm.LSM9DS1_MAGGAIN_4GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_8GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_12GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_16GAUSS);

  // 3.) Setup the gyroscope
  lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_245DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_500DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_2000DPS);
}

double accelX = 0;
double accelY = 0;
double accelZ = 0;
double rms = 0;

void setup()
{
  Serial.begin(115200);
  // Try to initialize and warn if we couldn't detect the chip
  if (!lsm.begin())
  {
    Serial.println("Oops ... unable to initialize the LSM9DS1. Check your
wiring!");
    while (1);
  }
  Serial.println("Found LSM9DS1 9DOF");
  setupSensor();
  delay(5000);//program stabilization
}

void loop()
{
  lsm.read();
  sensors_event_t a, m, g, temp;
  lsm.getEvent(&a, &m, &g, &temp);
  accelX = a.acceleration.x;
  accelY = a.acceleration.y;
  accelZ = a.acceleration.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}

Check the header of the library,
you will find readAccel readMag readGyro and readTemp in separate public functions and looking at the implementation of read it just calls those 4 in sequence. readAccel will update the accelData member field.
So you can just call lsm.readAccel() in the loop and then grab lsm.accelData directly and ignore the rest.
void loop()
{
  lsm.readAccel();
  accelX = lsm.accelData.x;
  accelY = lsm.accelData.y;
  accelZ = lsm.accelData.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}

Thanks! I'll try this out, hopefully it will speed up the sampling a bit

This worked, the sample rate is significantly faster now that I implemented the code above from @ratchet freak

@MattG having looked at the code in a bit more detail it looked like getEvent also did a read(). So your original code was doing a full read twice and only using the data for half the samples actually read.

that makes sense, it is significantly faster now that I implemented your suggestions. Thanks again.

Here is a link to the LSM9DS1 datasheet. In Chapter 3 it describes how to put the device in Accelerometer-only mode. At a quick scan of it, I believe there was timing information also, but at least knowing how to do it, you could then make your own timing measurements.

I see you can put the device into accel mode only, but unfortunately I don't understand how to actually implement the instructions. Is this something that would be changed in the library files?

In the Adafruit library's Adafruit_LSM9DS1.h at line 243 are a handful of functions to read individual sensors (Sensor& getAccel ( void ) { return _accelSensor; }, for instance). To get the timing benefit, you may need to put the device in accel-only mode, which, yes, will need some study of the library .cpp file to figure out how to do it or where to add the capability. I also see that there are some data-rate selections available. But that's about all I know of this device. Any more will need looking at the library code and the datasheet.

ok, thanks for the input and help on this @jrobert !