body:
When `myservo_1,myservo_2,myservo_3,myservo_4` is commented, I can't control the speed of my M1 motor. But only when I uncomment `myservo_1` and so on, I can control the motor speed again.

Can someone help me? My codes are listed down below:

    #include <Servo.h>
    Servo myservo_1;
    Servo myservo_2;
    Servo myservo_3;
    Servo myservo_4;

    int SensorL = 0;
    int SensorR = 0;
    int SensorM = 0;

    #define E1 10
    #define M1 12
    #define E2 11
    #define M2 13
    int pos = 0;
    int incomingByte = 0;

    void setup()
    {
      Serial.begin(9600);
      myservo_1.attach(9);
      myservo_2.attach(8);
      myservo_3.attach(7);
      myservo_4.attach(6);
      pinMode(SensorL, INPUT);
      pinMode(SensorR, INPUT);
      pinMode(SensorM, INPUT);
      pinMode(M1, OUTPUT);
      pinMode(M2, OUTPUT);
    //  pinMode(E1, OUTPUT);
    //  pinMode(E2, OUTPUT);
    }

    void loop()
    {
      SensorR = digitalRead(2);
      SensorL = digitalRead(3);
      SensorM = digitalRead(5);

      if (SensorL == LOW && SensorR == LOW && SensorM == HIGH)
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" FORWARD ");
        //delay(1);
      }
      if (SensorL == HIGH && SensorR == LOW && SensorM == HIGH)
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, LOW);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" LEFT ");
        //delay(1);
      }
      if (SensorL == LOW && SensorR == HIGH && SensorM == HIGH) //move right
      {
        digitalWrite(M1, LOW);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" RIGHT ");
        //delay(1);
      }

      if (SensorL == HIGH && SensorR == HIGH && SensorM == HIGH) //stop
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 0);
        analogWrite(E2, 0);
        Serial.println(" STOP ");
        //delay(1);
      }

      if (SensorL == HIGH && SensorR == LOW && SensorM == LOW) //move left
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, LOW);
        analogWrite(E1, 125);
        analogWrite(E2, 125);
        Serial.println(" LEFT ");
        //delay(1);
      }

      if (SensorL == LOW && SensorR == HIGH && SensorM == LOW) //move right
      {
        digitalWrite(M1, LOW);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 125);
        analogWrite(E2, 125);
        Serial.println(" MoVE Right ");
        //delay(1);
      }

      if (Serial.available() > 0)
      {
        incomingByte = Serial.read();
        {
          {
            if (incomingByte == 'J')//ARM OPEN
            {
              myservo_1.write(0);
              Serial.println(" ARM OPEN ");
            }
            if (incomingByte == 'L')//ARM CLOSE
            {
              myservo_1.write(180);
              Serial.println(" ARM CLOSE ");
            }
            if (incomingByte == 'I')//ARM UP
            {
              myservo_2.write(0);
              myservo_3.write(180);
              Serial.println(" ARM UP ");
            }
            if (incomingByte == 'K')//ARM DOWN
            {
              myservo_2.write(180);
              myservo_3.write(0);
              Serial.println(" ARM DOWN ");
            }
            if (incomingByte == 'U')//ROTATE LEFT
            {
              myservo_4.write(0);
              Serial.println(" ROTATE LEFT ");
            }
            if (incomingByte == 'O')//ROTATE RIGHT
            {
              myservo_4.write(180);
              Serial.println(" ROATE RIGHT ");
            }
            if (incomingByte == 'M')
            {
              myservo_1.write(90);
              myservo_2.write(90);
              myservo_3.write(90);
              myservo_4.write(90);
              Serial.println(" ALL STOP ");
            }
            if (incomingByte == 'N')//ARM STOP
            {
              myservo_1.write(90);
              Serial.println(" ARM STOP ");
            }
            if (incomingByte == 'B')//UP DOWN STOP
            {
              myservo_2.write(90);
              myservo_3.write(90);
              Serial.println(" UP DOWN STOP ");
            }
            if (incomingByte == 'V')//ROTATION STOP
            {
              myservo_4.write(90);
              Serial.println(" ROTATION STOP ");
            }
            if (incomingByte == 'W')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 200);
              analogWrite(E2, 0);
              Serial.println(" FORWARD ");
            }
            if (incomingByte == 'Z')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" FORWARD ");
              delay(100);
            }
            if (incomingByte == 'S')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, LOW);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" REVERSE ");
            }
            if (incomingByte == 'A')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, LOW);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" LEFT ");
            }
            if (incomingByte == 'D')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" TURNING RIGHT ");
            }
            if (incomingByte == 'X')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 0);
              analogWrite(E2, 0);
              Serial.println(" STOP MANAUAL ");
            }
            if (incomingByte == 'w')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW FORWARD ");
            }
            if (incomingByte == 's')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, LOW);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW REVERSE ");
            }
            if (incomingByte == 'a')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, LOW);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW LEFT ");
            }
            if (incomingByte == 'd')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW RIGHT ");
            }
          }
        }
      }
    }

title: Why can't I control speed of the motor? (M1 and E1)

Answers: 2

body:
The Servo library uses `timer 1` to send the signals to the servos. But `timer 1` is also used to run PWM on pins 9 and 10. It can't however do both.

So since Motor E1 uses pin 10, and `timer 1` is already used by the Servo library, PWM, and by extension, `analogWrite` doesn't work.

E2 uses pin 11, which uses `timer 2` for it's PWM, so is therefor no affected.

So move E1 to one of the PWM pins, other than 9 and 10, and thing should start working again.

I however don't know why M1 doesn't work.

body:
 - Please correct your code there are several mistakes, such as
   1. the lines at beginning of loop SensorR = digitalRead(2); SensorL = digitalRead(3); SensorM = digitalRead(5); doesn't make any sense.. as
   you not defined 2,3,5 pin as input. And for taking analog input
   please change pins 2,3,5 and analog pins..
   2. Motor Pin M1 and M2 are connected 12,13 which are not pwm pins so you can't use to change the speed of your Motor.. Please make this
   code sensible....


body:
I have this error while uploading my code to ESP8266 despite the fact that the code runs without errors. I have the git version of installation for the board.

**ERROR:**

    File"C:/../../AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 1889, in slip_reader
    raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
    esptool.FatalError: Invalid head of packet (0x46)
    esptool.FatalError: Invalid head of packet (0x46)

Any help with this? Thanks.

title: FatalError('Invalid head of packet (0x%s)' % hexify(b)) while uploading on ESP8266

Answers: 0


body: i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

title: how to switch more 230v with arduino?

Answers: 1

body:
You have to use a relay that can handle minimum 415 volts (and keep some reserve).

Also take the current/amperage into account (possibly use multiple relays).


body:
I am extremely new to Arduino coding and have downloaded a sketch for the PCA9685 to use with model railroading and turnout control.  When I verify the sketch I get several errors ... I don't even know how to resolve and could use some assistance.  There are two sketches:

#1:

        /***************************************************
      This sketch can be used to operate any number of turnouts on a
      Model Railroad. Code blocks can be added to accomodate any number
      of servos. This sketch uses only two servos for this demonstration.

      The pushbutton can be replaced with a SPST switch
      commonly used on a control panel. Three pin Bicolor LED can be used
      in place of two seperate LEDs in each circuit.

      10K Ohm pulldown resistor used on switch
      330 Ohm resistor used on LEDs. One per pair of LEDs

      Created 03/02/2019 by Tom Kvichak
      https://tomstrainsandthings.com/
      Additional Arduino Projects can be found at the above web address

     ****************************************************/

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    int buttonPin0 = 2;   // Can add as many buttons as needed
    int ledPin0C = 3;     // C designates Closed position of turnout
    int ledPin0T = 4;     // T designates Thrown position of turnout
    int buttonState0 = 0;

    int buttonPin1 = 5;
    int ledPin1C = 6;
    int ledPin1T = 7;
    int buttonState1 = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("pca9685_TurnoutFinal!");
      pwm.begin();
      pwm.setPWMFreq(60);
      delay(30);

      pinMode(ledPin0C, OUTPUT);
      pinMode(ledPin0T, OUTPUT);
      pinMode(buttonPin0, INPUT);
      pinMode(ledPin1C, OUTPUT);
      pinMode(ledPin1T, OUTPUT);
      pinMode(buttonPin1, INPUT);
    }

    void loop() {
      ///////////
      buttonState0 = digitalRead(buttonPin0);
      if (buttonState0 == HIGH) {
        pwm.setPWM(0, 0, 370);
        digitalWrite(ledPin0T, LOW);
        digitalWrite(ledPin0C, HIGH);
      }
      else  {
        pwm.setPWM(0, 0, 285);
        digitalWrite(ledPin0C, LOW);
        digitalWrite(ledPin0T, HIGH);
      }
      //////////
      buttonState1 = digitalRead(buttonPin1);
      if (buttonState1 == HIGH) {
        pwm.setPWM(1, 0, 370);
        digitalWrite(ledPin1T, LOW);
        digitalWrite(ledPin1C, HIGH);
      }
      else  {
        pwm.setPWM(1, 0, 285);
        digitalWrite(ledPin1C, LOW);
        digitalWrite(ledPin1T, HIGH);
      }
      //////////
    }

#2:

        /***************************************************
      This is an example for our Adafruit 16-channel PWM & Servo driver
      Servo test - this will drive 8 servos, one after the other on the
      first 8 pins of the PCA9685

      Pick one up today in the adafruit shop!
      ------> http://www.adafruit.com/products/815

      These drivers use I2C to communicate, 2 pins are required to
      interface.

      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
    //Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

    #define SERVOMIN  110 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  510 // this is the 'maximum' pulse length count (out of 4096)

    // May have to adjust values to match your servos
    // Test your servo with the procedures below

    // our servo # counter
    uint8_t servonum = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("pca9685_TurnoutTest!");
      pwm.begin();
      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
      delay(50);
    }
    ///////////////////Functions//////////////////////

    void driveMin() {
      pwm.setPWM(servonum, 0, SERVOMIN);    //Use to test low range
    }
    void driveMax() {
      pwm.setPWM(servonum, 0, SERVOMAX);    //Use to test high range
    }
    ///////////////End Of Functions//////////////////

    void loop() {

      for( int angle =0; angle<181; angle +=15){  // testing only right now
        delay(500);
        pwm.setPWM(1, 0, convert2angle(angle) );   // May only need this for sweeping the servo
      }

    }
    int convert2angle(int myang){
       int pulse = map(myang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
       Serial.print("Angle/Pulse: ");Serial.print(myang);
       Serial.print(" / "); Serial.println(pulse);
       return pulse;
    }

**ERROR MESSAGES:**

    pca9685_TurnoutTest:23:25: error: redefinition of 'Adafruit_PWMServoDriver pwm'

     Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                             ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:21:25: note: 'Adafruit_PWMServoDriver pwm' previously declared here

     Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                             ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void setup()':

    pca9685_TurnoutTest:35:6: error: redefinition of 'void setup()'

     void setup() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:33:6: note: 'void setup()' previously defined here

     void setup() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void loop()':

    pca9685_TurnoutTest:52:6: error: redefinition of 'void loop()'

     void loop() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:48:6: note: 'void loop()' previously defined here

     void loop() {

          ^

    Using library Wire at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\Wire
    Using library Adafruit-PWM-Servo-Driver-Library-master at version 2.0.0 in folder: C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master
    exit status 1
    redefinition of 'Adafruit_PWMServoDriver pwm'

Answers: 1

body:
You seem to compile a sketch from a folder, where more than 1 .ino file is placed. I guess this from the paths, that are mentioned in the error messages.

The Arduino IDE supports you to organize your code into multiple .ino files, so that big code can be read way easier. For this it put's together all .ino files in the folder of the main sketch, so that they get compiled together.

Since you have at least 2 full sketches in the same folder, this leads to a redefinition error, since these resources (the variable `pwm` and the functions `setup()` and `loop()`) are already defined by the first sketch, when the compiler gets the second sketch.

You have to put all your individual sketches into own folders. Then the error will not appear. I tried to compile your two sketches individually and that worked fine.


body:
    void setup() {
      pinMode(5, OUTPUT);
    }

    void loop() {
      analogWrite(5, 0);
      // or
      //digitalWrite(5, LOW);
    }

Output is 0.003V and the tiny voltage causes the circuit to draw 20uA.

Is there anyway to get absolute 0V from Arduino PWM pin?

title: Why Arduino pins don't output 0 volt?

Answers: 1

body:
It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.

LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".


body: Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

title: Interface a mobile phone's finger print scanner with arduino

Answers: 3

body:
Possible but not directly as the arduino compatible fingerprint sensor contains image formation and saving mechanism which means that those sensors scan a fingerprint form image and send the scan status not the finger print image....

As in case of fingerprint sensor of phones, the sensor directly send the whole image...

so you have to use FPGA (Field Programming Gate Arrays) to make communication between that...

But this is a very expensive way... As FPGA are very expensive but have huge functionality means you can design any circuit any sensor any controller you want using FPGA

body:
In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

- Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
- The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
- As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
- The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
- You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)

All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.

body:
Long-shot, but if the phone is still functional enough to unlock with a fingerprint, try sensing the overall screen brightness when locked and when unlocked, and use that as the "Fingerprint matched" signal. Obviously this won't work with a truly dead phone.

A *lot* of processing goes into reading and storing or matching a finger-print. The magic is in the software, not (only in) the sensor. An Arduino (Uno class or similar) is way under-powered for the task. Perhaps one of the Arm- or other high-end Arduinos would have the capability if you had or could write the necessary software.

Short answer: No.


body:
I have made a setup with Arduino Uno, Nema 17, T8 lead screw, IR Sensor and a DC motor.
I am trying to establish a code which:

1. Resets Home position of the Machining Head on the lead screw
2. Has an action button, which operates only when the position of the Head is on the lead screw, goes down the specified depth
3. Takes input from user to run the DC Motor (to rotate the tool on the machine head)
4. Takes second input to stop rotating and return to the reset position.

I am facing one major problem and two minor problems:

Major Problem:
To remove an error which was later resolved, I added the line: action_permit=0
Now due to some reason (I have pulled a lot of hairs trying to understand this), when I remove this action_permit line, the DC Motor rotation is stopped. I  have to include this line to rotate my DC Motor.

Minor Problem:
To get input from the user as to control when the DC motor starts and stops, I included the code which accepts 'y' for yes (start rotating the DC motor) and 'n' as no (stop rotation and return to home position)

Minor Problem:
I am not sure how to control the PWM, I have copied the code from a video, but do not know how to reach maximum and minimum rpm; also I understand the variation between PWM value and RPM is not linear. Any feedback on how to precisely control the rpm of the motor would be great
<!-- language-all: lang-cpp -->
```
int IR_signal=2;
int DC_ENB=11;
int DC_IN3=4;
int DC_IN4=5;
int STE_dir=6;
int STE_step=7;
int STE_ena=10;
int button_reset=8;
int button_action=9;
//define arduino pin
int action_permit;//0-action part is not allowed to run. 1-action part is allowed to run
int IRon;
int COUNT;//the amount of steps that the machine head should go
int HEIGHT;//total height that the machine head should go
int i;
int reset_on;
int action_on;
String Switch_DC;

//parameter
void setup() {
  // put your setup code here, to run once:
  pinMode(IR_signal,INPUT);
  pinMode(button_reset,INPUT);
  pinMode(button_action,INPUT);
  //input part
  pinMode(DC_ENB,OUTPUT);
  pinMode(DC_IN3,OUTPUT);
  pinMode(DC_IN4,OUTPUT);
  pinMode(STE_dir,OUTPUT);
  pinMode(STE_step,OUTPUT);
  pinMode(STE_ena,OUTPUT);
  //output part
  action_permit=0;// ban the action part at the beginning
  COUNT=0;
  HEIGHT=0;

  //original value of parameters
  //digitalWrite(DC_ENB,HIGH);
  analogWrite(DC_ENB,200);
  digitalWrite(STE_ena,LOW);
  digitalWrite(DC_IN3,HIGH);
  digitalWrite(DC_IN4,HIGH);
  //original pin output
  Serial.begin(9600);
  // start the monitor
}

void loop() {
  // put your main code here, to run repeatedly:
  reset_on=digitalRead(button_reset);
  action_on=digitalRead(button_action);
  //read the signal from the button
  if(reset_on==0)//reset button is pressed
  {
    delay(10);
    // preventing manual error
    if(reset_on==0)
    {
      RES();
    }
  }
  if(action_on==0)//action button is pressed
  {
    delay(10);
    // preventing manual error
    if(action_on==0)
    {
      ACT();
    }
  }
}
void RES()//reset part
{
  while(action_permit==0)//when 0, this "while" loop will keep running
  {
    IRon=digitalRead(IR_signal);// read the signal from IR sensor
    if(IRon==1)// machine head is not in original position
    {
      delay(1);
      //ensure the signal is not happened by a BUG
      IRon=digitalRead(IR_signal);
      if(IRon==1)
      {
        digitalWrite(STE_dir,LOW);
        digitalWrite(STE_step,HIGH);
        delay(1);
        digitalWrite(STE_step,LOW);
        delay(1);
        //if machine head is not in original position, it will go up for one step
      }
    }//if HIGH, go up
    else if(IRon==0)
    {
      action_permit=1;
      COUNT=0;

    }//once machine head reaches the original position, controller will get out this loop and allow action part to run
  }
}
void ACT()//action part
{
  if(action_permit==1)
  {

   for(i=0;i<3523;i+=1)
   {
     digitalWrite(STE_dir,HIGH);
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   delay(100);
   for(i=0;i<100;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(10);
     digitalWrite(STE_step,LOW);
     delay(10);
   }
   action_permit=0;

   Serial.println("Please press y to start tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if (Switch_DC == "y")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,HIGH);
    digitalWrite(DC_IN4,LOW);
    delay(2000);
   }

   Serial.println("Please press n to stop tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if(Switch_DC == "n")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,LOW);
    digitalWrite(DC_IN4,LOW);
   }
   digitalWrite(STE_dir,LOW);
   for(i=0;i<4523;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   action_permit=0;
  }
}
```

title: Requesting help with CNC Project using Arduino

Answers: 1

body:
You have some obvious problems in your code, though I don't know, if the logic will be correct (doing what you want it to do) if you fix them. But either way it is a good start.

- You check for `action_on` and `reset_on` to be LOW, so I guess the button will pull the pin to LOW, if you press it. You didn't activate the internal pullup resistors, so I guess you already have them externally (if not: You definitely need them). So `action_on==0` actually is the case for action is permitted to run, not forbidden. You seem to think, that it is the other way round.
- Then you are doing this (and the same with `reset_on`):

        if(action_on==0)//action button is pressed
          {
          delay(10);
          // preventing manual error
          if(action_on==0)

    You check, if `action_on` is zero. If yes, you wait a bit and check the same again. The value of `action_on` cannot change during the delay, so this will always be true and thus is superfluous. If you meant to read the button again, to check if the button was really pressed (for debouncing), you have to actually read the button state again with `digitalRead()` and save it to `action_on`, like you have done before. This is not done automatically for you.
- `for(i=0;i<3523;i+=1)`  Using a global variable to count in a for loop is not a good idea. Instead you should always use a local variable to do this: `for(int i=0;i<3523;i+=1)`
- `Switch_DC=Serial.readString();`  Using `readString()` is not good coding, because this function just reads all data, that comes until the timeout hits (default 1s). This is not a reliable way to read data from Serial. Instead you should read each character individually from the Serial interface, put it into a buffer, and only stop and process the output, if a delimiting character was send. Often a newline character `\n` is used for this. So one message/command, that should be processed as a whole should be ended with a newline character. That will prevent, that the input from serial is processed incorrectly, only because the timing was different. If you only have commands, that consist of only 1 character, you can instead use a single `Serial.read()`, which reads exactly one character from the Serial interface (or returns -1 if there is no character to read).
- Then you wrote this:

        if (Switch_DC == "y")
        action_permit=0;
        {

   I guess, here you have inserted the `action_permit=0`. This cannot be, want you meant. As you wrote it, the `action_permit=0` line will only be executed, if `Switch_DC` is equal to "y", since this statement is inside the if statement. The `;` at the end of the statement also closes the if statement. So the code inside the following brackets will always be executed and the brackets are superflous. I don't know, where you intended to insert the `action_permit=0`, but since it is never used in the rest of the function, it is sufficient to just use it at the end of the function, like you already did. Remove all other of these lines from that function.

---

If you want to control the RPM of the motor, not just some relative PWM value, you first need to measure the RPM. PWM just controls the electrical energy going into the motor in a relative way (relative to fully powered on). To set a RPM value for the motor, you need to measure the current RPM (for example with a light barrier or a rotary encoder) and use that as input for a PID controller (Proportional Integral Differential). The output of the PID controller then must be fed into the `analogWrite()` function. The PID controller will raise or lower the PWM value, until the RPM setpoint is reached. There is a [PID library][1] for Arduino, that will help you with the calculation.

  [1]: https://github.com/br3ttb/Arduino-PID-Library/


body:
I have tried code given below for simple traffic signal and also display on LCD which color is ON, but it didn't work. Please me to make it work.
<!-- language-all: lang-cpp -->

    int red = 10;
    int yellow = 9;
    int green = 8;
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    void setup(){
        pinMode(red, OUTPUT);
        pinMode(yellow, OUTPUT);
        pinMode(green, OUTPUT);
    }

    void loop(){
        changeLights();
        delay(1500);
    }

    void changeLights(){
        lcd.print("red");
        digitalWrite(yellow,LOW );
        digitalWrite(red, HIGH);
        digitalWrite(green,LOW );
        delay(3000);
        lcd.print("yellow");
        digitalWrite(yellow,HIGH );
        digitalWrite(red,LOW );
        digitalWrite(green,LOW );
        delay(3000);
        lcd.print("green");
        digitalWrite(yellow,LOW );
        digitalWrite(red,LOW );
        digitalWrite(green,HIGH );
        delay(3000);
        //if(
    }

title: a code to implement a simple traffic signal and also display on LCD which color is ON?

Answers: 2

body:
Write a sketch to test your LCD.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 4, 2);
    void setup(){
        lcd.begin();
        lcd.print("Hello World!");
    }
    void loop() {
        lcd.setCursor(0, 1);
        lcd.print(millis() / 1000);
    }

Make sure the R/W pin is connected to GND on your breadboard. You may need to connect the contrast pin to 5V. Ideally it should be connected to the wiper of a 10KOhm trimpot with either end connected to GND & 5V (so you can vary the contrast).

Once that set-up works change your code

     void setup(){
         lcd.begin();
         lcd.print("Traffic signals");
         delay(500);
         pinMode(red, OUTPUT);
         pinMode(yellow, OUTPUT);
         pinMode(green, OUTPUT);
     }

     void loop(){
         changeLights();
         lcd.setCursor(0,0);
     }

body:
A small update to your code

 1. Added `lcd.begin();` function
 2. added `lcd.clear();` function so that old characters will be removed before adding new display

Here is the complete code

    int red = 10;
    int yellow = 9;
    int green = 8;
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    void setup() {
      lcd.begin(16, 2);
      pinMode(red, OUTPUT);
      pinMode(yellow, OUTPUT);
      pinMode(green, OUTPUT);
    }

    void loop() {
      changeLights();
      delay(1500);
    }

    void changeLights() {
      lcd.clear();
      lcd.print("red");
      digitalWrite(yellow, LOW );
      digitalWrite(red, HIGH);
      digitalWrite(green, LOW );
      delay(3000);
      lcd.clear();
      lcd.print("yellow");
      digitalWrite(yellow, HIGH );
      digitalWrite(red, LOW );
      digitalWrite(green, LOW );
      delay(3000);
      lcd.clear();
      lcd.print("green");
      digitalWrite(yellow, LOW );
      digitalWrite(red, LOW );
      digitalWrite(green, HIGH );
      delay(3000);
      //if(
    }
The output would look like this:

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

[Here][2] is the link to the Arduino simulator example

  [1]: https://i.stack.imgur.com/HP3Io.gif
  [2]: https://wokwi.com/arduino/projects/304640214914040386


body:
I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say `expected unqualified-id before 'public'`.

Does anybody know how to fix this?

```
void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}
```

<!-- Remove this -->

title: Expected unqualified-id before 'public'

Answers: 1

body:
    static public int recordings[99999999] = {NULL}

This is not valid C code. Remove the word `public`.
Also you cannot create such a big array. The Arduino has only 2 KB (SRAM) memory and also since it is static you have to fill it with values directly, like:

    static int recordings[5] = { 0, 1, 2, 3, 4 };

How many values you want to store?

In case you need quite a lot (like hundreds), I would use a different solution for the `state` array as it only stores values 0 or 1. For example, you can use arrays of uint8_t which cost only 1 byte per element, but even better would be to store 8 0 or 1 (boolean) values in one byte each, but that means you have to get/set the values in the correct indices yourself.


body:
I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. My connection is successful and I am able to receive message/topic printed out on serial console. Here is my code:

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "SSID"
#define wifi_password "PASSWORD"
#define mqtt_server "192.168.1.1"
#define mqtt_user "mqtt_username"
#define mqtt_password "mqtt_password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;
WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
.button { background-color: #195B6A; border: none; color: white; padding: 16px 40px
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer
body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;
.button2 {background-color: #77878A;
p {font-size: 24px;color: #444444;margin-bottom: 10px;}
</style>
</head>
<body>
<div id="webpage">
<h1>Security Door</h1>
<p><a href="/show/SecurityDoor/Open"><button class="button">Open</button></a></p>
<p><a href="/show/SecurityDoor/Close"><button class="button">Close</button></a></p>
</div>
</body>
</html>
)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();
  Serial.print(messageTemp);

 if(topic=="livingroom/securitydoor"){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       doorClosing();
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function -----------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

```

Issue is: message from below is not printing in serial

```
       Serial.print("On");
       Serial.print("On from opening");
```

In fact code is displaying topic and message in serial console.

My actual user case is to display status on OLED display as well as control relay.

title: NodeMCU MQTT getting topic but not calling IF loop

Answers: 1

body:
thanks for suggestions,

When i am doing it in below way, it got worked

```
if (strcmp(topic, "livingroom/securitydoor") == 0)
  {
    Serial.print(topic);
  }
```


body:
I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.

I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.

I am using the GPSLocation sample from the Arduino_MKRGPS library (see [here][1]):

```
  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

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

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}
```

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.

Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?

Thanks!

  [1]: https://github.com/arduino-libraries/Arduino_MKRGPS/blob/master/examples/GPSLocation/GPSLocation.ino

title: MKR GPS Shield Sampling Frequency

Answers: 1

body:
It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.

I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.

In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.

EDIT:

I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.

I had to make the following two changes to the Arduino_MKRGPS library:

1. increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

```
GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);
```

2. In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:

```
  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");
```

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.


body:
[![Basic Circuit Diagram][1]][1]

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

Hi,

I am currently doing a project and it seems that I may have blown my Arduino Nano (or maybe not). The power LED of the Nano was still on and I believe the L pin blinks once every time I press the reset button.

I wanted to use 4AA alkaline batteries to power my project. The servo is a continuous servo rated for 4-6V and 15-200mA from Parallax. Given that the Nano runs optimally when powered at 7-12V, I decided to buy a step-up converter (adjustable output voltage). It looks like this although I bought it elsewhere:

https://www.ebay.com.au/i/283603471149?chn=ps&norover=1&mkevt=1&mkrid=705-139619-5960-0&mkcid=2&itemid=283603471149&targetid=752505019384&device=c&mktype=pla&googleloc=9071392&poi=&campaignid=1979582348&mkgroupid=72745766764&rlsatarget=pla-752505019384&abcId=1139426&merchantid=7364522&gclid=Cj0KCQjwt5zsBRD8ARIsAJfI4Bh8cSOKugFrugHz-gA-s8nXclnO7H8iQ-WX46FRdhDLchwbl6UyWLgaAr4oEALw_wcB

When I tried to test it with the servo running, my Nano stopped working after several seconds later. Did I wire them up wrongly? I also measured the output of the step-up converter when it was running with a voltmeter between the two terminals of the step-up's output. Would it be possible to short it that way?

Appreciate any help I can get. Thanks

title: Blew my Arduino. Did I wire this correctly?

Answers: 1

body:
It would be best if everything ran at the same voltage. (And it is necessary that everything uses the same ground.)  Which is possible as there are 5V Arduino boards.  Interestingly, the Arduino nano, according to [this schematic][1], runs at 5V.

In order to use the Arduino Nano at 5V, instead of using VIN / Pin 1, you should be able to skip the Arduino's 5V regulator and use +5V / Pin 4.  But this must be a regulated 5V power source.

Now, why are you having problems controlling the servo?

It is difficult to tell, but your boost switching power supply negative input may not be directly connected to the negative output.  With out a common ground, it may be difficult to create the proper signal to control the servo.

To be specific, if the ground or negative side of the servo power supply is not at the same potential as the ground or negative side of the Arduino power supply, controlling the servo may be difficult at best and at worst you could burn something out on the servo or Arduino.

To check, measure with a volt meter to see if there is any difference between the boost switcher negative input and negative output.

To solve this problem consider using a USB power supply plugged into the Arduino Nano and powering the servo off the 5V at pin 4 of the Nano.  Or, keep using your 6V battery and 6V to 9V boost switching power supply.  Connect this as you are to VIN Pin 1.  The Arduino Nano's 5V power regulator should kick in and provide 5V at pin 4.

  [1]: https://content.arduino.cc/assets/NanoV3.3_sch.pdf


body:
In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?

```c++
#include <CStringBuilder.h>

int Max_pack_size = 100;

void setup() {
  SerialUSB.begin(115200);

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}
```

title: How to decrease delay for String concatenation + Arduino Due

Answers: 1

body:
I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.

This is the original code as you can see i can use only Max_pack_size of 5

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
```
The timer displays values around 2.08 milliseconds for the code above.

First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.

Note that when we generate `String` from `long` the [implicit cast][1] allocates `char buf[2 + 3 * sizeof(long)];` so the max length of such string is 14 characters. String is of course terminated by null character `'\0'`

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}
```

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!

Let's drop the String. It's just an over complicated wrapper for a char array anyway.

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
```

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.cpp


body:
I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else

    void setup() {
        // put your setup code here, to run once:
        pinMode(5, INPUT);
        pinMode(6, OUTPUT);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        digitalRead(5, HIGH);
        digitalWrite(6, HIGH);
        delay(3000);
        digitalWrite(6, LOW);
        digitalWrite(6, HIGH);
        delay(2000);
        digitalWrite(6, LOW);
        digitalWrite(6, HIGH);
        delay(1000);
    }

title: How to use the pushbutton without using if, else

Answers: 3

body: As the required operation is finite and short, you can just hard code the sequence.

body:
You could you simple inversion of boolean variable to set state of LED.

    const int LedPin = 5;
    bool ledState = true;

    // in your loop

    // bool will be transformed from true to 1 (HIGH)
    digitalWrite(LedPin, (int)ledState);
    // invert LED state to be false
    ledState = !ledState;
    // false -> 0 (LOW)
    digitalWrite(LedPin, (int)ledState);

body:
Ternary operator maybe helpful. [[Reference]][1]

  [1]: https://www.tutorialspoint.com/arduino/arduino_conditional_operator.htm


body:
I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:

~~~c++
const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}
~~~

However, the `Serial.println("trigger");` is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?

**P.S.** [Filip Franik][1] asked me to draw the schematics:

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

<!-- End schematic -->

**P.S.** I used [the official Button's tutorial][2] and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.

  [1]: https://arduino.stackexchange.com/users/34529/filip-franik
  [2]: https://www.arduino.cc/en/tutorial/button

title: Interrupt is activated as soon as I insert a jumper wire into the port

Answers: 2

body:
Connect both Pin2 and Pin3 with two 1K resistors to ground.

When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.

This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

[![modified design from the question][1]][1]

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to [burn a bootloader][2] on the chip. It's not a hard procedure but it requires a second Arduino.

  [1]: https://i.stack.imgur.com/ASSdN.png
  [2]: https://arduino.stackexchange.com/questions/473/how-do-i-burn-the-bootloader

body:
CMOS inputs "float" when not connected to anything, and will give semi-random values. You can either connect the pin to ground via a medium value resistor (1kΩ-10kΩ), or set the pin to INPUT_PULLUP mode.

You shouldn't move the interrupt pin connections around while the Arduino is running. As soon as you disconnect the wire from the input, it begins floating again, and can detect semi-random HIGH/LOW values.

If you use an external pull-down resistor, put a connector after the ground connection and move that connection, so the pull-down resistor is always connected to the pin.

If you use INPUT_PULLUP mode, you should not use a pull down or pull up resistor. This mode connects the pin weakly to +5V, which will hold it at a HIGH value when not connected to anything. You would then ground it to trigger an interrupt. In INPUT_PULLUP mode you can probably disconnect the wire from the interrupt pin without triggering interrupts.


body:
I have trouble figuring out how to sort a String that has a Number in it.

The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.

I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.

edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.

I guess it would also be enough to just sort the strings, but i cant find a function for that also.

title: How to Sort a String with Number by Ascending

Answers: 2

body:
You can use the `qsort` function (see [c-library-function-to-do-sort][1]).

With the user definable `comp` function you can get the first two or three characters, convert it to in integer and compare it against the converted integer from another element.

I would not advise to use strings, because of the limited SRAM storage of an Arduino, you might run out of memory too fast.

  [1]: https://stackoverflow.com/questions/1787996/c-library-function-to-do-sort

body:
As Michel Keijzers points out, `qsort` is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

* parse the start of the strings as integers
* compare the integers
* if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is `atoi()`. Unlike
functions like `strtol()`, `atoi()` does no error checking, but it is
good enough if you know for sure that the strings have the right format.

Here is the comparison function:

```c++
int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}
```

And here is an example on how to use it:

```c++
#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);
```

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").


body:
I recently got my esp8266-01 and for interfacing with Arduino I completed all the steps need for right form pins to board allotting from esp8266 community after everything I still get error of "connection failed fatal error : timeout ", so anyone just help out for
 soln ?
I am interfacing with empty code of loops only to check it's response at connectivity at first .

title: Esp8266 fatal timeout error

Answers: 0


body:
How to get Current date, month and year. I have used RTC, NTPClient, but it didn't work. This gives default output of 1970. What can I do for fixing it.
<!-- language-all: lang-cpp -->

    time_t now = time(nullptr);
    struct tm* newtime = localtime(&now);
    String tmpNow = "";
    tmpNow += String(newtime->tm_year + 1900);
    tmpNow += "-";
    tmpNow += String(newtime->tm_mon + 1);
    tmpNow += "-";
    tmpNow += String(newtime->tm_mday);
    tmpNow += " ";

title: How to get current Date

Answers: 1

body:
An [example][1] how to use NTPClient is available at the projects github

```c++
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

```

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in [video here][2] and with it we should be able to get the real time as seen in github [example][3]

```c++
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

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

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.

Check some more examples [here][4]

  [1]: https://github.com/arduino-libraries/NTPClient/blob/master/examples/Basic/Basic.ino
  [2]: https://www.youtube.com/watch?v=E6wkvTG2Ofs
  [3]: https://github.com/PaulStoffregen/Time/blob/master/examples/TimeRTC/TimeRTC.ino
  [4]: https://github.com/PaulStoffregen/Time/tree/master/examples


body:
I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. Also like to display status on OLED

here is my code

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "ssid"
#define wifi_password "wifipassword"
#define mqtt_server "192.168.1.1"
#define mqtt_user "username"
#define mqtt_password "password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String display_line2;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;

WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
.button { background-color: #195B6A; border: none; color: white; padding: 16px 40px
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer
body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;
.button2 {background-color: #77878A;
p {font-size: 24px;color: #444444;margin-bottom: 10px;}
</style>
</head>
<body>
<div id="webpage">
<h1>Security Door</h1>
<p><a href="/show/SecurityDoor/Open"><button class="button">Open</button></a></p>
<p><a href="/show/SecurityDoor/Close"><button class="button">Close</button></a></p>
</div>
</body>
</html>
)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  //dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();

 if(strcmp(topic, "livingroom/securitydoor") == 0){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function --------------------------------------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

//----------------------- LED display--------------------------------------

void doorOpening() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Opening");
  display.display();
}

void doorClosing() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Closing");
  display.display();
}

```

actually doorOpening() function is coming and doorClosing() function is not coming on OLED

again i am not very good in programming and arduino/esp8266

title: MQTT with OLED realy :- display not coming properly

Answers: 1

body: i found the issue, actually relay pin was defined on D1 & D2 by mistake i connected oled to that pins


body:
So i have project for underwater rangefinding using JSN-SR04T. I've read on the datasheet that the module sends square waves. Is it possible to program it so that it sends Chirp waves instead ? (Help with the coding is very appreciated)
Thanks in advance

title: Can Chirp Waves be sent using JSN-SR04T?

Answers: 1

body:
As I googled the sensor, I found various sites stating, that a JSN-SR04T behaves exactly like the HC-SR04. The difference is mainly the water prooving.

So the answer is: No, you can't do this. The square wave, which drives the ultrasonic transducers, is generated by a hardware circuit and is not meant to be changed. To output a chirp wave you would need to rebuild the signal generation and measurement hardware (leaving only the transducers unchanged). At that point you may just buy the pure ultrasonic transducers and build the rest yourself.


body:
I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?
<!-- language-all: lang-cpp -->

    #define trigPin 2
    #define echoPin 3

    // Define variables:
    long duration;
    int distance;

    void setup() {
      // Define inputs and outputs
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // Begin Serial communication at a baudrate of 9600:
      Serial.begin(9600);
    }
    void loop() {
      // Clear the trigPin by setting it LOW:
      digitalWrite(trigPin, LOW);

      delayMicroseconds(5);
     // Trigger the sensor by setting the trigPin high for 10 microseconds:
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
      duration = pulseIn(echoPin, HIGH);

      // Calculate the distance:
      distance = duration*0.034/2;

      // Print the distance on the Serial Monitor (Ctrl+Shift+M):
      Serial.print("Distance = ");
      Serial.print(distance);
      Serial.println(" cm");

      delay(100);
    }

title: Ultrasonic Sensor - JSN-SR04T 2.0

Answers: 1

body:
According to the data sheet the minimum target distance is 20cm in the open air at a 343 m/s

The speed of sound in water is 1481 m/s so the minimum distance would be 20cm x 1481 / 343 = 86cm.

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

You cannot measure distances under 83cm in water.

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


body:
From what I have read, when placed within a magnetic field, a current will flow in both sensors.

My goal is to use this kind of sensors to guide a robot thanks to an existing automower loop wire, such as suggested in [DIY Perimeter Wire Generator and Sensor][1].

I am thus wondering what is the difference between a Hall effect sensor and an inductive one such as the one described in the link above?

  [1]: https://www.instructables.com/id/DIY-Perimeter-Wire-Generator-and-Sensor/

title: What is the difference between a Hall effect sensor and an inductive one?

Answers: 1

body:
First they physically work differently. In the Hall effect sensor the electrons flowing through a plate will be deflected. Thus there will be a voltage perpendicular to the current, which can be measured. The voltage will be proportional to the magnetic field strengh. So you can sense a magnet, that is near the sensor, even if it doesn't move.

For the inductive sensor you have a guiding wire, that has an AC current flowing through it. This also means, that a magnetic field ist constantly building up and collapsing again around the wire. This change of magnetic field will induce an induction voltage in a nearby wire loop (the actual sensor). The frequency of that voltage is the same as of the guidance wire and the strength depends on the distance between the wires. So you are not measuring the magnetic field strength directly, but you measure how much it is changing (mathematically you differentiate).

Two different measurement methods which can be used to do the same thing. To guide a robot over a predefined course I would use the induction method (as long as the situation allows laying out wires), since it can be made less susceptible to noise. For that you can filter out all frequencies except of the used guiding frequency with a LC circuit. Or even better (though maybe not important) a lock-in amplifier. The hall sensor is an analog device, which can be very noisy.


body:
What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:

    setup(){
        wifi.mode(WIFI_AP_STA);
        setup softAP
        server.on("/",handleroot)
        server.begin()
    }
    loop(){
        server.handleClient()
        if(credential_submited){
            Wifi.begin(credentials);
            flag_connection_started =true;
            credential_submited = false;
            flag_for_internet_server=true;
        }
        if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
            server.on("/",handleroot)
            server.begin()
            flag_for_internet_server=false;
        }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

title: WiFi connection in loop function

Answers: 2

body:
WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.

You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().

BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.

body:
This is not a big deal...

You can do it vary easily, the most simple way is that you can use EEPROM to achieve this..

Simply pass the SSID and PASSWORD of new network to ESP8266 and save it in EEPROM and also create a new variable in eeprom that store the status that new network credentials is entered or not and check it in loop and then fetch new network credentials from the EEPROM and try to connect to it...

You can also check and connect to your desired network from the loop...

Or alternatively you can use the library that can help you in doing that [WiFiManager]: https://github.com/tzapu/WiFiManager


body:
I am taking reading from temperature sensor and from that data. I have to control 3 LEDs. Lets consider LED1, LED2, LED3.

    If temperature range between 0-20
       I have to HIGH LED2.
       else if temperature range between 20-30
    I have to HIGH LED1; HIGH LED3; LOW LED1;

my sketch is something like this:-

    while(1)
    {
    if(temp>=0&&temp<=20)
    {
    digitalWrite(2,HIGH);
    }
    else if (temp>=20&&temp<=30)
    {
    digitalWrite(1,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(1,LOW);
    }
    }

The problem which I am facing is LED1 is continuously ON (which should be OFF), when temperature is between 20-30 because of continuously running loop so, how can I stop loop, once the statement under second condition has executed till the second condition has made false.

title: Syntax for stopping loop until the condition has made false

Answers: 2

body:
Your code doesn't make sense. You have a `while (1)` statement, which will run forever. Inside the body of that statement, you never change the value of `temp`.

An Arduino sketch's `loop()` function runs continuously. You should not have a `while (1)` loop inside your loop function. You should have a loop function something like this:

    void loop() {
      temp = //read a temp value somehow
      if(temp>=0&&temp<=20)
      {
        digitalWrite(2,HIGH);
      }
      else if (temp>=20&&temp<=30)
      {
        digitalWrite(1,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(1,LOW);
      }
    }

With that loop function you would fetch a new value of temp on each pass through the loop, then decide what LEDs to light.

body:
You don't want to stop the loop! You want it to run fast and often.

Eventually you want it to not change the current state of a LED, but in your case, I rather do not see enough defined states of LEDs.

>I want to first ON LED1 then ON LED2 then OFF LED1"

if `then` means an amount of time, remember that loop runs fast and does not take time by itself. You will have to notice the starting point in time and compare that with the current time and your desired intervals. (And you do not mention what should happen to LED2 after the second _then_ )

    const unsigned int LED1_DURATION=500;
    const unsigned int LED3_DURATION=1000;
    bool c2 = false;  // true while condition2 is met
    unsigned long start2;  // time when condition2 starts
    void loop() {
      int temp = analogRead(A0); //read a temp value somehow
      if(temp<=20)
      {
        digitlaWrite(1, LOW);
        digitalWrite(2,HIGH);
        digitlaWrite(3, LOW);
        c2 = false;
      }
      else if (temp >20 && temp <= 30)
      {
         digitalWrite(2, LOW);

         if (c2 == false) { c2 = true; start2=millis(); } // detect start time

         if ((millis() - start2 < LED1_DURATION) ||
             (millis() - start2 > LED3_DURATION)   )
              digitalWrite(1,HIGH);
         else digitalWrite(1, LOW);

         if ((millis() - start2 > LED1_DURATION) &&
             (millis() - start2 < LED3_DURATION)    )
              digitalWrite(3,HIGH);
         else digitalWrite(3,LOW);
      }
      else
      {
        digitlaWrite(1, LOW);
        digitalWrite(2, LOW);
        digitlaWrite(3, LOW);
        c2 = false;
      }
    }

This code contains a couple of guesses about states you did not mention, and a slightly different behavior (sorry), but I hope you get an idea...


body:
is there a way that i can declare gpio6 (CLK) as an input without getting a wdt reset?  I'm somewhat new to circuitry, but my boss wants to use it(GPIO6) to talk with external devices.  I have more pictures of the schematics if you think that it would help.[![enter image description here][1]][1]

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

title: nodemcu GPIO6 clock

Answers: 2

body:
No. There is no way you can use it (or not without a lot of messing around...).

According to the [ESP8266 GPIO Reference Guide](https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/):

> GPIO6 to GPIO11 are usually connected to the flash chip in ESP8266 boards. So, these pins are not recommended to use.

If you mess with those pins you won't be able to access the flash chip - and that means that you can't run code. And of course that means that the watchdog then times out.

I say that you can't "without a lot of messing around", because theoretically it *could* be possible if you had a function resident in RAM which reconfigured the pins, then did whatever was needed with them (taking into account the fact that there's a flash chip connected there...), then afterwards reconfigure the pins back to working in XIP SPI Flash mode.  But that's not something I would like to even contemplate doing.

body:
No you can't.
Refer to this: https://tttapa.github.io/ESP8266/Chap04 - Microcontroller.html

However as that article states there is a dedicated SPI set of pins on the esp8266 so you should be able to use that?

From your circuit diagram I see this might not be an option for you as you seem to have most of the pins allocated to a different function.

Your best and most robust solution would probably be to have a separate microcontroller chip handling your I2C and SPI requirements, using the Esp8266 UART functionally to provide your wireless capabilities.

As a side note why do you have so many clock lines?


body:
I want to read and writ data on Google sheets using ESP8266 WIfi Nodemcu and I'm able to do it but the time interval between two writing row is 3 seconds which is too much. I can read data but I am able to read only the first row not any other rows i am not able to read even changing the URL parameters.

Here is My Code -

<pre>
#include "ESP8266WiFi.h"
#include "HTTPSRedirect.h"
#include "DebugMacros.h"

// Fill ssid and password with your network credentials

const char* ssid = "Leobotics";

const char* password = "leobotics123";

int sheetHumid = 1;

int sheetTemp  = 2;

int sheetaqu   = 3;

String readaqu = "";

const char* host = "script.google.com";

// Replace with your own script id to make server side changes

const char *GScriptId = "AKfycbyu_JnX7F29Ea5cZUy7HdsFbv9W5UmedmNbhTwt5tznwRUiQhYS";

const int httpsPort = 443;

// echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout

const char* fingerprint = "ED:83:75:6B:83:FE:01:DE:BA:72:84:05:71:FA:CE:54:FB:6E:23:CA";

//const uint8_t fingerprint[20] = {};

// Write to Google Spreadsheet

String url = String("/macros/s/") + GScriptId + "/exec?value=Hello";

// Fetch Google Calendar events for 1 week ahead

String url2 = String("/macros/s/") + GScriptId + "/exec?cal";

// Read from Google Spreadsheet

String url3 = String("/macros/s/") + GScriptId + "/exec?read";

String payload_base =  "{\"command\": \"appendRow\", \
                    \"sheet_name\": \"Sheet1\", \
                    \"values\": ";
String payload = "";

HTTPSRedirect* client = nullptr;

// used to store the values of free stack and heap
// before the HTTPSRedirect object is instantiated
// so that they can be written to Google sheets
// upon instantiation

unsigned int free_heap_before = 10;

unsigned int free_stack_before = 20;

void setup() {

  Serial.begin(115200);

  Serial.print("Connecting to wifi: ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");

//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());

  // Use HTTPSRedirect class to create a new TLS connection

  client = new HTTPSRedirect(httpsPort);

  client->setInsecure();

  client->setPrintResponseBody(true);

  client->setContentTypeHeader("application/json");

  Serial.print("Connecting to ");

  Serial.println(host);

  // Try to connect for a maximum of 5 times
  bool flag = false;

  for (int i=0; i<5; i++){

    int retval = client->connect(host, httpsPort);

    if (retval == 1) {

       flag = true;

       break;
    }

    else

      Serial.println("Connection failed. Retrying...");
  }

  if (!flag){

    Serial.print("Could not connect to server: ");

    Serial.println(host);

    Serial.println("Exiting...");

    return;
  }

}

void loop() {

  datasend();

  static int error_count = 0;

  static int connect_count = 0;

  const unsigned int MAX_CONNECT = 20;

  static bool flag = false;

  if (!flag){

    client = new HTTPSRedirect(httpsPort);

    client->setInsecure();

    flag = true;

    client->setPrintResponseBody(true);

    client->setContentTypeHeader("application/json");

  }

  if (client != nullptr){

    if (!client->connected()){

      client->connect(host, httpsPort);

      payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

      client->POST(url2, host, payload, false);

    }
  }

  else{

    DPRINTLN("Error creating client object!");

    error_count = 5;

  }

  if (connect_count > MAX_CONNECT){

    connect_count = 0;

    flag = false;

    delete client;

    return;

  }

  Serial.println("GET Data from cell 'A1':");

  if (client->GET(url3, host)){

    ++connect_count;

    payload = payload_base + "\"" + readaqu + "," + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

    Serial.println("RECIEVED DATA IS GIVEN BELOW   ");

    Serial.println("                              ");

    Serial.println("1");

    Serial.println(readaqu);

    Serial.println("2");

    Serial.println(sheetaqu);

    Serial.println("3");

    Serial.println(sheetTemp);

    Serial.println("4");

    Serial.println(sheetHumid);

    Serial.println("                              ");
    Serial.println("RECEIVE DATA PRINT IS OVER  ");

    sheetaqu ++;

    sheetTemp ++;

    sheetHumid ++;

  }
  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  Serial.println("POST append memory data to spreadsheet:");

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  if(client->POST(url2, host, payload)){

    ;
  }

  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  if (error_count > 3){

    Serial.println("Halting processor...");

    delete client;

    client = nullptr;

  }

  delay(4000);

}

void datasend()

{
   // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  // Note: setup() must finish within approx. 1s, or the the watchdog timer
  // will reset the chip. Hence don't put too many requests in setup()
  // ref: https://github.com/esp8266/Arduino/issues/34

  Serial.println("\nGET: Write into cell 'A1'");

  Serial.println("=========================");

  // fetch spreadsheet data

  client->GET(url, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nGET: Fetch Google Calendar Data:");

  Serial.println("================================");

  // fetch spreadsheet data

  client->GET(url2, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nSeries of GET and POST requests");

  Serial.println("===============================");

  // delete HTTPSRedirect object

  delete client;

  client = nullptr;
}
</pre>

title: Reading Data from Google Sheets using Nodemcu

Answers: 1

body:
I think you'll need to modify your Google Script for that Sheet so that whatever function you are invoking to GET row data takes in an additional parameter for the row value.

Then just add the Javascript logic within that function for retrieving the data at that passed-in row index to be returned.

Does that make sense?


body:
I build something like a flashlamp with different modi. From the hardware site it's quite simmilar to the Nanjg105c.
There is a Attiny85 which generates a PWM signal to an AMC7135.

I have one push button, if I click it the Attiny go to sleep, if I hold the button the Attiny changes his mode.
[![enter image description here][1]][1]
For checking the battery voltage I use the watchdog timer to make the ADC conversion every 8sec.

        #include "OneButton.h"
    #include <avr/sleep.h>               // Sleep Modes
    #include <avr/power.h>              // Power management
    #include <avr/wdt.h>              // Watchdog Timer
    #include <util/delay.h>

    #define mid 4000                // BAttery Level Mid
    #define low 3200                // Battery Level low, flash and start dimming the Led
    #define crit 2600               // Battery Level critical, shut down

    const byte LEDr = 1;              // pin 1
    const byte LEDw = 4;              // pin 4
    const byte ModeNr = 3;
    volatile bool WDR_flag = false;
    bool PWR_flag = false;

    OneButton button1(2, true);
    int count = 1;
    int flag = 0;
    long Vcc;
    int PWMr = 255;
    int PWMw_l = 50;
    int PWMw_h = 255;

    ISR(PCINT0_vect)
    {
        // do something interesting here
    }

    ISR(WDT_vect){
      WDR_flag=true;
     }

    void setup()
    {
        pinMode(3, OUTPUT);
        pinMode(LEDr, OUTPUT);            // turn the LED on (HIGH is the voltage level)
        pinMode(LEDw, OUTPUT);
        digitalWrite(LEDr, HIGH);           // turn the LED on (HIGH is the voltage level)
        digitalWrite(LEDw, HIGH);
        delay(1000);
        button1.attachClick(sleep);
        button1.attachLongPressStart(changeMode);
        WDT_on();
    }

    void loop()
    {
      uint8_t i = 0;
        button1.tick();               // keep watching the push buttons:
      if(WDR_flag == true){           // do every 8s
        WDR_flag = false;           //reset WDT Flag
        digitalWrite(3, HIGH);      //debug with third LED
        delay(250);
        digitalWrite(3, LOW);
        WDT_off();
        //ADC_on();
        /*Vcc = readVcc();            //read Battery voltage
        if(Vcc < low && count == 3){
          if(PWMw_h <= PWMw_l){       //change Mode to low when PWM output is smaler then low PWM
            count = 2;
          }else
        {
        i = 0;
            while (i++<3 && PWR_flag == false) {         //flash 3 times the red LED befor dimm the white LED
              analogWrite(LEDr, PWMr);
              _delay_ms(500);
              digitalWrite(LEDr, LOW);
              _delay_ms(250);
          PWR_flag = true;
            }
          PWMw_h = PWMw_h / 2;        //halve the PWM output of the white LED
          }
          if(Vcc <= crit){          //go to sleep when Battery is empty
            sleep();
          }
        }
        if(Vcc < low && count == 1){
          i = 0;
          while (i++<3) {
            digitalWrite(LEDr, LOW);
            _delay_ms(250);
            analogWrite(LEDr, PWMr);
            _delay_ms(500);
            }
          PWMr = PWMr / 2;
          if(Vcc <= crit){
            sleep();
          }
        }*/
        //ADC_off();                //save power
        WDT_on;                 //start watchdog again

      }
      switch (count) {
        case 1:                 //Mode red LED
        analogWrite(LEDr, PWMr);
        digitalWrite(LEDw, LOW);
        break;
      case 2:                   //low Mode white LED
        digitalWrite(LEDr, LOW);
        analogWrite(LEDw, PWMw_l);
        break;
      case 3:                   //high Mode white LED
        digitalWrite(LEDr, LOW);
        analogWrite(LEDw, PWMw_h);
        break;
      }
    }

    void sleep()                  // This function will be called when the button1 was pressed 1 time
    {
        digitalWrite(LEDr, LOW);
        digitalWrite(LEDw, LOW);
        //prepare sleep
        WDT_off();
        GIFR |= bit(PCIF);              // clear any outstanding interrupts
        GIMSK |= _BV(PCIE);             // Enable Pin Change Interrupts
        PCMSK |= _BV(PCINT2);             // Use PB2 as interrupt pin
        ADC_off();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

        sleep_enable();               // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
        sei();                    // Enable interrupts
        sleep_cpu();                // sleep

        cli();                    // Disable interrupts
        PCMSK &= ~_BV(PCINT2);            // Turn off PB2 as interrupt pin
        sleep_disable();              // Clear SE bit
        WDT_on();

        flag = 1;                 //set flag, uc was in sleepmode before
    }

    void changeMode()               // This function will be called once, during pressed for a long time.
    {
        if (flag == 1) {
            flag = 0;
        }
        else {
            if (count < ModeNr) {
                count++;
            }
            else {
                count = 1;
            }
        }
    }

    void WDT_on() {
      // Setup watchdog timer to only interrupt, not reset
      cli();                    // Disable interrupts
      wdt_reset();                // Reset the WDT
      WDTCR |= (1 << WDCE) | (1 << WDE);       // Start timed sequence
      WDTCR = (1 << WDIE) | (1 << WDP3) | (1<<WDP0);      // Watchdog cycle = 8 s
      //WDTCR = (1 << WDIE);             // Watchdog Interrupt enable
      sei();                    // Enable interrupts
    }

    void WDT_off(){
      cli();                    // Disable interrupts
      wdt_reset();                // Reset the WDT
      MCUSR &= ~(1<<WDRF);            // Clear Watchdog reset flag
      WDTCR |= (1<<WDCE) | (1<<WDE);        // Start timed sequence
      WDTCR = 0x00;               // Disable WDT
      sei();                    // Enable interrupts
    }

    void ADC_on() {
      ADCSRA = (1 << ADEN );            // ADC power on
    }

    void ADC_off() {
      ADCSRA &= ~(1<<7);              //ADC off
    }

    long readVcc() {
      // Read 1.1V reference against AVcc
      // set the reference to Vcc and the measurement to the internal 1.1V reference

      ADMUX = _BV(MUX3) | _BV(MUX2);
      delay(2);                  // Wait for Vref to settle
      ADCSRA |= _BV(ADSC);              // Start conversion
      while (bit_is_set(ADCSRA,ADSC));        // measuring

      uint8_t low_adc  = ADCL;              // must read ADCL first - it then locks ADCH
      uint8_t high_adc = ADCH;              // unlocks both

      long result = (high_adc<<8) | low_adc;

      result = 1126400L / result;           // Calculate Vcc (in mV); 1126400 = 1.1*1024*1000
      int x = 0;
      /*while (x++<2) {         //debug with third LED
              digitalWrite(3, HIGH);
              _delay_ms(500);
              digitalWrite(3, LOW);
              _delay_ms(250);
            } */
      return result;                // Vcc in millivolts
    }

my problem is that the watchdog fires only once. after putting the attiny to sleep the watchdog fires also only once.

I think the problem is in the WDT_off() function...

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

title: Attiny85 Watchdog fires only once

Answers: 1

body:
The line below lacks parens `()` to make it a function call; as it stands, it's not actually calling `WDT_on`.

    WDT_on;                 //start watchdog again

should be:

    WDT_on();                 //start watchdog again


body:
1) what is the max draw I can draw from NodeMCU V3 logic and 5v pins?
2) Also, I heard i draw with it more than 500mA, the PC USB port stops working. Is that information actual? Because USB 3 port has 900mA and USB 2 had 500mA max

title: NodeMCU max draw

Answers: 1

body:
for ESP8266 (which your NodeMCU is based upon) , the maximum current is about 20mA sinking and 12mA sourcing per [single] pin. so the maximum current of all GPIOs together is a lot lower than the 500mA USB limits.

you have to use external drivers (transistors, MOSFETs) for that purpose.

**Sink current**: the current which is provided when you pull the pin LOW. e.g. when you provide GND for the cathode of an LED. (the Anode is connected to VCC).

**Source current**: the current which is provided when you pull the pin HIGH. e.g. when you provide VCC for the anode of an LED. (the cathode is connected to GND).

*the difference is for different internal resistance for identical N-MOS/P-MOS, due to their structure. that's why many devices like 7segment drivers, or motor drivers supply GND for the Load (common anode drivers) instead of VCC.*


body:
The sketch rotates servo back and forth with buttons.
When I rotate servo MG 995/996R 2-4 times Arduino stops working. Its voltage step-down transformer switches from ~9V to ~3.7V which is not enough for Arduino. To make it work again, I must turn off-on the device.

There is no such a glitch with smaller servos such as SG90.

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

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

title: Arduino stops working when servo makes a few rotations

Answers: 1

body:
[Ground loops][1] can be bad.  Do follow up as suggested in the comments regarding ensuring the power supply grounds are the same. To be specific, connecting the power supply grounds through the Arduino is a bad idea! The trace size should not be assumed adequate for the unknown amount of current passing between the ground outputs of the power supplies.  And a voltage potential can develop causing the processor to behave unexpectedly or worse burn out components.

Also, consider that some Arduino platforms regulate power to 5 volts on the board and that many servos run fine at 5 volts. If this is true here, you could greatly simplify and possibly solve the describe problem by using a single 5 volt power supply.

Lastly, ensure there is a pull up on the 2 inputs connected to the (assumed) normally-open-momentary-contact switches.  There are none in the diagram.  So it is assumed pull ups have been activated in the code such as explained [here][2].

  [1]: https://en.wikipedia.org/wiki/Ground_loop_(electricity)
  [2]: https://www.arduino.cc/en/Tutorial/InputPullupSerial