message:
Circuit diagram for running bipolar stepper motor using LDR

I am new to Arduino, some how I have put this code together to run stepper motor using LDR(kind of solar tracker program) I searched on net and tried using servo motor circuit to run stepper motor, assuming just replacing servo motor with stepper motor would work. I guess that is not the case (because servo motor is not moving according to LRD inputs). Please help me with circuit diagram.

Here is the code I am using

```

const int dirPin  = 5;
const int stepPin = 4;
const int enPin   = 6;
const int SensorPin1 = A0;
const int SensorPin2 = A1;
int sensorValue1 = 0;
int sensorValue2 = 0;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);

  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);
  Serial.begin(9600);

}
void loop() {
  sensorValue1 = analogRead(SensorPin1);
  Serial.println(sensorValue1);
  sensorValue2 = analogRead(SensorPin2);
  Serial.println(sensorValue2);

  if(sensorValue1 < 40 && sensorValue2 < 400){
    Serial.print("No sun Detected");
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
  }
  else if(sensorValue1 > 400){

    digitalWrite(dirPin,HIGH);
    digitalWrite(stepPin,HIGH);

 }
else if(sensorValue2 > 400){
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,HIGH);
}
}

```

**Hardware Used:**

 - Bipolar stepper motor- NEMA 23 20Kg torque
 - Stepper driver: TB6600
 - Power supply: SMPS 12V, 5amp
 - LDR: 2
 - Resistors: 2, 10K resistors
 - 1 Arduino Uno
 - Breadboard

[![Circuit Diagram][1]][1]

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

body:
If it helps, I tuned your code little.

    const int dirPin  = 8;
    const int stepPin = 7;
    const int enPin   = 13;//with pin 13 You can monitor on-board LED, if its lit, "enable" is HIGH and stepper will turn.
    const int rightSensorPin = A0;
    const int leftSensorPin = A1;
    int rightSensorRead = 0;
    int leftSensorRead = 0;
    int rightLightPct = 0;
    int leftLightPct = 0;
    int degreeChange = 1;

    void setup() {
      Serial.begin(9600);
      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
      pinMode(enPin,OUTPUT);
      pinMode(A0, INPUT_PULLUP);//no need extra resistors. Just connect one LDR leg to A0 and another GND.
      pinMode(A1, INPUT_PULLUP);
    }

    void loop() {
      rightSensorRead = analogRead(rightSensorPin);
      leftSensorRead = analogRead(leftSensorPin);
      rightLightPct = map(rightSensorRead, 0, 1023, 0, 100);
      leftLightPct = map(leftSensorRead, 0, 1023, 0, 100);
      degreeChange = map(abs(rightLightPct-leftLightPct),0,100,2,10);
      Serial.print("right = ");
      Serial.print(rightSensorRead);
      Serial.print(" left = ");
      Serial.print(leftSensorRead);
      Serial.print(" Pct r/l = ");
      Serial.print(rightLightPct);
      Serial.print("/");
      Serial.println(leftLightPct);
      if(rightLightPct < 15 && leftLightPct < 15){
        Serial.println("Sun is detected");
        digitalWrite(enPin, LOW);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(5000);//if somthing get in a way, program waits 5 sec. If nothing in that time, program will continue. That time may erase or add some more.
      }else if(rightLightPct > 50 && leftLightPct > 50){
        Serial.println("Sun is set!");
        digitalWrite(enPin, LOW);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
      }else if(rightLightPct > 20 && leftLightPct > 20){
        Serial.println("Seeking sun!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }else if(rightLightPct > leftLightPct){
        Serial.println("Turning CW!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,HIGH);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }else{
        Serial.println("Turning CCW!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }
    }


sender: user

message:
Wire with MCP23008 I/O expander with I2C

I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.

So I set it up for read as follows:

    #define MCP23008_DEVICE_I2C_ADDRESS 0x20
    #define MCP23008_SLAVE_I2C_ADDRESS  0x04

    #define MCP23008_REGISTER_IODIR     0x00
    #define MCP23008_REGISTER_GPIO      0x09

    #define IO_ALL_PINS_INPUT           0xFF

    inline void eeprog::_read_enable()
    {
        Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
        {
            Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
            Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
        }
        Wire.endTransmission();
    }

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:

    inline uint8_t eeprog::_read()
    {
        Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
        {
            Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
        }
        Wire.endTransmission();

        Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

        return Wire.read();
    }

Looking at my logic analyzer this is what I get:

[![I2C read from MCP23008][1]][1]

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?

Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?

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

sender: assistant

body:
Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.

The NACK at the end is not an error, it is a way to communicate between the Master and Slave.

When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.

Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.

The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.


message:
How to calibrate the MQ7 sensor module?

I recently bought a **MQ7 sensor module** like the one in the attached picture. I have read several tutorials, and they're all different. Some of them says that i need to **connect the module directly to 5v** and wait 24 hours to made it work properly, others says that i need to program **different periods (5v and 1.4v) and wait the same time to make correct meditions.** I read this [Datasheet][1], but i think that the information it has is not for the module.

If anyone knows how to setup this module i will aprecciate an answer (i want to read analog values).

Thanks in advance and sorry for my bad english.

[![Back View][2]][2]
[![Front View][3]][3]

  [1]: https://www.sparkfun.com/datasheets/Sensors/Biometric/MQ-7.pdf
  [2]: https://i.stack.imgur.com/gBWa3.jpg
  [3]: https://i.stack.imgur.com/T1lIy.jpg

body:
first of all, you need to understand how these sensors work.

 1. the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
 2. in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
 3. the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
 4. as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

 - you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
 - the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
 - the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC


message:
Can someone check my code? My Arduino isn't doing a consistent count cycle

I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.

The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.

The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.

The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.

It then repeats this sub cycle about 20 times.

After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.

It then does this whole complete cycle 20 times before stopping.

There's a momentary switch as well, which when pushed, is supposed to restart everything again.

It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.

I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.

Any ideas what I could try?

    int Relay_1 = 10;           //first Relay
    int Relay_2 = 11;           //second Relay
    int Prox_Input = 12;        //input signal from proximity sensor
    int Switch_Input = 13;      //the switch

    int Cycle_Number = 20;      //number of repeating number of "complete" cycle
    int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
    int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
    int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

    bool Button_Pushed = true ; //the state required for the button
    int i, j;

    void setup() {
      /*configurate the output relays to be begin "low"*/
      pinMode(Relay_1 , OUTPUT);
      digitalWrite(Relay_1, LOW);

      pinMode(Relay_2 , OUTPUT);
      digitalWrite(Relay_2 , LOW);
      /*===========================================================*/
      /*configurate the input switch and sensor*/
      pinMode(Prox_Input , INPUT);
      pinMode(Switch_Input , INPUT_PULLUP);
      /*===========================================================*/
      /*configurate Serial port if you want it*/
      Serial.begin(9600);
      /*===========================================================*/
    }

    void loop() {
      if (Check_Button() == Button_Pushed) { //check the button
        for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
          for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
            digitalWrite(Relay_1 , HIGH);
            delay(Delay_Sub_Cycle);
            digitalWrite(Relay_1 , LOW);
            while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
          }
          digitalWrite(Relay_2 , HIGH);
          delay(Delay_Sub_Cycle);
          digitalWrite(Relay_2 , LOW);
          delay(Delay_Cycle);
        }
      }
    }

    bool Check_Button()  {
      int Reading_1;
      int Reading_2;

      Reading_1 = digitalRead(Switch_Input);
      delay(20);
      Reading_2 = digitalRead(Switch_Input);
      if ((Reading_1 == 1) && (Reading_2 == 1))
        return true;
      else
        return false;
    }

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

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

body:
The only reason it might "jump the gun" would be this line:

>              while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal

I suggest you check for a *transition*, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.


message:
Why is IF statement executing on itself

x = 5;
    Serial.println (x);

    if (x == 0);
        {
          //stuff in this IF keeps happening why ?
          //Iam too stupid ?
        }

body:
You have a rogue semi-colon.

Splitting your code up on the end of statements you get:

    1. x = 5;
    2. Serial.println (x);
    3. if (x == 0);
    4. { // stuff }

With the semi-colon after the `if` it terminates the `if` before the opening block `{`, and that block becomes a completely separate statement detached from the `if`.


message:
Arduino WiFi Rev2 JSON String

I have been trying to use the WifiNINA library to access the JSON output from the [following API][1] using the WifiNINA library and the Arduino Wifi Rev2.

This is the code that I have been using (it is an **edited** example form the library):

    /*
      Web client

     This sketch connects to a website (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo)
     using the WiFi module.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     Circuit:
     * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

     created 13 July 2010
     by dlf (Metodo2 srl)
     modified 31 May 2012
     by Tom Igoe
     */

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

    #include "arduino_secrets.h"
    ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
    char ssid[] = SECRET_SSID;        // your network SSID (name)
    char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
    int keyIndex = 0;            // your network key Index number (needed only for WEP)

    int status = WL_IDLE_STATUS;
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.alphavantage.co";    // name address for Google (using DNS)

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    WiFiClient client;

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the WiFi module:
      if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < "1.0.0") {
        Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }
      Serial.println("Connected to wifi");
      printWifiStatus();

      Serial.println("\nStarting connection to server...");
      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.println("connected to server");
        // Make a HTTP request:
        client.println("GET /query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo HTTP/1.1");
        client.println("Host: https://www.alphavantage.co");
        client.println("Connection: close");
        client.println();
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting from server.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

    void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your board's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

However, when I run the library, all that the serial monitor returns is:

    Attempting to connect to SSID: HIDDEN
    Connected to wifi
    SSID: HIDDEN
    IP Address: HIDDEN
    signal strength (RSSI):-40 dBm

    Starting connection to server...
    connected to server
    HTTP/1.1 301 Moved Permanently
    Connection: close
    Server: gunicorn/19.7.0
    Date: Sun, 07 Apr 2019 15:02:16 GMT
    Transfer-Encoding: chunked
    Location: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700
    Content-Type: text/html; charset=utf-8
    Via: 1.1 vegur

    0

    disconnecting from server.

I would like the code to return the string from the link. The output should like this (instead of just the 0). I had to shorten the example output below because of size restraints, but it should be the full webpage.

    {
        "Meta Data": {
            "1. Information": "Intraday (5min) open, high, low, close prices and volume",
            "2. Symbol": "MSFT",
            "3. Last Refreshed": "2019-04-05 16:00:00",
            "4. Interval": "5min",
            "5. Output Size": "Compact",
            "6. Time Zone": "US/Eastern"
        },
        "Time Series (5min)": {
            "2019-04-05 16:00:00": {
                "1. open": "119.8100",
                "2. high": "119.9100",
                "3. low": "119.7350",
                "4. close": "119.8800",
                "5. volume": "728814"
            },
            "2019-04-05 15:55:00": {
                "1. open": "119.9200",
                "2. high": "119.9200",
                "3. low": "119.7800",
                "4. close": "119.8000",
                "5. volume": "307126"
            },
            "2019-04-05 15:50:00": {
                "1. open": "119.9300",
                "2. high": "119.9300",
                "3. low": "119.8800",
                "4. close": "119.9200",
                "5. volume": "235238"
            }
        }
    }

  [1]: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo

body:
The target site uses HTTPS. If you connect to port 80, it redirects to HTTPS on port 443.

Use the `WiFiSSLClient` of the library. See the WiFiSSLClient example. Basically it is same as the example you used. There are two differences. It uses `WiFiSSLClient` instead of `WiFiClient` and connects to standard https port 443.


body:
It's not that the API is incompatible with the Arduino, it's that the Arduino Firmware update tool used to add the required SSL certificate to the wifi module fails to do so because the SSL certificate for www.alphavantage.co does not exist at their domain.

This can be verified by:

openssl s_client -showcerts -connect www.alphavantage.co:443


message:
Error Downloading http://downloads.arduino.cc/packages/packages_index.json

I managed to update the library but getting error "Error Downloading http://downloads.arduino.cc/packages/packages_index.json" when updating the *Board Manager*. I switched the proxy to no proxy instead of automatic. Anyone can help me?

body:
The URL is wrong, and should read:

    https://downloads.arduino.cc/packages/package_index.json

Note that "package_index" is in the singular, not the plural.

Check what you have in the "Additional Boards Manager URLs:" section of Preferences.


body:
I had the same issue and the fix that worked for me is to directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter.

One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it):

    -Djavax.net.ssl.trustStore=NUL
    -Djavax.net.ssl.trustStoreType=Windows-ROOT

[I found this answer here][1]

  [1]: http://You can also try directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter. One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it): -Djavax.net.ssl.trustStore=NUL -Djavax.net.ssl.trustStoreType=Windows-ROOT


message:
Slow speed with stepping motor

I am currently working on a project where I need a stepping motor and a servo running at the same time, the servo turns fine and the speed is ok, but the stepping motors speed is very slow and as a result it is loud. I tried the code for the stepping motor on its own and it runs faster, but when it is ran with the servo it is slow. I have follwed a few tutorials to get this to the stage it is at currently, I have removed any delays that i could find which did help a little, but it is still not enough.

The servo is powered from the arduino and the stepping motor is powered by a 12v plug. I am just not sure if there is something within this code that is causing it to slow down? Thank you for you time! The code that it is running slow from is here:
<!-- language-all: lang-cpp -->

    #include <Servo.h>

    Servo myservo;

    // Configurable Variables
    int MaxServoTurn = 20;

    // Spooky Variables
    int pos = 0;
    int customDelay;
    int customDelayMapped;
    const int pin_LED = 10;
    const int pin_switch = 8;
    const int stepPin = 3;
    const int dirPin = 4;
    boolean oldSwitchState = LOW;
    boolean newSwitchState1 = LOW;
    boolean newSwitchState2 = LOW;
    boolean newSwitchState3 = LOW;
    unsigned long timeNow = 0;
    unsigned long timePrev = 0;
    unsigned int timeWait = 100;
    boolean flashingLEDisON = false;
    boolean LEDstatus = LOW;
    boolean keyPressed = false;
    boolean buttonToggle = false;

    // Setup only, call functions in here
    void setup() {
      myservo.attach(9);
      //Sets the two pins as Outputs
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
      //Enables the motor to move in a particular direction
      digitalWrite(dirPin, HIGH);
      pinMode(pin_LED, OUTPUT);
      digitalWrite(pin_LED, LOW);
      pinMode(pin_switch, INPUT);
    }

    // This is the main controller for the application
    void loop() {
      for (pos = 0; pos <= MaxServoTurn; pos += 1) {
        buttonLoop();
        if (buttonToggle == true) {
          myservo.write(pos);
          setupPotentiometer();
        }
      }
      for (pos = MaxServoTurn; pos >= 0; pos -= 1) {
        buttonLoop();
        if (buttonToggle == true) {
          myservo.write(pos);
          setupPotentiometer();
        }
      }
    }

    void buttonLoop() {
      newSwitchState1 = digitalRead(pin_switch);
      newSwitchState2 = digitalRead(pin_switch);

      newSwitchState3 = digitalRead(pin_switch);

      if (  (newSwitchState1 == newSwitchState2) && (newSwitchState1 == newSwitchState3) )
      {
        if ( newSwitchState1 != oldSwitchState )
        {
          if ( newSwitchState1 == HIGH ) {
            keyPressed = true;
            buttonToggle = true;
          } else {
            keyPressed =  false;
            buttonToggle = false;
          }
          oldSwitchState = newSwitchState1;
        }
      }

      if ( keyPressed )
      {
        // turn on or turn off the blinking LED
        if ( flashingLEDisON == false)
        {
          flashingLEDisON = true;
        }
        else
        {
          flashingLEDisON = false;
          // the LED may be on so to be safe we turn it off. If you wished you could check LEDstatus
          LEDstatus = LOW;  digitalWrite(pin_LED, LEDstatus);
        }
        keyPressed = false;
      }

      // if the blinking LED is on. See if it is time to blink it
      if ( flashingLEDisON == true )
      {
        timeNow = millis();
        if (timeNow - timePrev >= timeWait )
        {
          timePrev = timeNow;
          if (LEDstatus == LOW) {
            LEDstatus = HIGH;
          } else {
            LEDstatus = LOW;
          }
          digitalWrite(pin_LED, LEDstatus);
        }
      }
    }

    void setupPotentiometer() {
      customDelayMapped = speedUp(); // Gets custom delay values from the custom speedUp function
      // Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(customDelayMapped);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(customDelayMapped);
    }

    // Function for reading the Potentiometer
    int speedUp() {
      int customDelay = analogRead(A0); // Reads the potentiometer
      int newCustom = map(customDelay, 0, 1023, 300, 4000); // Convrests the read values of the potentiometer from 0 to 1023 into desireded delay values (300 to 4000)
      return newCustom;
    }

body:
A stepper motor requires that you send pulsed control signals to it for each step. If you want it to run at a given number of steps/second, you have to send the controlling pulses at the correct time intervals.

If you have delays in your code, it will slow down the timing of the control pulses, and slow down your steppers. You need to rewrite your code to use millis() to calculate the timing of your control signals instead of using `delay()` or `delayMicroseconds()`


body:
I had a project where I needed to run two steppers at the same time as they were moving a heavy load and were moving the same piece.

While a servo is going to move the desired spot, a stepper will not.

In the process of setting up the stepper you designated steps per rev and amount of steps to take at a time.

The stepper is only going to move the "amount of steps" at a time for each run of the code. I ran into a similar  problem and I had to put in a 2ms delay after the servo run command to make the motors run smoother and faster, other wise it sounded like a bunch of gears gnashing and skipping.  These steppers were facing each other that is why they move opposite directions.
<!-- language-all: lang-cpp -->

    if (down==true){
      TLstep.step(-step1);
      TRstep.step(step1);
      delay(2);
    }

I know it been a year since this was looked at. Hope you got your issue figured out.


message:
LED on same Pin as Toggle Switch, not illuminating

I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of **simulated byte**, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).

So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.

My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.

I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) *seemed* to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)

Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?

The breadboard looks like this:

[![BreadBoard Image][1]][1]

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

body:
LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.

You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.

So:

    Vout = (Vin - Vled) * (R2 / (R1 + R2))

         = (5 - 2) * (1000 / (200 + 1000))

         = 3 * (1000 / 1200)

         = 3 * 0.833

         = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.

You're between those two voltages - in the "dead zone".

The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.


body:
This is your circuit that does not work:

<!-- 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/k6vcW.png)

<!-- End schematic -->

There are many ways to use a single pin. Some circuits are with a diode and some circuits need to turn off the led to read the switch. The most simple solution might be this:

<!-- 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/QrCme.png)

<!-- End schematic -->

When the switch is not closed, the LED is a weak pullup (perhaps too weak). By using INPUT_PULLUP for D7, the pullup is stronger and D7 can read the switch.
As an extra it is possible to turn the LED on when the switch is open. But you have to be sure to switch between OUTPUT + LOW and INPUT_PULLUP in the code or else there is a shortcut.


message:
How to start serial monitor on Windows startup

How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

body:
You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.

Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.

For Windows 10 you can make a program run at startup by following [these](https://social.technet.microsoft.com/Forums/en-US/f0005629-0377-4e4b-82cc-26aff7b95884/how-do-you-add-new-startup-programs-in-wndows-10?forum=WinPreview2014General) instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.


message:
arduino LCD help

I am trying to create smart clock with alarm using an Arduino Uno.

My problem is when I set the alarm, I can't set the alarm again. Every time I must power off my Arduino and then power on in order to set the alarm again.

I am using:
Arduino Uno
LCD 16*2
buttons
buzzer and LED
RTC

My code works like this:
At the beginning it will let you to set date and time by buttons and you can set alarm too.
When it reaches the alarm time, it turns on the melody of buzzer and LEDs turn on.

but

I want to turn off the alarm so I can set another alarm.

This is my code:

<!-- language-all: lang-C++ -->

    #include "RTClib.h"
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int alarmState = 0;
    int alarmSnooze = 0;
    int btnSet = 0;
    int btnSel = 0;
    int alarmValue = 0;
    int alarmCounter = 0;
    boolean turnOffAlarm = false;
    boolean settingAlarm = false;
    int counter = 0;
    boolean initialCount = true;
    boolean alarmSet = false;
    int timeArray[6]; // 0=Hour, 1=Minutes, 2=day, 3=Day of Week, 4=Month, 5=Year;
    int timeCounter = 0;
    int alarmArray[2];
    char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    RTC_DS1307 rtc;    // Create a RealTimeClock object
    DateTime now; // Read data from the RTC Chip

    //////////////////////////
     ///difine button////
    int  b6=6;
    int b7=7;
    int b8=8;
    int b9=9;
    ////////////////////

    ///melody///
    #include "pitches.h"

    const int piezoPin = 13; //piezo
    const int rPin = A0;  //red LED
    const int gPin = A1;  //green LED
    const int bPin = A2;  //blue LED
    const int pPin = 6;  //pushbutton

    int ledState = 0;
    int ledOn = false;

    // notes
    int melody[] = {
      NOTE_F5,NOTE_D5,NOTE_AS4,NOTE_D5,NOTE_F5,NOTE_AS5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
      NOTE_F5,NOTE_F5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_AS5,NOTE_F5,NOTE_D5,NOTE_AS4,
      NOTE_D6,NOTE_D6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_F6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_DS6,
      0,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
      NOTE_F5,NOTE_AS5,NOTE_AS5,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_G5,NOTE_G5,NOTE_C6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_AS5,NOTE_A5,
      NOTE_F5,NOTE_F5,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_C6,NOTE_AS5
    };

    // durations: 2 = half note, and 8/3,4,6,8,12. It appears that 8/2.9 is more accurate than 8/3.
    float noteDurations[] = {
      6,12,4,4,4,2,6,12,4,4,4,2,
      8,8,8/2.9,8,4,2,8,8,4,4,4,4,4,
      6,12,4,4,4,2,8,8,4,4,4,2,
      8,8,8/2.9,8,4,2,8,8,4,4,4,2,
      4,4,4,8,8,4,4,4,4,8,8,8,8,4,4,
      8,8,8/2.9,8,8,8,2,8,8,4,4,4,2
    };

    // calculates the number of elements in the melody array.
    int musicLength=sizeof(melody)/sizeof('NOTE_F5');

    //////////////////////////

    void setup()
    {

      pinMode(pPin, INPUT);
      pinMode(rPin, OUTPUT);
      pinMode(gPin, OUTPUT);
      pinMode(bPin, OUTPUT);

      Serial.begin(9600);
      lcd.begin(16, 2);
      pinMode(10, OUTPUT);
      rtc.begin(); // Start the RTC library code
      rtc.adjust(DateTime(0, 0, 0, 0, 0, 0));
    }
    void loop()

    { alarmState = digitalRead(b9);
      alarmSnooze = digitalRead(b6);
      btnSet = digitalRead(b7);
      btnSel = digitalRead(b8);

      if (timeCounter == 0)
      {
        if(initialCount == true){
          counter=0;
          initialCount = false;
        }
        setHour();
      }
      else if (timeCounter == 1)
      {
        if(initialCount == true){
          counter=0;
          initialCount =false;
        }
        setMinute();
      }
      else if (timeCounter == 2)
      {
        if(initialCount == true){
          counter= 1;
          initialCount=false;
        }
        setDay();
      }
      else if (timeCounter == 3)
      {
        if(initialCount == true){
          counter = 0;
          initialCount =false;
        }
        setDOW();
      }
      else if (timeCounter == 4)
      {
        if(initialCount==true){
          counter=0;
          initialCount=false;
        }
        setMonth();
      }
      else if (timeCounter == 5)
      {
        if(initialCount==true){
          counter=0;
          initialCount=false;
        }
        setYear();
      }
      else if (timeCounter == 6)
      {
        rtc.adjust(DateTime(2000+timeArray[5], timeArray[4], timeArray[2], timeArray[0], timeArray[1], 0));
        timeCounter++;
        delay(200);
      }
      else if (timeCounter > 6){
        if(alarmState == LOW&&settingAlarm==false){
          now = rtc.now();
          digitalClockDisplay();
        }
        else if(alarmState == HIGH||settingAlarm==true)
        {
          settingAlarm = true;
          if(alarmValue==0){
            if(initialCount==true)
            {
              lcd.clear();
              alarmCounter=0;
              initialCount=false;
            }
            setAlarmHour();
          }
          else if(alarmValue==1){
            if(initialCount==true)
            {
              alarmCounter=0;
              initialCount=false;
            }
            setAlarmMinute();
          }
          else if(alarmValue>1){
            alarmSet = true;
            settingAlarm = false;
          }
        }
        if(alarmArray[0]==now.hour()&&alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==LOW){
           for (int thisNote = 0; thisNote < musicLength; thisNote++) {
          // blink the three LEDs in sequence
          if (thisNote%3==0){
            digitalWrite(rPin, HIGH);
            digitalWrite(gPin, LOW);
            digitalWrite(bPin, LOW);
          }
          else if (thisNote%3==1){
            digitalWrite(rPin, LOW);
            digitalWrite(gPin, HIGH);
            digitalWrite(bPin, LOW);
          }
          else if (thisNote%3==2){
            digitalWrite(rPin, LOW);
            digitalWrite(gPin, LOW);
            digitalWrite(bPin, HIGH);
          }

          // calculate the note duration. change tempo by changing 2000 to other values
          int noteDuration = 2000/noteDurations[thisNote];
          tone(piezoPin, melody[thisNote],noteDuration);

          // to distinguish the notes, set a minimum time between them.
          // the note's duration + 30% seems to work well
          float pauseBetweenNotes = noteDuration * 1.30;

          //split the delay into two parts and check to see
          //whether the pushbutton is pressed to turn off
          //the sound and light
          delay(pauseBetweenNotes/2);
          if(digitalRead(pPin)==HIGH) {
            break;
          }
          delay(pauseBetweenNotes/2);
          if(digitalRead(pPin)==HIGH) {
            break;
          }

        }
          digitalWrite(13, HIGH);

        }

        else if(alarmArray[0]==now.hour() && alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==HIGH){
          noTone(13);
          digitalWrite(13, LOW);
          digitalWrite(rPin, LOW);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, LOW);
          turnOffAlarm = true;
        }
      }
    }

    void nextValue(){
      btnSel=LOW;
      // Update array value with counter
      timeArray[timeCounter] = counter;
      counter=0;
      initialCount = true;
      timeCounter++;
      delay(200);
      lcd.clear();
    }
    void nextAlarmValue(){
      btnSel=LOW;
      // Update array value with counter
      alarmArray[alarmValue] = alarmCounter;
      alarmCounter=0;
      initialCount = true;
      alarmValue++;
      delay(200);
      lcd.clear();
    }

    void setAlarmHour(){
       if(alarmCounter==24){
        alarmCounter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set alarm hour");
      lcd.setCursor(7,1);
      lcd.print(alarmCounter);
      if (btnSet==HIGH)
      {
        alarmCounter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextAlarmValue();
     }
    }

    void setAlarmMinute(){
      if(alarmCounter==59){
      alarmCounter=0;
      lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set alarm minute");
      lcd.setCursor(7,1);
      lcd.print(alarmCounter);
      if (btnSet==HIGH)
      {
        alarmCounter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextAlarmValue();
     }
    }

    void setDOW(){
      if(counter==7){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set day of week");
      lcd.setCursor(7,1);
      lcd.print(days[counter]);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }
    void setHour()
    {
      if(counter==24){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set hour");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set minutes
    void setMinute()
    {
      if(counter==60){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set minute");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set date
    void setDay()
    {
      if(counter==32){
        counter=1;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set day");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set month
    void setMonth()
    {
      if(counter==12){
        counter=0;
        lcd.clear();
      }
      lcd.setCursor(0,0);
      lcd.print("Set month");
      lcd.setCursor(7,1);
      lcd.print(months[counter]);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    // Function to set year
    void setYear()
    {
      lcd.setCursor(0,0);
      lcd.print("Set year");
      lcd.setCursor(7,1);
      lcd.print(counter);
      if (btnSet==HIGH)
      {
        counter++;
        delay(200);
      }
     else if(btnSel==HIGH)
     {
      nextValue();
     }
    }

    void digitalClockDisplay(){
      // digital clock display of the time
      long hours;
      String amOrPm = "";
      if(now.hour() > 12){
        hours = now.hour() - 12;
        amOrPm = "PM";
      }
      else if(now.hour()==0){
        hours=12;
        amOrPm = "AM";
      }
      else{
        hours = now.hour();
        amOrPm = "AM";
      }
      lcd.setCursor(0,0);
      lcd.print(days[timeArray[3]]);
      lcd.print(" ");
      lcd.print(months[timeArray[4]]);
      lcd.print(" ");
      lcd.print(now.day());
      lcd.print(" ");
      lcd.print(now.year());
      lcd.setCursor(0,1);
      lcd.print(hours);
      printDigits(now.minute());
      printDigits(now.second());
      lcd.print(" ");
      lcd.print(amOrPm);
    }

    void printDigits(int digits){
      // utility function for digital clock display: prints preceding colon and leading 0
      lcd.print(":");
      if(digits < 10)
        lcd.print('0');
      lcd.print(digits);
    }

body: It looks like you haven't reset your state variable *turnOffAlarm* after you turn off the alarm.


body:
Since the question is tagged [code-review]

1.
        char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

 This should be a `const` array of `const char *`, not of `char *`.

        const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

 Same goes for `months`.

3.
        int  b6=6;
        ...
        const int piezoPin = 13;
        ...

 Why some of your pins are `const` and others are not? I don't see any attempts or reasons to change the value of `b6` in the code. Why is it not `const`?

4.

        int melody[] = { ... };
        float noteDurations[] = { ... };

   Both are supposed to be be `const`, apparently.

5.
        // calculates the number of elements in the melody array.
        int musicLength=sizeof(melody)/sizeof('NOTE_F5');

 Really? What is `'NOTE_F5'`? What did your compiler tell you about it? Did you just ignore the compiler's message?

 Should be

        const int musicLength = sizeof melody / sizeof *melody;

 I'd prefer `unsigned` or `size_t`, but let's not open this can of worms.

6. In a single-file sketch all global variables (i.e. the ones that really need to be global) should be declared either `const` or `static` (or placed in an anonymous namespace). Declaring a global variable that is not `const` or `static` requires a good reason for doing so.


message:
How do I redefine the overlfow of compare interrupts in Arduino programming?

If I'm programming a pin change interrupt I can call attachInterrupt at various points in my code and change what function is called when the interrupt occurs.

The overflow and compareA/B interrupt calls are defined by the ISR macro which is evaluated at compile time, which therefore can't be changed at run time. One solution would be to make that function consist of a single line, which invokes a function pointer. If I'm reading the code correctly, this is how attachInterrupt is implemented. Short of mucking with the interrupt vector table (which seems like a bad idea, or at least very hard to debug if you screw it up), is there another way to redefine the overflow or compare interrupt functions?

body:
What about using a `switch` statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?

    uint8_t status = 0;

    void myInterruptFn() {
      switch(status) {
        case 0:
          // do something
          status = 1;
          break;
        case 1:
           // do something else
           status = 0;
           break;
       }
    }


message:
Serial.available is working only for the first time

I am working on RFID. I am sending data through serial monitor and the Serial.available is not identifying the data after the first time, its working perfectly fine only once after reopening the comport.

I have tried all the possible changes I could do in the code. I want that when I run this code, then after entering the data in serial monitor it should show "Scan the mifare card" and after scanning the card it should perform read or write action.

    #include <SPI.h>//include the SPI bus library
    #include <MFRC522.h>//include the RFID reader library

    #define SS_PIN 10  //slave select pin
    #define RST_PIN 9 //reset pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
    MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will hold the card information

    void setup()
     {
            Serial.begin(9600);        // Initialize serial communications with the PC
            SPI.begin();               // Init SPI bus
            mfrc522.PCD_Init();
            //while (! Serial); // Wait untilSerial is ready - Leonardo
            //Serial.println("Enter data");
     }

    String incomingStr;
    byte blockcontent[16];
    int count=0;
    String arr2[6];
    int arr3[6];
    int u2=0;
    String arr[16];
    int arr1[16];
    int u=0;
    int y;
    char action;
    //int newc=0;

    void loop()
    {
     // Serial.println("bahar");
      if (Serial.available())
        {
          doReceive();
          int newc=0;
          while(newc==0)
           {
             if ( ! mfrc522.PICC_IsNewCardPresent())
                {
                   if(count==0)
                       {
                           Serial.println("Scan your mifare card %");
                           count++;
                       }
                }
            else
                {
                   newc=1;
                }
           }

         if ( ! mfrc522.PICC_ReadCardSerial())
           {
             return;
           }
         if(action=='%')
           {
             doWrite();
           }
         else if(action=='$')
           {
             doRead();
           }
         else if(action=='^')
           {
             for (byte i = 0; i < mfrc522.uid.size; ++i)
               { // read id (in parts)
                  Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
                  Serial.print(mfrc522.uid.uidByte[i], HEX);
               }
             Serial.print("*");
           }
      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
      Serial.flush();
       }
    }

    void doReceive()
    {
       incomingStr = Serial.readString();
       int sto=incomingStr.indexOf(')');
       action=incomingStr.charAt(sto+1);
       y=sto+2;
       for(int j=0;j<sto;j++)
        {
          if(incomingStr.charAt(j)!= ' ')
           {
             //Serial.print(incomingStr.charAt(j));
             //arr[u]=arr[u].concat(incomingStr.charAt(j));
             arr2[u2]+=incomingStr.charAt(j);
           }
         else
           {
             //Serial.println(arr[u]);
             u2++;
           }
        }
      for(u2=0;u2<6;u2++)
        {
          arr3[u2]=arr2[u2].toInt();
          key.keyByte[u2]=arr3[u2];
          //Serial.println(key.keyByte[u2]);
        }
     }
    void doWrite()
    {
      int block=1;
      for(int i=0;i<incomingStr.length();i=i+16)
      {
        if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
          {
            block=block+1;
          }
        for(int u=0;u<16;u++)
          {
            blockcontent[u]=0;
            //Serial.println(arr1[u]);
          }
        String s1=incomingStr.substring(y+i,y+16+i);
        s1.getBytes((char *) blockcontent, 30);
        writeBlock(block, blockcontent);
        block=block+1;
      }
      Serial.println("Data written successfully*");
    }
    void doRead()
    {
      int block=1;
      for(int i=0;i<4;i++)
        {
          if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
            {
              block=block+1;
            }
          byte readbackblock[18];
          readBlock(block, readbackblock);//read the block back
          //Serial.print("Block contains: ");
          for (int j=0 ; j<16 ; j++)//print the block contents
            {
               Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
            }

         //Serial.println();
         block=block+1;
        }
      Serial.println("*");
     }

body:
First of all try to add these debugging prints here to see if this while loop is becoming infinite:

      while(newc==0)
       {
         if ( ! mfrc522.PICC_IsNewCardPresent())
            {
               if(count==0)
                   {
                       Serial.println("Scan your mifare card %");
                       count++;
                       **Serial.println("test0")*
                   }

            }
        else
            {
               newc=1;
               **Serial.println ("newc=1")**
            }
       }


body:
`arr2` have size `6`. Have you made sure that here

    ...
    for(int j=0;j<sto;j++)
    {
      if(incomingStr.charAt(j)!= ' ')
       {
         arr2[u2]+=incomingStr.charAt(j);
       }
     else
       {
         u2++;
       }
    }
    ...

you are not writing beyond the bounds of that array?

Moreover, you never explicitly set the initial value of `u2` before starting this cycle - whatever was left in global variable `u2` from the previous uses will serve as the staring value for this cycle.

Judging by cursory examination of the rest of your code, only the very first call to `doReceive` will begin this cycle with `u2 == 0`. After that every time you call `doReceive`, you will start this cycle with `u2 == 6`, definitely overflowing the array and destroying the content of adjacent memory locations. The behavior is undefined.

I guess it is a "global variables strike again" kind of situation. Why on Earth is `u2` made a global variable???

It is quite possible that you can "fix" your code by simply adding `u2 = 0;` before the above cycle. But even after that the code will remain in a rather precarious state.


message:
Arduino Uno & ESP32 communication using RS485

I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.

After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.

 **Receiver**

    #include <SoftwareSerial.h>

    SoftwareSerial softwareSerial(9, 10);
    String str;

    void setup()
    {

   Serial.begin(9600);
   softwareSerial.begin(9600);

    }

    void loop()
    {

   while (softwareSerial.available() > 0) {

  char inChar = softwareSerial.read();

  if (inChar == '$') {

   str.trim();
   Serial.println("received command" + str);
   memset(&str, 0, sizeof(str));
   Serial.flush();
   softwareSerial.flush();
  }
  else {
   str = str + inChar;
  }

  }

    }

**Sender**

    #include <SoftwareSerial.h>

    SoftwareSerial swSer1(22, 23, false, 256);
    String str;

    void setup() {

   Serial.begin(9600);
   swSer1.begin(9600);

    }

    void loop() {

      String sendCmd = "MSG1$";
      Serial.println("Sending ");
      Serial.println(sendCmd );
      char copy[50];
      sendCmd.toCharArray(copy, 50);
      swSer1.write(sendCmd);
      delay(1000);

    }

Here my question is where i am going wrong in this project. Please guide me.

**Note :** DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.

body: Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.


body: I don't think you can use pins 9 and 10 they are connected to the internal mSPI flash, uart0 is connected to FTDI usb chip, use uart2 on 16 and 17.


message:
ESP12E Soft WDT reset stack trace leads to libraries

Im using **ESP12E DevKit v2** (esp8266 wifi module) board for controlling relays and displaying DHT22 temp,humidity on web server.
It runs smoothly when the web client is closed but when i leave the website on for like a 20mins it crashes.
I have installed the ESPdecoder and the stack trace always leads mostly to libraries. I tried using
  ***ESP.wdtDisable();
   ESP.wdtEnable(WDTO_8S);*** commands and ***yield();*** function but doesnt make any difference.

How can i fix this or what am i doing wrong in the code?

    Soft WDT reset

    >>>stack>>>

    ctx: sys
    sp: 3fffed40 end: 3fffffb0 offset: 01b0
    3fffeef0:  3ffe93dc c84524b8 60000600 4020ea06
    3fffef00:  00000000 3ffeda08 00000000 00000000
    3fffef10:  4022d488 3ffeda08 3ffee9c0 60000600
    3fffef20:  4022fdd1 3ffeda08 3ffee9c0 c84550ad
    3fffef30:  4022fe16 3fffdab0 00000000 3fffdcb0
    3fffef40:  3ffee9d0 3fffdab0 00000000 40206223
    3fffef50:  40000f49 40000f49 3fffdab0 40000f49
    3fffef60:  40000e19 40001878 00000002 00000000
    3fffef70:  3fffff10 aa55aa55 000000f0 40104ba0
    3fffef80:  40104ba6 00000002 00000000 3715d4f6
    3fffef90:  4010000d 0e060f10 942b6d57 69e0d507
    3fffefa0:  40100b40 3fffef3c 40100aed 3ffffea8
    3fffefb0:  3fffffc0 00000000 00000000 feefeffe
    3fffefc0:  feefeffe feefeffe feefeffe feefeffe
    3fffefd0:  feefeffe feefeffe feefeffe feefeffe
    3fffefe0:  feefeffe feefeffe feefeffe feefeffe
    3fffeff0:  feefeffe feefeffe feefeffe feefeffe
    3ffff000:  feefeffe feefeffe feefeffe feefeffe
    3ffff010:  feefeffe feefeffe feefeffe feefeffe
    3ffff020:  feefeffe feefeffe feefeffe feefeffe
    3ffff030:  feefeffe feefeffe feefeffe feefeffe
    3ffff040:  feefeffe feefeffe feefeffe feefeffe
    3ffff050:  feefeffe feefeffe feefeffe feefeffe
    3ffff060:  feefeffe feefeffe feefeffe feefeffe
    3ffff070:  feefeffe feefeffe feefeffe feefeffe
    3ffff080:  feefeffe feefeffe feefeffe feefeffe
    3ffff090:  feefeffe feefeffe feefeffe feefeffe
    3ffff0a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff100:  feefeffe feefeffe feefeffe feefeffe
    3ffff110:  feefeffe feefeffe feefeffe feefeffe
    3ffff120:  feefeffe feefeffe feefeffe feefeffe
    3ffff130:  feefeffe feefeffe feefeffe feefeffe
    3ffff140:  feefeffe feefeffe feefeffe feefeffe
    3ffff150:  feefeffe feefeffe feefeffe feefeffe
    3ffff160:  feefeffe feefeffe feefeffe feefeffe
    3ffff170:  feefeffe feefeffe feefeffe feefeffe
    3ffff180:  feefeffe feefeffe feefeffe feefeffe
    3ffff190:  feefeffe feefeffe feefeffe feefeffe
    3ffff1a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff200:  feefeffe feefeffe feefeffe feefeffe
    3ffff210:  feefeffe feefeffe feefeffe feefeffe
    3ffff220:  feefeffe feefeffe feefeffe feefeffe
    3ffff230:  feefeffe feefeffe feefeffe feefeffe
    3ffff240:  feefeffe feefeffe feefeffe feefeffe
    3ffff250:  feefeffe feefeffe feefeffe feefeffe
    3ffff260:  feefeffe feefeffe feefeffe feefeffe
    3ffff270:  feefeffe feefeffe feefeffe feefeffe
    3ffff280:  feefeffe feefeffe feefeffe feefeffe
    3ffff290:  feefeffe feefeffe feefeffe feefeffe
    3ffff2a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff300:  feefeffe feefeffe feefeffe feefeffe
    3ffff310:  feefeffe feefeffe feefeffe feefeffe
    3ffff320:  feefeffe feefeffe feefeffe feefeffe
    3ffff330:  feefeffe feefeffe feefeffe feefeffe
    3ffff340:  feefeffe feefeffe feefeffe feefeffe
    3ffff350:  feefeffe feefeffe feefeffe feefeffe
    3ffff360:  feefeffe feefeffe feefeffe feefeffe
    3ffff370:  feefeffe feefeffe feefeffe feefeffe
    3ffff380:  feefeffe feefeffe feefeffe feefeffe
    3ffff390:  feefeffe feefeffe feefeffe feefeffe
    3ffff3a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff400:  feefeffe feefeffe feefeffe feefeffe
    3ffff410:  feefeffe feefeffe feefeffe feefeffe
    3ffff420:  feefeffe feefeffe feefeffe feefeffe
    3ffff430:  feefeffe feefeffe feefeffe feefeffe
    3ffff440:  feefeffe feefeffe feefeffe feefeffe
    3ffff450:  feefeffe feefeffe feefeffe feefeffe
    3ffff460:  feefeffe feefeffe feefeffe feefeffe
    3ffff470:  feefeffe feefeffe feefeffe feefeffe
    3ffff480:  feefeffe feefeffe feefeffe feefeffe
    3ffff490:  feefeffe feefeffe feefeffe feefeffe
    3ffff4a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff500:  feefeffe feefeffe feefeffe feefeffe
    3ffff510:  feefeffe feefeffe feefeffe feefeffe
    3ffff520:  feefeffe feefeffe feefeffe feefeffe
    3ffff530:  feefeffe feefeffe feefeffe feefeffe
    3ffff540:  feefeffe feefeffe feefeffe feefeffe
    3ffff550:  feefeffe feefeffe feefeffe feefeffe
    3ffff560:  feefeffe feefeffe feefeffe feefeffe
    3ffff570:  feefeffe feefeffe feefeffe feefeffe
    3ffff580:  feefeffe feefeffe feefeffe feefeffe
    3ffff590:  feefeffe feefeffe feefeffe feefeffe
    3ffff5a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff600:  feefeffe feefeffe feefeffe feefeffe
    3ffff610:  feefeffe feefeffe feefeffe feefeffe
    3ffff620:  feefeffe feefeffe feefeffe feefeffe
    3ffff630:  feefeffe feefeffe feefeffe feefeffe
    3ffff640:  feefeffe feefeffe feefeffe feefeffe
    3ffff650:  feefeffe feefeffe feefeffe feefeffe
    3ffff660:  feefeffe feefeffe feefeffe feefeffe
    3ffff670:  feefeffe feefeffe feefeffe feefeffe
    3ffff680:  feefeffe feefeffe feefeffe feefeffe
    3ffff690:  feefeffe feefeffe feefeffe feefeffe
    3ffff6a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff700:  feefeffe feefeffe feefeffe feefeffe
    3ffff710:  feefeffe feefeffe feefeffe feefeffe
    3ffff720:  feefeffe feefeffe feefeffe feefeffe
    3ffff730:  feefeffe feefeffe feefeffe feefeffe
    3ffff740:  feefeffe feefeffe feefeffe feefeffe
    3ffff750:  feefeffe feefeffe feefeffe feefeffe
    3ffff760:  feefeffe feefeffe feefeffe feefeffe
    3ffff770:  feefeffe feefeffe feefeffe feefeffe
    3ffff780:  feefeffe feefeffe feefeffe feefeffe
    3ffff790:  feefeffe feefeffe feefeffe feefeffe
    3ffff7a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff800:  feefeffe feefeffe feefeffe feefeffe
    3ffff810:  feefeffe feefeffe feefeffe feefeffe
    3ffff820:  feefeffe feefeffe feefeffe feefeffe
    3ffff830:  feefeffe feefeffe feefeffe feefeffe
    3ffff840:  feefeffe feefeffe feefeffe feefeffe
    3ffff850:  feefeffe feefeffe feefeffe feefeffe
    3ffff860:  feefeffe feefeffe feefeffe feefeffe
    3ffff870:  feefeffe feefeffe feefeffe feefeffe
    3ffff880:  feefeffe feefeffe feefeffe feefeffe
    3ffff890:  feefeffe feefeffe feefeffe feefeffe
    3ffff8a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff900:  feefeffe feefeffe feefeffe feefeffe
    3ffff910:  feefeffe feefeffe feefeffe feefeffe
    3ffff920:  feefeffe feefeffe feefeffe feefeffe
    3ffff930:  feefeffe feefeffe feefeffe feefeffe
    3ffff940:  feefeffe feefeffe feefeffe feefeffe
    3ffff950:  feefeffe feefeffe feefeffe feefeffe
    3ffff960:  feefeffe feefeffe feefeffe feefeffe
    3ffff970:  feefeffe feefeffe feefeffe feefeffe
    3ffff980:  feefeffe feefeffe feefeffe feefeffe
    3ffff990:  feefeffe feefeffe feefeffe feefeffe
    3ffff9a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9f0:  feefeffe feefeffe feefeffe feefeffe
    3ffffa00:  feefeffe feefeffe feefeffe feefeffe
    3ffffa10:  feefeffe feefeffe feefeffe feefeffe
    3ffffa20:  feefeffe feefeffe feefeffe feefeffe
    3ffffa30:  feefeffe feefeffe feefeffe feefeffe
    3ffffa40:  feefeffe feefeffe feefeffe feefeffe
    3ffffa50:  feefeffe feefeffe feefeffe feefeffe
    3ffffa60:  feefeffe feefeffe feefeffe feefeffe
    3ffffa70:  00000000 00000000 0000001f 40105379
    3ffffa80:  4000050c feefeffe feefeffe feefeffe
    3ffffa90:  40222216 00000030 00000010 ffffffff
    3ffffaa0:  40218973 3fff0884 00000000 00000000
    3ffffab0:  00000a43 00000000 00000a43 3fff07b4
    3ffffac0:  00000a43 00000000 00000020 000000fd
    3ffffad0:  00000005 00000000 00000020 40101696
    3ffffae0:  3ffe96b5 40104a97 3ffed118 40101696
    3ffffaf0:  401023ad 3ffed118 3ffed118 40101696
    3ffffb00:  00000005 00000000 00000020 40101696
    3ffffb10:  3ffe96b5 40104a97 3ffed0f0 4010257e
    3ffffb20:  00000002 00000000 00000020 40101696
    3ffffb30:  3ffe96b2 40104a7c 3ffece48 4010257e
    3ffffb40:  00000001 40103c9f 3ffed878 00000001
    3ffffb50:  40104102 c047a314 401029be 00000100
    3ffffb60:  00000000 00000000 0000001f 40105379
    3ffffb70:  40103be6 00000023 7fffffff 00000002
    3ffffb80:  00000123 3ffed118 3ffe9801 00000008
    3ffffb90:  40102a5b 00080000 3ffedb88 4010257e
    3ffffba0:  00000000 00000000 00002200 4000050c
    3ffffbb0:  3fffc278 40102758 3fffc200 00000022
    3ffffbc0:  3ffffbd0 3ffe9f6c 3ffe9f6c 00000001
    3ffffbd0:  4021bddb 00000030 00000010 ffffffff
    3ffffbe0:  4021bddb 00000001 00000000 0000c005
    3ffffbf0:  0000024e 00000001 ffff7f72 0000888e
    3ffffc00:  000005e0 00000020 401038a1 3ffed830
    3ffffc10:  0000013a 00000000 3fff0c70 000000fd
    3ffffc20:  0000005a 00000001 401049e2 3ffed830
    3ffffc30:  00000000 00000000 00000020 40101696
    3ffffc40:  3ffe96b0 40104a7c 3fff034c 3ffed830
    3ffffc50:  00000001 40103c9f 3ffed830 40101696
    3ffffc60:  40104102 00040000 40229be3 00000001
    3ffffc70:  ffffffff 00000000 3ffe9801 00000008
    3ffffc80:  40229c32 3ffecdd0 3ffefa4c 00000001
    3ffffc90:  40229d3e 3ffecdd0 3ffefa4c 3ffecdd0
    3ffffca0:  00000002 00000000 00000020 40101696
    3ffffcb0:  3ffe96b2 40228cef 3ffecdd0 3fff0c54
    3ffffcc0:  00000000 4021bf97 3ffee2d8 40105379
    3ffffcd0:  00000000 00000002 00000000 3ffecdd0
    3ffffce0:  3fff1882 4010511f 3fff0c54 3fff01dc
    3ffffcf0:  3fff184c 0000002f 00000000 00000001
    3ffffd00:  00000004 4020e2d9 3ffef418 3fff01dc
    3ffffd10:  3fff1882 00000045 00000001 3ffeefc8
    3ffffd20:  3fffff20 3fffff20 0000000a 00000000
    3ffffd30:  3ffef83c 3ffef804 3fff184c 4020e55b
    3ffffd40:  00000002 3ffef804 3fff184c 4020e94c
    3ffffd50:  3ffef6a8 4bc6a7f0 94bc6a7f 00000001
    3ffffd60:  00000001 00000000 4bc6a7f0 3ffef6ac
    3ffffd70:  3ffef83c 00000003 3ffef804 40216024
    3ffffd80:  00000000 3ffee998 8d04d0fb 00000000
    3ffffd90:  00000002 3fff184c 3ffef294 00000000
    3ffffda0:  3ffee9c0 3ffef294 3ffe851c 3fff184c
    3ffffdb0:  00000001 4bc6a7f0 deb851eb 00000001
    3ffffdc0:  00000001 00000000 4bc6a7f0 00000000
    3ffffdd0:  3ffef2bc 000001d3 000001d3 40100664
    3ffffde0:  00000001 00000000 3fff0774 40100aa8
    3ffffdf0:  3b172b21 000001d3 3ffe851c 4020e175
    3ffffe00:  00000001 3ffffe8f 40206268 402036f7
    3ffffe10:  00000001 00000000 3fff0774 40203e3f
    3ffffe20:  00000002 3ffffeae 3fff0774 40203ec5
    3ffffe30:  00000001 4bc6a7f0 8083126e 3fffff40
    3ffffe40:  00000030 0000000a 3fffff40 402057ed
    3ffffe50:  3ffffe8f 000001d3 000001d3 40100664
    3ffffe60:  00000001 4bc6a7f0 3c6a7efa 00000001
    3ffffe70:  00000001 00000000 4bc6a7f0 00000000
    3ffffe80:  00000001 00000000 401001c0 00334411
    3ffffe90:  00000000 000001d3 000001d3 40100664
    3ffffea0:  3b46b3ee 00000000 3ffe851c 00000000
    3ffffeb0:  00000002 3ffe9259 40206268 3fffefa0
    3ffffec0:  00000002 00000000 3fff0774 40203e73
    3ffffed0:  0000000b 00000000 3fff0774 40203ec5
    3ffffee0:  3fffff40 3fe0004f 3fff0774 41cccccd
    3ffffef0:  423c999a 00000000 3fffff40 402057ed
    3fffff00:  3ffe9259 3ffef020 3fffff40 402057ed
    3fffff10:  3ffe8be4 3ffef020 3fffff40 40205818
    3fffff20:  423c999a 3ffef020 3fffff40 40205864
    3fffff30:  429a0000 3ffef020 3ffef03c 40202cc9
    3fffff40:  40206988 00000000 00001388 40206738
    3fffff50:  00000000 3fff0774 00000000 00000000
    3fffff60:  00000000 00000000 00000000 00000000
    3fffff70:  3fff0ccc 0000007f 00000000 feefeffe
    3fffff80:  429c28f6 00000000 42473333 feefeffe
    3fffff90:  00000000 00000000 00000001 3ffef238
    3fffffa0:  3fffdad0 00000000 3ffef208 40206314
    <<<stack<<<

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

**My code:**

    #include <ESP8266WiFi.h>
    #include <DHT.h>
    #include <NTPClient.h>
    #include <WiFiUdp.h>
    #define DHTTYPE DHT22

    const char* ssid = "ID";
    const char* password = "pass";
    const char* ssid2 = "ID2";
    const char* password2 = "pass2";

    // Define NTP Client to get time
    WiFiUDP ntpUDP;
    NTPClient timeClient(ntpUDP);

    WiFiServer server(80); // Set web server port number to 80
    String header; // Variable to store the HTTP request

    // Decode HTTP GET value
    String valueString = "0";
    int pos1 = 0;
    int pos2 = 0;

    // Variables to store the current output state
    int relay0State = 0;
    int relay1State = 0;
    int relay2State = 0;
    String brightness = "0";

    // Variables to save date and time
    String formattedDate;
    String dayStamp;
    String timeStamp;

    // Variables assigned to pins
    const int relay0 = 16;
    const int relay1 = 5;
    const int relay2 = 4;
    const int DHT1Pin = 0;
    const int DHT2Pin = 2;

    // Initialize DHT sensors
    DHT dht1(DHT1Pin, DHTTYPE);
    DHT dht2(DHT2Pin, DHTTYPE);

    void setup() {
      //Watchdog timer settings
      ESP.wdtDisable();
      ESP.wdtEnable(WDTO_8S);

      Serial.begin(115200);
      // Initialize the output variables as outputs
      pinMode(relay0, OUTPUT);
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      // Set outputs to LOW
      digitalWrite(relay0, LOW);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);

      dht1.begin();
      dht2.begin();

      // Connect to available Wi-Fi network with SSID and password
      Serial.print("Connecting to ");
      int n = WiFi.scanNetworks();
      if (n == 0)
        Serial.println("No networks found!");
      else {
        for(int i=0;i<n;i++) {
          if(WiFi.SSID(i)==ssid) {
            WiFi.begin(ssid,password);
            ssid = ssid;
          } else if (WiFi.SSID(i)== ssid2) {
            WiFi.begin(ssid2,password2);
            ssid = ssid2;
          }
        }
      }
      Serial.println(ssid);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      // Print local IP address and start web server
      Serial.println("");
      Serial.println("WiFi CONNECTED with IP: ");
      Serial.println(WiFi.localIP());
      server.begin();
      timeClient.begin(); // Initialize a NTPClient to get time
      timeClient.setTimeOffset(7200); // Setting offset time in seconds to adjust for current timezone -> GMT +1 = 3600
    }

    void loop(){
      ESP.wdtFeed(); //Feed the watchdog timer
      WiFiClient client = server.available();   // Listen for incoming clients

       while(!timeClient.update()) {
        timeClient.forceUpdate();
      }
      formattedDate = timeClient.getFormattedDate(); // The formattedDate comes with the following format 2018-05-28T16:00:13Z
      // Extract date
      int splitT = formattedDate.indexOf("T");
      dayStamp = formattedDate.substring(0, splitT);
      // Extract time
      timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);

      if (client) {
        String currentLine = "";               // String to hold incoming data from the client
        while (client.connected()) {           // loop while the client's connected
          if (client.available()) {            // if there's bytes to read from the client,
            char c = client.read();            // read a byte, then
            header += c;
            if (c == '\n') {                    // if the byte is a newline character
                                                // if the current line is blank, you got two newline characters in a row. That's the end of the client HTTP request, so send a response:
              if (currentLine.length() == 0) {
                // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                // and a content-type so the client knows what's coming, then a blank line:
                client.println("HTTP/1.1 200 OK");
                client.println("Content-type:text/html");
                client.println("Connection: close");
                client.println();

                // Read humidity
                float h1 = dht1.readHumidity();
                float h2 = dht2.readHumidity();
                // Read temperature as Celsius (the default)
                float t1 = dht1.readTemperature();
                float t2 = dht2.readTemperature();
                // Read temperature as Fahrenheit (isFahrenheit = true)
                float f1 = dht1.readTemperature(true);
                float f2 = dht2.readTemperature(true);

                // Calculating average temp and humidity from DHT22 sensors
                float temperature = (t1 + t2)/2;
                float temperaturef = (f1 + f2)/2;
                float humidity = (h1 + h2)/2;

                if(header.indexOf("GET /1/") | header.indexOf("GET /0/") < 0){
                    if(humidity < 50){
                    relay1State = 1;
                    digitalWrite(relay1, HIGH);
                  } else {
                    relay1State = 0;
                    digitalWrite(relay1, LOW);
                  }
                  if(temperature < 23) {
                    relay0State = 1;
                    digitalWrite(relay0, HIGH);
                  } else {
                    relay0State = 0;
                    digitalWrite(relay0, LOW);
                  }
                }

                if (header.indexOf("GET /0/on") >= 0) {
                  relay0State = 1;
                  digitalWrite(relay0, HIGH);
                } else if (header.indexOf("GET /0/off") >= 0) {
                  relay0State = 0;
                  digitalWrite(relay0, LOW);
                } else if (header.indexOf("GET /1/on") >= 0) {
                  relay1State = 1;
                  digitalWrite(relay1, HIGH);
                } else if (header.indexOf("GET /1/off") >= 0) {
                  relay1State = 0;
                  digitalWrite(relay1, LOW);
                }

                // Display the HTML web page
                client.println("<!DOCTYPE html><html>");
                client.println("<head><meta http-equiv=\"refresh\" content=\"1\" name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
                client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
                client.println("<style> html {font-family: Helvetica; display: inline-block; margin: 0px; text-align: center; height: auto; box-sizing: border-box;} h1, h2{width: 100%; color: #444444; font-size: 55px;} h2 {font-size: 30px;} h3, h4 {width: 50%; font-size: 24px; color: #444444; padding: 18px; margin: 10px; border-radius: 35px; margin: 4px auto;} h4 {padding: 5px;} .button {background-color: #4CAF50; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} .button2 {background-color: #555555;} .content {width: 100%; } .light {border-radius: 35px; width: 50%; margin: 4px auto;} .slider {-webkit-appearance: none; width: 30%; height: 10px; border-radius: 5px; margin-bottom: 20px; background: #d3d3d3; outline: none; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 20px; height: 20px; border-radius: 50%; background: #444444; cursor: pointer;} @media (max-width: 1000px) {h1{font-size: 40px;} h2{font-size: 25px;} h3,h4{width: 75%; font-size: 20px;} .light{ width: 75%;}}</style><title>Smart TERA</title> </head> ");
                client.println("<body><div class=\"header\"> <h1>Smart TERA</h1><h2>");
                client.println(timeStamp);
                client.println(" / " + dayStamp);
                client.println("</h2> </div> <div class=\"content\"><h3 style =\"background-color: #ff8000;\">Temperature: ");
                client.println(temperature);
                client.println("℃ /  ");
                client.println(temperaturef);
                client.println("℉ </h3><h3 style =\"background-color: #4da6ff;\">Humidity: ");
                client.println(humidity);
                client.println("%</h3><div class=\"light\" style=\"background-color: #ffff33;\"><h3>Light Brightness: <span id=\"lightPos\"></span> %</h3> <input class=\"slider\" type=\"range\" min=\"0\" max=\"100\" step=\"25\" value="+brightness+" id=\"myRange\">");
                client.println("<script> var slider = document.getElementById(\"myRange\"); var lightP = document.getElementById(\"lightPos\"); lightP.innerHTML = slider.value; $.ajaxSetup({timeout:1000}); slider.oninput = function() { slider.value = this.value; lightP.innerHTML = this.value; $.get(\"/?value=\" + this.value + \"&\"); {Connection: close};}</script> </div>");

                if(header.indexOf("GET /?value=")>=0) {
                    pos1 = header.indexOf('=');
                    pos2 = header.indexOf('&');
                    valueString = header.substring(pos1+1, pos2);
                    if(valueString == "0" ){
                      brightness = "0";
                      analogWrite(relay2, 0);
                    } else if (valueString == "25"){
                      brightness = "25";
                      analogWrite(relay2, 256);
                    } else if (valueString == "50"){
                      brightness = "50";
                      analogWrite(relay2, 512);
                    } else if (valueString == "75"){
                      brightness = "75";
                      analogWrite(relay2, 768);
                    } else if (valueString == "100"){
                      brightness = "100";
                      analogWrite(relay2, 1024);
                    }
               }
                // Display current state, and ON/OFF buttons for controlling relays, If the relay0State is off, it displays the ON button
                client.println("<h4>Rock Heater - State ");
                if (relay0State == 0) {
                  client.println("off</h4><p><a href=\"/0/on\"><button class=\"button\">ON</button></a></p>");
                } else {
                  client.println("on</h4><p><a href=\"/0/off\"><button class=\"button button2\">OFF</button></a></p>");
                }

                client.println("<h4>Humidifier - State ");
                if (relay1State == 0) {
                  client.println("off </h4><p><a href=\"/1/on\"><button class=\"button\">ON</button></a></p>");
                } else {
                  client.println("on </h4><p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
                }
                client.println("</div></body></html>");

                // The HTTP response ends with another blank line
                client.println();
                // Break out of the while loop
                yield();
                break;
              } else { // if you got a newline, then clear currentLine
                currentLine = "";
              }
            } else if (c != '\r') {  // if you got anything else but a carriage return character,
              currentLine += c;      // add it to the end of the currentLine
            }
          }
        }
        // Clear the header variable and close the connection
        header = "";
        client.stop();
       }
    }

**Decoded error:**
[![stacktrace][1]][1]

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

body:
First, take out the wdt.feed all that does is delay the real problem and/or shift it somewhere else. As a rule of thumb, if you even THINK you have to use / touch / play with / cancel the WDT, your code is already wrong. The root problem is your code is "blocking" longer than the underlying WiFI stack is happy with. A culprit is: while(!timeClient.update()) How long does that take? If it "blocks" then your code will fail. "Multiple" / "Parallel" tasks must run asynchronously and yield() to the backgound WiFi if they are long-running. If you mix old fashioned, blocking code with modern asynchronous code, THIS is exactly what you will get.

Other points: all that println stuff in the main loop is horribly inefficient and won't be helping. Setup the main body of text once and edit / resend the bits that change.

Also I believe DHT11 can sometimes take a while to settle / read. If the library you are using is not optimised for ESP8266 and / or non-blocking, there's another potential source of error. I believe DHT11 can also sometimes return NaN rather than a valid value - how do you cope with that?

There's an async webserver library that does all that side of things properly - you are reinventing a wheel and yours is square. You need to find an async NTP library too. "But I found it in the library examples!" Is NOT a guarantee / justification that the code is a) useful b) any good c) well-written d) functional for any other purpose. In my experience its usually the opposite of all four, especially if you mix two libraries together. It's an "example" - it's not production code.

Final takeaway:

1. Use the right library for the right job
2. NEVER mess with the WDT
3. NEVER mix sync + async code
4. Most example ESP8266 code assumes a single function, not needing to cooperate with any other. If you mix / blend separate examples / functions (e.g. DHT11 AND NTP AND WEBSERVER), YOU must provide the co-operation between functions + ESP8266 background WiFi. If you don't (and you haven't) you will cause a WDT reset, 100% guaranteed.


body:
i had look like this problem before.
for me , when i much used of " Serial.print " this RST fault occur for me..
so i use of a function:

    void Serial_Show() {
        Serial.println();
    }
maybe your problem is this.
you can test it by deleting all Serial.print() function and next add one by one...


message:
What is the difference between the two sensors?

I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.[![][1]][2]

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

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

body:
Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look.
They seems to both be [`FC-51` modules][1]: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them.
The potentiometer is there to determine the triggering level so that when powered you can have a `LOW` signal on the `OUT` pin when the threshold is reached.

  [1]: https://www.google.com/amp/s/surtrtech.com/2018/01/27/how-to-use-the-fc-51-infrared-proximity-obstacle-avoidance-sensor-with-arduino/amp/


message:
Ensure board is always on the same port?

I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

body: My experience is that the Serial-to-USB converters (of which Arduino is one) have are assigned a COM port according to the USB port they are plugged into. So if you always to connect it to the same physical USB port it will have the same number. However this number will not be the same with a different Arduino or on a different computer.


body:
*Normally*, the COM port number wont change, but you cannot simply rely on this.

Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.

Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.

And, btw. it's not related to VB.net


message:
Not able to control DC motor speed with l298N & pwm pins

I am using arduino uno to control dc motor speed with L298N. But the problem is that the motor is only going at max speed. PWM pin doesn't work for some reason.
I heard many people had some problem but haven't found the solution yet.

code:-

    #include <L298N.h>

    #define ENA 9
    #define IN1 8
    #define IN2 7

    L298N motor(ENA, IN1, IN2);

    void setup() {
    // Setup pin mode

    //used for display information
      Serial.begin(9600);

    }

    void loop() {
    //Drive Motor Forward
      motor.setSpeed(10);
      motor.forward();
      delay(500);
      motor.setSpeed(100);
      motor.forward();
      delay(500);
      motor.setSpeed(255);
      motor.forward();
      delay(500);

    }

I only see the motor move at full speed every time. I connected 5V of Arduino to +12V pin of motor driver and Arduino is powered with my laptop USB.

I am using 4.5V toy dc motor for test - [DC motor][1]

What could be wrong here?

  [1]: https://uae.souq.com/ae-en/dc-geared-motors-for-robots-straight-shaft-12139874/i/?a_source=google&a_medium=cpc&a_content=search_shopping&u_type=shopping&a_campaign=Shopping-Smart-UAE-EN-Global&referrer=re=1&a=amodi&ca=Google-Shopping-Smart-1018320391&an=Google Search&p=Android&pl=45586436090&cr=-&s=&gclid=CjwKCAjwhbHlBRAMEiwAoDA34xlPRdDs2_k7X-qV8erCRBm9ERJz3M0s-0CaZYC5dPhSB717S_m1DhoCvpUQAvD_BwE

body:
Try to use this code, without the library, and be sure to connect every pin to the correct Arduino output. If everything is okay it should work. Check the tutorial [here][1]

    int IN3 = 5;
    int IN4 = 4;
    int ENB = 3;
    void setup()
    {
     pinMode (ENB, OUTPUT);
     pinMode (IN3, OUTPUT);
     pinMode (IN4, OUTPUT);
    }
    void loop()
    {

      digitalWrite (IN3, HIGH);
      digitalWrite (IN4, LOW);
      analogWrite(ENB,55);
      delay(2000);
      analogWrite(ENB,105);
      delay(2000);
      analogWrite(ENB,255);
      delay(2000);
      analogWrite(ENB,0);
      delay(5000);
    }

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/


body:
Modifying the library code file L298N.cpp. Insert 2 lines in setSpeed():

    void L298N::setSpeed(unsigned short pwmVal)
    { _pwmVal = pwmVal;
      if (_ismoving == true)                   // +++
       analogWrite(_pinEnable, _pwmVal);      // +++
    }

Problem solved!


message:
Calculating the time between the signal when its ON and when it gets OFF

class Channel
    {
        private:
            uint8_t _pin;
            uint8_t _state;
            uint32_t _rise;
            uint32_t _fall;
            uint8_t _count;
            uint8_t _channel;

            static uint8_t channelCount;

            void display()
            {
                uint32_t diff = (_fall - _rise) / 1000;
                uint32_t secs = diff % 60;
                uint32_t mins = diff / 60;
              //  Serial.print(",");
                Serial.print(_channel);
                Serial.print(",");
                Serial.print(mins);
                Serial.print(",");
                Serial.print(secs-4);
                Serial.print(",");
                Serial.println(_count);
            }

        public:
            Channel(int pin) : _pin(pin), _count(0)
            {
                _pin = pin;
                _count = 0;
                _channel = channelCount;
                channelCount++;
            }
            void process()
              {
                int s = digitalRead(_pin);
                if (s != _state)
                  {
                    _state = s;
                    if (s == LOW)  // Fell
                      {
                        _fall = millis();
                        _count++;
                        display();
                      }
                    else
                      {
                        _rise = millis();
                      }
                    }
                }
            void begin()
            {
                pinMode(_pin, INPUT);
            }
    };

    uint8_t Channel::channelCount = 0;

    Channel channels[] = { 3,5 };
    #define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

    void setup()
    {
        Serial.begin(115200);
        Serial.println("Channel,Minutes,Seconds,Count");
        for (unsigned int i = 0; i < NUM_CHANNELS; i++)
          {
            channels[i].begin();
          }
    }

    void loop()
    {
        for (unsigned int i = 0; i < NUM_CHANNELS; i++)
          {
            channels[i].process();
          }
    }

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.

In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below [![which was taken when the output is recorded][1]][1]

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

body: I suspect secs is 0 sometimes, because of _rise being 0? In that case unsigned int subtraction causes this: secs(0) - 4 = -4 % 2^32, resulting in your 4294967292


message:
problem in uploading the code

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
    Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

body:
It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

- RX/TX UART port used
- USB port broken
- USB cable broken
- Arduino broken
- USB port drivers not properly installed
- Problem inside IDE
- ...

To troubleshoot you could try:

- Disconnect RX/TX jumpers
- Try another USB port
- Remove other USB devices
- Try another USB cable
- Try another Arduino
- Try another PC/laptop
- Reinstall IDE
- Reinstall USB drivers


body: Try to upload your code without any device connected to Uno. Disconnect all IO pins. Upload the code via onboard USB port.