message:
Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3?

I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.

Writing to SoftwareSerial seems to be working but reading not.
As I write "AT", the module returns me "-5" which should be "OK".

As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial ss(rx, tx);

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

    void loop() {
      while (Serial.available()) ss.write(Serial.read());
      while (ss.available()) Serial.write(ss.read());
    }

body:
You may get better results if you do not nest the read and write function calls as you did.  That is, read everything then write everything.

The reason for this is that [softwareserial.read()][1] returns 1 character.  If you immediately turn around and pass that character to [softwareserial.write()][2] you will devote the resources of the processor to sending that character.  In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.

That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the [Mega 2560][3] processor on the [Arduino Mega][4].

Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater.  A hardware serial port or [UART][5] can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerialRead
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialWrite
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
  [4]: https://store.arduino.cc/usa/mega-2560-r3
  [5]: https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter


sender: user

sender: assistant

body:
With SoftwareSerial 9600 baud is about the maximum rate you can reliably run at when using a 5V 16MHz Arduino. You are using an 8MHz one at 3.3V, so you can expect that speed cap to be halved.

Don't use SoftwareSerial. Ever. Full stop. There is no call to ever use it. If you don't have enough real UART ports on your board then you are using the wrong board. Don't just use a board because it's the one that everyone uses. Look at what you want to do and then pick a suitable board that fits your needs. There are many many 3.3V boards available with multiple (or even one single spare) UARTs - for example the Fubarino Mini, the Teensy 3.x, Any number of ESP32 based boards - all with a similar footprint to the Pro Mini, and with a huge amount more power to boot.


message:
How to acheive fast and reliable communication between NodeMCUs?

I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have  tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.

Any ideas how could I can acheive speed of 10Hz via WiFi?

Thanks for any help.

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

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

client socket

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

server side

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


message:
Insane heat development with ESP8266

I have a ESP8266 on a Wemos D1 mini board. Simple "Rainbow with FastLED" animation. Shouldn't do much but the board gets so hot I can't touch it and it drains a 2500mAh battery in less than an hour.

Any idea what I'm doing wrong? Especially as a comparable micropython implementation just doesn't get that hot and the same battery keeps for about 5 hrs...

Here's the code
<!-- language-all: lang-cpp -->

    #define FASTLED_ALLOW_INTERRUPTS 0
    #include "FastLED.h"
    #include <EEPROM.h>

    // How many leds in your strip?
    #define NUM_LEDS 60
    #define DATA_PIN 13
    #define CLOCK_PIN 14
    #define COLOR_ORDER RGB
    int starthue = 0;
    int incrementer = 255/NUM_LEDS;
    CRGB leds[NUM_LEDS*2];
    int address = 0;
    int max_modes = 4;
    int colormode;

    void setup() {
      Serial.begin(9600);
      // put your setup code here, to run once:
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS*2);
        EEPROM.begin(512);
      colormode = EEPROM.read(address);
      Serial.println(colormode);
      int new_mode = (colormode == max_modes) ? 1 : ++colormode;
      Serial.println(new_mode);
      new_mode = (colormode == 0) ? 1: new_mode;
      Serial.println(new_mode);
      EEPROM.write(address, new_mode);
      EEPROM.commit();
      EEPROM.end();
    }

    void rainbow_mid(int howfast) {
      while (true) {
        fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
        for (int i =0; i< NUM_LEDS; i++) {
          leds[NUM_LEDS-i-1] = leds[i];
          leds[NUM_LEDS*2-i-1] = leds[i];
        }
        FastLED.show();
        delay(howfast);
        starthue++;
      }
    }

    void rainbow(int howfast) {
      while (true) {
        fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
        //addGlitter(80);
        for (int i =0; i< NUM_LEDS; i++) {
          //leds[NUM_LEDS-i-1] = leds[i];
          leds[NUM_LEDS*2-i-1] = leds[i];
        }
        FastLED.show();
        delay(howfast);
        starthue++;
      }

    }

    void loop() {
      switch(colormode) {
        case 1: rainbow_mid(10); break;
        case 2: rainbow_mid(50); break;
        case 3: rainbow(10); break;
        case 4: rainbow(50); break;
      }

    }

body:
the heat is from the supply lines of board.

it's not the chip itself, as if it gets hot like that the chip should be destroyed.
it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too.
so the heat is not from the chip. its from power supply tracks on the PCB.

use another power source for the LED strip.


message:
How to Specify Array Length during Object Construction within Arduino IDE?

I'm working on a group project to involving the creation of an in-house library using the Arduino IDE. As the Arduino IDE uses C++, the library must be a class. One of the classfields is an array of numbers. We would like it if we could specify the array length during object construction, as there are pros and cons to low and high array lengths. Is it possible to specify or change the array length during object construction?

Unfortunately, the Arduino IDE doesn't allow the usage of C++ vectors, so that's out of the question.

body:
Some example solutions can be found in [this stackexchange question/answer][1].  The accepted answer used this code:

    private int size;

    private String words[];

    public WordStore(int n){
         words =new String[n];
    }

  [1]: https://stackoverflow.com/questions/20425361/set-array-length-to-value-passed-to-constructor


body:
As suggested in [st2000’s
answer](https://arduino.stackexchange.com/a/66916/7508), you could use
dynamic allocation but, if you do that, do not forget to free the
allocated memory in the destructor. Otherwise you have a nasty memory
leak and your program will not live long:

```c++
class MyClass {
public:
    MyClass(size_t length) : arrayLength(length) {
        theArrayOfNumbers = new int[arrayLength];
    }
    ~MyClass() {
        delete[] theArrayOfNumbers;
    }
private:
    const size_t arrayLength;
    int *theArrayOfNumbers;
};
```

One issue with this approach is that dynamic allocation is no very
friendly to the limited amount of memory you have in a microcontroller.

A safer option would be to use a template class instead. This way the
array is statically allocated:

```c++
template <size_t arrayLength>
class MyTemplateClass {
    int theArrayOfNumbers[arrayLength];
};
```

One caveat with this approach is that the users of the library may not
be comfortable with the syntax for instantiating a template. You will
have to provide clear examples in the documentation. Another issue is
that the array size will have to be a compile-time constant.


body:
Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.

It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):

    int memArray[N];
    // ...
    myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.


message:
How to connect IRLZ44N to Arduino?

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

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

<!-- End schematic -->

In above schematic;

1. what value should R1 have? is it even needed?
2. do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

[IRLZ44N DATASHEET][1]

  [1]: https://www.infineon.com/dgdl/irlz44npbf.pdf?fileId=5546d462533600a40153567217c32725

body:
1. It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source

2. As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)


message:
From Strings to int problem

I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.

Arduino code:

    String br;

    void setup()
    {
      Serial.begin(9600);
      pinMode(9, OUTPUT);
    }

    void loop()
    {
       while (Serial.available()>0)
     {
        br = Serial.readString();
        analogWrite(9, br.toInt());
        Serial.println(br.toInt());
     }
    }

Qt code:

    void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
    {
       this->sendMessageToDevice(QString::number(position) + "n");
       qDebug() << "Grip: " << QString::number(position);
    }

    void MainWindow::sendMessageToDevice(QString message)
    {
       if(this->device->isOpen() && this->device->isWritable())
       {
           //this->addToLogs("Sending information to the device " + message);
           this->device->write(message.toStdString().c_str());
       }
       else
       {
           this->addToLogs("I can not send a message. The port is not open!");
       }
    }

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

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

body:
As Majenko wrote in his comment, your problem lies with `Serial.readString()`. It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. `String.toInt()` will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the `n`, that you send). It stops there and returns the already converted value.

This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.

Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.

The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character `n` is ok here. But mostly the newline character `\n` is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use `\n`.

As an example of this serial code, you can take the `readline()` function from [Majenko's blog post][1]:

    char buf[80];

    int readline(int readch, char *buffer, int len) {
        static int pos = 0;
        int rpos;

        if (readch > 0) {
            switch (readch) {
                case '\r': // Ignore CR
                    break;
                case '\n': // Return on new-line
                    rpos = pos;
                    pos = 0;  // Reset position index ready for next time
                    return rpos;
                default:
                    if (pos < len-1) {
                        buffer[pos++] = readch;
                        buffer[pos] = 0;
                    }
            }
        }
        return 0;
    }

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

    void loop() {
        if (readline(Serial.read(), buf, 80) > 0) {
            Serial.print("You entered: >");
            Serial.print(buf);
            Serial.println("<");
        }
    }

You can convert the character buffer to an int with `atoi()` in the if statement in `void loop()` and use it for ´analogWrite()`.

  [1]: https://majenko.co.uk/blog/reading-serial-arduino


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

[![Hardware Sketch][1]][1]

    #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

    }

  [1]: https://i.stack.imgur.com/bZgqU.jpg

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

 1. 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];'.
 2. 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.
 3. 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.
 4. 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


body:
Consider removing the type [String][1] 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][2]. 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.

  [1]: https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
  [2]: https://en.wikipedia.org/wiki/Memory_leak


message:
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:
[![4 AA batteries powering a motor shield, with 2 DC motors attached to motor ports 1 and 4.][1]][1]

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!

  [1]: https://i.stack.imgur.com/azvtE.jpg

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


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


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


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

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


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

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

I used a modified version of the code from Jeff's example to retrieve heading values from the MPU6050, as shown below
<!-- language-all: lang-cpp -->

    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?

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

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.

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

Frank

  [1]: https://i.stack.imgur.com/Ux9wG.jpg
  [2]: https://i.stack.imgur.com/3hZSW.jpg
  [3]: https://i.stack.imgur.com/VxcpP.jpg

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

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

  [1]: https://i.stack.imgur.com/6Wg8V.jpg


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

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


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


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

body:
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][1]. 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.

  [1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Data_transmission


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


message:
ESP 01 lost its firmware when it disconnected

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

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

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

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


message:
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.*

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


message:
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) -
<!-- language-all: lang-cpp -->

    #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?

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


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

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


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

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


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


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

```c++
/*
   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:**

```text
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()'
```

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


message:
How to code 4 relays to go off in intervals and not in sequence?

Code :

```c++
//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?

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


message:
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:
<!-- language-all: lang-cpp -->

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

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


body:
Buddy you are using those pins which are used for communication purpose that is pin No. 0 and 1 is for RXD and TXD  [![See the image you will observe what you are trying to do is wrong][1]][1]

  [1]: https://i.stack.imgur.com/LZcBB.jpg


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

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


message:
LSM9DS1 breakout - How to increase speed

With regards to the Adafruit LSM9DS1 breakout:
[enter link description here][1]

And using the Library:
[enter link description here][2]

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:
<!-- language-all: lang-cpp -->

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

  [1]: https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/overview
  [2]: https://github.com/adafruit/Adafruit_LSM9DS1

body:
Check the [header][1] of the library,

you will find `readAccel` `readMag` `readGyro` and `readTemp` in separate public functions and looking at the [implementation][2] 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.

  [1]: https://github.com/adafruit/Adafruit_LSM9DS1/blob/master/Adafruit_LSM9DS1.h
  [2]: https://github.com/adafruit/Adafruit_LSM9DS1/blob/master/Adafruit_LSM9DS1.cpp#L158

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


body:
Here is a link to the [LSM9DS1 datasheet][1]. 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.

  [1]: https://www.st.com/resource/en/datasheet/lsm9ds1.pdf


message:
LED Matrix Display with dissimilar brightness

So far I have seen in LED matrix related projects that the brightness is controlled in an entirety manner. That means the   brightness of total display can either be reduced or increased. How can we display only a part of the display with more brighter than the remaining matrix? Appreciate if anyone provide some pseudo logic to achieve this.

body:
Short answer: You likely can't, at a hardware level.

The only way you'd be able to do this is to vary the duty cycle of each individual LED in the matrix (the percent of on-time vs. off-time).

The device would have to support that. Edit your question with the model number of the LED matrix you're using and it's spec sheet.

(Note that if you're using a simple grid of LEDs and row/column addressing you could use PWM to get some control over brightness, but you'd probably already be using multiplexing of the LEDs, which makes varying brightness per LED more complex.)


body:
There's two options:

1. Use a matrix driver that supports different brightnesses per pixel, or:
2. Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.

The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.

You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.

For example if you first display a frame of:

    . . . . . . . .
    . . # # # # . .
    . # . . . . # .
    . # . . . . # .
    . # . . . . # .
    . # . . . . # .
    . . # # # # . .
    . . . . . . . .

followed by the image:

    . . . . . . . #
    . . # # # # # .
    . # . . . # # .
    . # . . # . # .
    . # . # . . # .
    . # # . . . # .
    . # # # # # . .
    # . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.

The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.


body:
LED brightness is normally controlled by how long a given LED is lit.  An LED that is on for 70ms and off for 30ms will be brighter then an LED that is on for only 30ms and off for 70ms.

So, the answer is to shorten the amount of time which the LED is on and lethen the time the LED is off for only those LEDs in your display which are to be dimmer.

This is usually referred to as the [duty cycle][1] of the LED.  On an Arduino, the [PWM or Pulse Width Modulator][2] feature of the embedded processor is normally used to create the duty cycle signal for an LED.

  [1]: https://en.wikipedia.org/wiki/Duty_cycle
  [2]: https://www.arduino.cc/en/tutorial/PWM


body:
Depends on what LEDs your matrix is made of. One option would be to make it from 'smart' LEDs at each location, such as WS2812B. These are a chip and 3 LEDs in one package, usually a 5050 size SMD package, but they can also be had in thru hole packages, and can be found built up into boards also (look at Sparkfun and Adfruit for examples). Serial data is sent in, with a 0-255 value for each LED, the control chip then drives the 3 LEDs with the PWM level commanded - 0/255 for off, 128/255 for 1/2 on for example, 255/255 for full on.  The data is passed from device to device to load them up, so for example an 8x8 matrix would need 8x8x3 = 192 bytes of data sent in to load the display. The Arduino then doesn't need to do any more until the matrix needs to change.  WS2812B needs some fancy timing to send in 0/1 data in a combined data/clock signal line, options are the Neopixel library or the FastLed.h library for Arduino, to send data in at up to 800 KHz rate. There is also another version of the chip that uses seperate clock and data lines, SPI.transfer I think can be used to send in data even faster.  I don't recall that device's part number off hand, I've not used it.

For premade 8x8 modules using single color LEDs, then as described in other answers  MAX7219 is often used, with 15 levels of brightness available for the whole display.