message:
how to break out servo.write(angle) after it reach the angle?

I used a servo as a grabber so I don't know the angle I need specifically.I need it to break the `serve.write(angle)` when the grabber holds something.
I used a simple code

    #include <Servo.h>
    Servo myservo;
    void setup() {
      myservo.attach(9);
    }
    void loop() {
      myservo.write(100);
      delay(500);
      myservo.write(50);
      delay(500);
    }
when it holds anything it deos not return to the small angle until I remove the obstacle from its way.

body:
You change the angle in small increments until the sensor triggers:

    bool closing = false;
    bool openeing = false;
    int angle;

    void loop(){

        //read touchSensor

        if(sensorHit){
            closing  = false;
        }
        if(closing){
            if(angle <= minAngle) closing = false;
            angle -= 1;
            myservo.write(angle);

        }

        if(opening){
            if(angle >= maxAngle) opening = false;
            angle += 1;
            myservo.write(angle);

        }

    }

The to start moving the grasper you set `opening` or `closing` to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.


sender: user

message:
unable to find string literal operator 'operator"" stylesheet'

I am new to programing in C and I get this error:

    unable to find string literal operator 'operator"" stylesheet'.

I am making a website for NodeMCU 0.9. My code:

     String message2 = "<!DOCTYPE html>";
          message2 += "<head>";
          message2 +=  "<title>Bootstrap Example</title>";
          message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
          message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
          message2 +=  "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>";
          message2 +=  "<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>";

sender: assistant

body:
I think I answered a similar question in a previous answer.

You use "before/after viewport in the fourth line, which should be prefixed with \ to make it an escape code to be treated like a " character instead of the start/end of a string.

Also afaik String is C++, as is the += operator, not C.

See [answer][1]

  [1]: https://arduino.stackexchange.com/questions/46508/nodemcu-and-expected-before-wrong


message:
Arduino classes, can't get property value

I have tried hard to make a stepper motor work with a class, but I can't get a property returning its value in a method. I get 0 (zero) instead of 26 (expected) from _stepPin.

I have tried this->_stepPin with no success.

Here is the code. See the comments inside.
<!-- language-all: lang-cpp -->

     class MKSStepperMotors {

       public:
        int _dirPin;
        int _stepPin;
        int _enablePin;

        MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

          int _dirPin = dirPin;
          int _stepPin = stepPin;
          int _enablePin = enablePin;

          //Habilitamos el motor
          pinMode(_enablePin, OUTPUT);
          digitalWrite(_enablePin, LOW);

          //Cambiamos la direccion y aumentamos la velocidad
          pinMode(_dirPin, OUTPUT);
          digitalWrite(_dirPin, LOW);

          // Le indicamos el pin de señal
          pinMode(_stepPin, OUTPUT);

        }

        void move(int steps, int stepDelay)
        {

          for (int x = 0; x < steps; x++) {
            Serial.println(_stepPin); //  <-- _stepPin is zero and not 26 as it should
            digitalWrite(_stepPin, HIGH); <-- _stepPin is zero and not 26 as it should
            delayMicroseconds(stepDelay);
            digitalWrite(_stepPin, LOW);  <-- _stepPin is zero and not 26 as it should
            delayMicroseconds(stepDelay);
          }
        }
    };

     MKSStepperMotors pedo(28, 26, 24);

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

     void loop() {

          pedo.move(3200,100);

    }

body:
When you put the type there, you are creating new variables.  SO in your constructor:

     MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

          int _dirPin = dirPin;
          int _stepPin = stepPin;
          int _enablePin = enablePin;

You start by creating three new variables with the same names as the member variables defined in the class.  Throughout the rest of the constructor those get used instead of the ones that are member variables.

You gotta lose the "int" there.

You also have another bug in there.  The constructor may run before the init function if one of these objects gets declared at global scope.  Things like digitalWite and pinMode aren't going to work yet in that case.  A constructor should just have code to initialize variables, it should never touch hardware.  The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.


body:
You have redeclared the class member fields in your constructor:

    class MKSStepperMotors {

       public:
        int _dirPin;
        int _stepPin;
        int _enablePin;

        MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

          int _dirPin = dirPin;
          int _stepPin = stepPin;
          int _enablePin = enablePin;
          ...
        }

The `int _dirPin = dirPin;` declares a local variable with the same name as your class member `_dirPin` and *shadows* it, hence your 3 class members never get initialized!

You should change your constructor as follows:

        MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

          _dirPin = dirPin;
          _stepPin = stepPin;
          _enablePin = enablePin;
          ...
        }

Or better, use standard C++ constructor initialization:

        MKSStepperMotors(int dirPin, int stepPin, int enablePin)
        :_dirPin(dirPin),_stepPin(stepPin),_enablePin(enablePin) {
          ...
        }

In this latter example, you don't need to initialize your class members in the constructor body as they are already initialized before the body gets executed (this is idiomatic C++ usage).


message:
How do I connect a temperature and heartbeat sensor to an Arduino Uno?

I have been using a temperature sensor and heartbeat sensor separately and I am trying to code for temperature and heartbeat sensors. How do I get its output on the Arduino IDE's Serial Plotter?

Code of temperature sensor:

<!-- language: lang-cpp -->

    int val;
    int tempPin = 1;

    void setup()
    {
      Serial.begin(9600);
    }
    void loop()
    {
      val = analogRead(tempPin);
      float mv = ( val / 1024.0) * 5000;
      float cel = mv / 10;
      float farh = (cel * 9) / 5 + 32;

      Serial.print("TEMPRATURE = ");
      Serial.print(cel);
      Serial.print("*C");
      Serial.println();
      delay(1000);

      /* uncomment this to get temperature in farenhite
        Serial.print("TEMPRATURE = ");
        Serial.print(farh);
        Serial.print("*F");
        Serial.println();
      */
    }

body:
If you separate your code into functions you may understand what you want to do better.

In the listing above, you have code that reads the temp and prints the temp.  So creating two functions `ReadTemp()` and `ShowTemp()` will make the code in loop look cleaner and easier to read.  i.e.

    void loop()
    {
        const float cel = ReadTemp();
        DisplayTemp(cel);
        delay(1000);
    }

    float ReadTemp(void)
    {
        val = analogRead(tempPin);
        float mv = ( val/1024.0)*5000;
        float cel = mv/10;
        // float farh = (cel*9)/5 + 32;
        return cel;
    }
    void ShowTemp(const float& cel)
    {
        Serial.print("TEMPRATURE = ");
        Serial.print(cel);
        Serial.print("*C");
        Serial.println();
    }

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it.  If you create two functions `ReadHB()` and `ShowHB()` you will be able to easily add them to the above loop function.

I've never used the serial plotter, but if you wrap it in a function called `PlotTemp()` and `PlotHB()` then you can slot them in instead of the Show functions.


message:
SIM800L starts sending garbage values to Arduino after random interval

I have a [SIM800L][1] module connected to Arduino Mega's Serial3. SIM800L is powered by 4.2V power supply and I have put a voltage divider between Arduino's TX3 and SIM800L's RX so that the voltage in the line stays about 2V. The TX line of the module is directly connected to Arduino's RX3.

The problem is that when I try to communicate with the module it responds fine but after some AT commands the module starts panicking and start sending random garbage. The code I'm using is a simple Serial to Serial code :

    #include<SoftwareSerial.h>

    #define mySerial Serial3
    //SoftwareSerial mySerial(10, 11);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      mySerial.begin(38400);

    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }

Output :
[![enter image description here][2]][2]
[This is with serial monitor set to 115200 baud rate]

[![enter image description here][3]][3]
[The garbage values with serial monitor set to 9600 baud rate]

The solutions I have tried so far are :

1. Put a 220uF cap between SIM800L's VCC and GND. (a 470uF tantalum cap is already included on the module but still to be safe)

2. Tried various baud rates from 9600 to 115200 (the baud rate setting on the module is set to auto baud rate) but only 38400 works reliably.

3. Tried to pull the RX3 line up on Arduino with a 100k resistor so that it doesn't float.

4. Tried to put up to 5s delay between AT commands given to the module but it still goes into panic.

The thing I noticed is that if we enter some wrong command like ATD74xxxxxxxx (which calls a phone number) instead of with proper ending like ATD74xxxxxxxx; the module does the same thing which is spitting garbage values.

Can anybody help me with what is wrong with the module?

  [1]: https://robokits.co.in/wireless-solutions/gsm-gprs/sim800l-gprs-gsm-module-micro-sim-card-core-board-quad-band-ttl
  [2]: https://i.stack.imgur.com/qiixM.png
  [3]: https://i.stack.imgur.com/maG2d.png

body: I believe GSM modules needs about 2A current for few operations. One of them is calling. Are you providing proer current?


message:
SparkFun ESP8266 find out when on battery power and when charging

For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.

Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.

Is there a way to find out (in code) when the board switches from mains power to battery and back?

body:
You can implement this software if the voltage is different in both cases.

The voltage from the power supply should be higher than the voltage of the battery, but do not exceed the permissible values.

Then you can use [ESP.getVcc()][1] :

> ESP.getVcc() may be used to measure supply voltage. ESP needs to
> reconfigure the ADC at startup in order for this feature to be
> available. Add the following line to the top of your sketch to use
> getVcc:
>
> `ADC_MODE(ADC_VCC);`
>
> TOUT pin has to be disconnected in this mode.
>
> Note that by default ADC is configured to read from TOUT pin using
> analogRead(A0), and ESP.getVCC() is not available.

  [1]: https://github.com/esp8266/Arduino/blob/5b5ba1a6bea709bb9ba7e13621af44b5ff2f1e25/doc/libraries.rst


message:
Temperature Sensor not giving proper values

In my current project I am reading temperature through sensor which is having only two wires.

[![Temperature Sensor][1]][1]

To read sensor values, I have used below schematic which I have found on Arduino Project Hub site.

[![ds1820b connection][2]][2]

In my project I am using below Arduino program.

    #include <OneWire.h>
    #include <DallasTemperature.h>

    // Data wire is plugged into pin 2 on the Arduino
    #define ONE_WIRE_BUS 2

    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    void setup(void)
    {
      // start serial port
      Serial.begin(9600);
      Serial.println("Dallas Temperature IC Control Library Demo");

      // Start up the library
      sensors.begin();
    }

    void loop(void)
    {
      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      Serial.print(" Requesting temperatures...");
      sensors.requestTemperatures(); // Send the command to get temperatures
      Serial.println("DONE");

      Serial.print("Temperature is: ");
      Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
        // You can have more than one IC on the same bus.
        // 0 refers to the first IC on the wire
        delay(1000);
    }

After doing all this I am getting this output on serial monitor.

[![Result][3]][3]

At which step I am doing wrong?

  [1]: https://i.stack.imgur.com/BNsXK.jpg
  [2]: https://i.stack.imgur.com/BlXtc.jpg
  [3]: https://i.stack.imgur.com/WzMkp.png

body:
The -127 for your temperature reading is actually the error code for `DEVICE_DISCONNECTED_C`.

In the library's example code, they put an if that checks for this error code before printing the temperature:

    if(tempC != DEVICE_DISCONNECTED_C)
    {
      Serial.print("Temperature for the device 1 (index 0) is: ");
      Serial.println(tempC);
    }

Since your sensor has only 2 wires, according to Wikipedia, you need a capacitor to power the sensor:

> One distinctive feature of the bus is the possibility of using only two wires — data and ground. To accomplish this, 1-Wire devices include an 800 pF capacitor to store charge and power the device during periods when the data line is active.

This should hopefully resolve your issues.


message:
Arduino not adding decimals correctly on double variable

I have encountered a strange behavior today.
I can't understand why the sequence is altered after 26.1000.
I get a number 0.0001 less than the desired value (26.2124 instead of 26.2125).
I need precision and can't get it.

Here is the code:

    double _pos = 0;

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

    void loop() {
      _pos += (0.1125);
      Serial.println(_pos,4);
      while (_pos >26.5) delay(1);
    }

and here is the result

    0.1125
    0.2250
    0.3375
    0.4500
    0.5625
    0.6750
    0.7875
    0.9000
    1.0125
    1.1250
    1.2375
    1.3500
    1.4625
    1.5750
    1.6875
    1.8000
    1.9125
    2.0250
    2.1375
    2.2500
    2.3625
    2.4750
    2.5875
    2.7000
    2.8125
    2.9250
    3.0375
    3.1500
    3.2625
    3.3750
    3.4875
    3.6000
    3.7125
    3.8250
    3.9375
    4.0500
    4.1625
    4.2750
    4.3875
    4.5000
    4.6125
    4.7250
    4.8375
    4.9500
    5.0625
    5.1750
    5.2875
    5.4000
    5.5125
    5.6250
    5.7375
    5.8500
    5.9625
    6.0750
    6.1875
    6.3000
    6.4125
    6.5250
    6.6375
    6.7500
    6.8625
    6.9750
    7.0875
    7.2000
    7.3125
    7.4250
    7.5375
    7.6500
    7.7625
    7.8750
    7.9875
    8.1000
    8.2125
    8.3250
    8.4375
    8.5500
    8.6625
    8.7750
    8.8875
    9.0000
    9.1125
    9.2250
    9.3375
    9.4500
    9.5625
    9.6750
    9.7875
    9.9000
    10.0125
    10.1250
    10.2375
    10.3500
    10.4625
    10.5750
    10.6875
    10.8000
    10.9125
    11.0250
    11.1375
    11.2500
    11.3625
    11.4750
    11.5875
    11.7000
    11.8125
    11.9250
    12.0375
    12.1500
    12.2625
    12.3750
    12.4875
    12.6000
    12.7125
    12.8250
    12.9375
    13.0500
    13.1625
    13.2750
    13.3875
    13.5000
    13.6125
    13.7250
    13.8375
    13.9500
    14.0625
    14.1750
    14.2875
    14.4000
    14.5125
    14.6250
    14.7375
    14.8500
    14.9625
    15.0750
    15.1875
    15.3000
    15.4125
    15.5250
    15.6375
    15.7500
    15.8625
    15.9750
    16.0875
    16.2000
    16.3125
    16.4250
    16.5375
    16.6500
    16.7625
    16.8750
    16.9875
    17.1000
    17.2125
    17.3250
    17.4375
    17.5500
    17.6625
    17.7750
    17.8875
    18.0000
    18.1125
    18.2250
    18.3375
    18.4500
    18.5625
    18.6750
    18.7875
    18.9000
    19.0125
    19.1250
    19.2375
    19.3500
    19.4625
    19.5750
    19.6875
    19.8000
    19.9125
    20.0250
    20.1375
    20.2500
    20.3625
    20.4750
    20.5875
    20.7000
    20.8125
    20.9250
    21.0375
    21.1500
    21.2625
    21.3750
    21.4875
    21.6000
    21.7125
    21.8250
    21.9375
    22.0500
    22.1625
    22.2750
    22.3875
    22.5000
    22.6125
    22.7250
    22.8375
    22.9500
    23.0625
    23.1750
    23.2875
    23.4000
    23.5125
    23.6250
    23.7375
    23.8500
    23.9625
    24.0750
    24.1875
    24.3000
    24.4125
    24.5250
    24.6375
    24.7500
    24.8625
    24.9750
    25.0875
    25.2000
    25.3125
    25.4250
    25.5375
    25.6500
    25.7625
    25.8750
    25.9875
    26.1000
    26.2124
    26.3249
    26.4374
    26.5499

body:
I do not see any specific difference after 26.2124.

However, in your case you are using 6 digits (e.g. 26.5499). To use an unsigned long/uint32_t you can store easily 6 digits, but only using whole numbers.

However, by adding 1125 every time and dividing the result by 10,000.0 for printing you get exact results.

    unsigned long _pos = 0;

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

    void loop() {
      _pos += 1125;
      Serial.println((float) _pos / 10000.0,4);
      while (_pos > 265000) delay(1);
    }


body:
The number 0.1125 would written in binary as 0.0001110011001100..., with
an infinite repetition of “1100”. As the `float` data type has only
24 bits of precision, it can obviously not represent such a number.
Instead, when you write `0.1125` in code, you get the closest
representable number, namely 0.11249999701976776123046875, which is
0.00011100110011001100110011 in binary. Note that AVR-based Arduinos do
not really support double precision: you get a float32 whether you
declare a `float` or a `double`.

Furthermore, when you keep adding this number to itself, quite often the
sum is not a representable number. Thus, in addition to the initial
rounding error in the representation of 0.1125, you get an additional
rounding error with the addition. These errors accumulate and you end up
with a value that is significantly off what you expect.

You can avoid accumulating errors by working with integers, and
converting o `float` only when needed:

<!-- language: lang-c++ -->

    void loop()
    {
        static long count;
        count++;
        Serial.println(count * 0.1125, 4);
        while (count > 235) delay(1);
    }

Note that you still get two rounding errors: in the representation of
0.1125 and in the multiplication. But at least you are not accumulating
a large number of them.


body:
> I can't understand why the sequence is altered after 26.2124.

because floats / doubles are not precise representation of their respective values.


body:
The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.

There is no such thing as `double` on an 8-bit Arduino - it is only an alias for `float`. By using `double` you aren't gaining any more precision than using `float`.

Even `double` isn't perfectly precise. It's more precise than `float` (on systems that support `double`), but still far from precise.

People that care about specific levels of precision code using variables of that precision. That's called using *fixed point* mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that *you* define it to be.

Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or *granularity* and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use `float`: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.


message:
Broken serial connection corrupting Arduino values

I have a problem with my homemade fan speed controller powered by an Arduino Nano, which reads a value from Serial (Arduino serial monitor, or Processing sketch) and uses the 0~255 value to set a variable `fanspeed1` to set a PWM pin to control the fan speed.

The problem is when I close the Processing sketch, or the Arduino serial monitor, `fanspeed1` is changed to max value (the fan speeds up to full speed).

I would like to send serial to set the value and then close the serial monitor, or Processing sketch and the value of `fanspeed1` should not change.

If I need to post some code I can simplify my sketch down to a send serial, receive serial, make pin pwm = serial(0~255), but I am guessing there is a simple solution to this unfindable with my googling.

Help please, these fans need controlling...

body:
You could consider writing/reading the value to/from the EEPROM.

http://arduino.cc/en/Reference/EEPROM

This allows the board to be reset, or even turned off, and retain the value previously set.  What you would be doing is saving the value to the internal memory of the Arduino.  This is resettable and persistent over a "reboot".

Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

> Syntax
>
> EEPROM.write(address, value)
>
>EEPROM.read(address)
>
>EEPROM.update(address, value)

For objects:
>EEPROM.put(address, data)
>
>EEPROM.get(address, data)


message:
Emergency stop button for arduino mega code and circuit attached

I am trying to control steppers with pushbuttons and sensors.I want to add one more Pushbutton so that I can press it to stop the circuit and code running if something goes wrong in between.
Below is the code I am using to run the steppers:

<!-- language: lang-cpp -->

    int dirpin_T1 = 26;
    int dirH_T1 = 28;
    int steppin_T1 = 30;
    int dirpin_F1 = 5;
    int dirH_F1 = 6;
    int steppin_F1 = 7;

    int PB17ACW = 23;
    int PB17ACCW = 22;
    int PB17BCW = 25;
    int PB17BCCW = 24;

    int S01 = 34; // SENSOR INPUTS
    int S02 = 35;
    int S03 = 36;
    int S04 = 37;

    void setup()
    {
      pinMode(dirpin_T1, OUTPUT);
      pinMode(dirH_T1, OUTPUT);
      pinMode(steppin_T1, OUTPUT);
      pinMode(dirpin_F1, OUTPUT);
      pinMode(dirH_F1 , OUTPUT);
      pinMode(steppin_F1, OUTPUT);

      pinMode(PB17ACW, INPUT_PULLUP);
      pinMode(PB17ACCW, INPUT_PULLUP);
      pinMode(PB17BCW, INPUT_PULLUP);
      pinMode(PB17BCCW, INPUT_PULLUP);

      pinMode(S01, INPUT);
      pinMode(S02, INPUT);
      pinMode(S03, INPUT);
      pinMode(S04, INPUT);
    }

    void loop()
    {
      if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == LOW)
      {
        // STOP MOTOR WHEN NO KEY PRESSED
      }

      // FOR FORWARD ROTATION
      if (digitalRead(PB17ACW) == HIGH &&  digitalRead(PB17ACCW) == LOW )
      {
        digitalWrite(dirpin_T1, LOW );     // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
        {
          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        }

        digitalWrite(dirpin_F1, LOW );     // Set the direction.
        digitalWrite(dirH_F1, LOW);
        delay(1000);
        do
        {
          digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        } while (digitalRead(S01) == LOW);

        delay(1000);

        digitalWrite(dirpin_T1, LOW );     // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
        {
          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        }
      }

      // FOR  BACKWARD ROTATION
      if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == HIGH)
      {
        digitalWrite(dirpin_T1, LOW );     // Set the direction.
        digitalWrite(dirH_T1, LOW);
        delay(1000);

        for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
        {
          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        }
        digitalWrite(dirpin_F1, LOW );     // Set the direction.
        digitalWrite(dirH_F1, HIGH);
        delay(1000);
        do
        {
          digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        } while (digitalRead(S02) == LOW);

        delay(1000);
        digitalWrite(dirpin_T1, LOW );     // Set the direction.
        digitalWrite(dirH_T1, HIGH);
        delay(1000);

        for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
        {
          digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
          digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
          delayMicroseconds(50);
        }
      }
    //WANT CODE TO STOP CODE ANYTIME I PRESS STOP BUTTON

    }

body:
The best option is to convert the `delay()` based code to a `millis()` based state machine. That way the code will never block and always be going through the loop and the place where you check wether that button was hit.

Then when that button is hit you transition to the E_STOP state which turns off all motors until the restart button is hit which goes to recalibrate the position if needed.

---

A more quick and dirty solution is to replace every every delay with

    unsigned long current = millis();
    while(milis() - current < delay){
        if(E_Stop()){
            stopped = true;
            return;
        }
    }

And add a if check to bail out to every loop.

     for (/*...*/)
      {
        //...
        delayMicroseconds(50);
        if(E_Stop()){
            stopped = true;
            return;
        }
      }

At the start of `loop()` you then add a

    if(stopped){
        //check for restart signal if true recalibrate otherwise return
    }


message:
Turning a motor on and a led at the same time for a given time period

I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.

At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.
<!-- language-all: lang-cpp -->

    // Program: Led drive using reflective optical sensor
    // Author: Arduino e Cia

    int outgoingsignal = 8 ; // Pin of led
    int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor
    int reading;      // Stores information about sensor reading
    int statusled = 0 ;
    int motorPin = 9;  // define the pin the motor is connected to
                       // (if you use pin 9,10,11 or 3you can also control speed)
                       // Stores led status (on / off)

    void setup ()
    {
      pinMode (outgoingsignal, OUTPUT); // Defines the led pin as
      pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
       pinMode(motorPin, OUTPUT);
    }

    void loop ()
    {
      // Le the sensor pin information
      reading = digitalRead (pinsensor);
      if (reading != 1 ) // Checks if the object was detected
      {
        while (digitalRead (pinsensor)!= 1)
        {
         delay (100);
        }

        statusled =! statusled;
        // Reverses the status of the led (on / off)

        // Turns on or off the led as "statusled"
        digitalWrite (outgoingsignal, statusled);
      motorOnThenOffWithSpeed(); }

    }
    void motorOnThenOffWithSpeed(){

      int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed)
      int onTime = 2500;  //the number of milliseconds for the motor to turn on for

      int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed)
      //int offTime = 1000; //the number of milliseconds for the motor to turn off for

      analogWrite(motorPin, onSpeed);   // turns the motor On
      delay(onTime);                    // waits for onTime milliseconds
      analogWrite(motorPin, offSpeed);  // turns the motor Off
     // delay(offTime);                   // waits for offTime milliseconds
    }

body: If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.


body:
Easy three steps:

1. Connect the led to the motor control pin (via some means to limit the current).

2. Program your motor control pin to turn it on or off as you so desire.

3. Sit back and enjoy.


message:
Arduino an sparkfun microled problem

In on of my projects i am using sparkfuns MicrOLED library. Downloaded it from github, installed as usual but no code calling that library compiles. Error is SPF_MicrOLED.h no such file or directory.

It is strange as the library is installed, example sketches are in the examples menu but they don`t want to compile ether, same error. Not sure what to do. Tried also to rename microled library folder but same error.

body:
>Error is SPF_MicrOLED.h no such file or directory.

That is to be expected because the [library](https://github.com/sparkfun/SparkFun_Micro_OLED_Arduino_Library) doesn't contain a file named SPF_MicrOLED.h.

It does contain a file named [SFE_MicroOLED.h](https://github.com/sparkfun/SparkFun_Micro_OLED_Arduino_Library/blob/master/src/SFE_MicroOLED.h). Use the correct filename in your `#include` and the problem will be solved.


message:
Clamping 9-volt input to 8-volt?

Have a DFRobot Arduino Pro Mini.

Seems odd to me, but according to their specs the voltage regulator on board cannot handle more than 8-volt input. I can find no documentation, or have they answered me concerning what specific regulator they use on the board.

I would like to be able to run this board from a 9-volt battery. What is the best / most eloquent way to do this, keeping the smallest component footprint for a home etched board ?

An additional regulator ?? Could a diode clamp the voltage down ?

Many thanks in advance.

body:
I would make sure first that their claim ofb8v max is right. Look up the datasheet for the regulator and go from there.

If you have to go with 8v max, put a diode or two, or an led in serial should work most of the time.

For those where such an approach doesn't work, wire up an external regulator.


message:
Digital Inputs have gone crazy

My digital inputs are behaving as if they were floating, even though I've properly connected them with a resistor.  I've tried the pull-down configuration pictured below, as well as a internal pull-up.

By using digitalRead() and serial.pintln() I've collected the state of each input tested (0 to 10) and they all do the same: random 0's and 1's.  When I change a state (press or release the button), they seem to work for a second or two, then, they go crazy again.  Sometimes, they even work backwards (showing HIGH when it's supposed to be LOW) for a couple of seconds.

Is my two-day old Arduino UNO fried?

[![Arduino UNO diagram][1]][1]

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

body:
Solved it, but here is the solution, so there is an answer available for anyone who might encounter the same problem...

Quality check your protoboards.  This is making me feel stupid.  The protoboard I used had a faulty connection on the blue line I was using, causing an inevitable floating input.  So relieved I found the problem, and yet so annoyed!

Take care you all.


message:
How do I send tweets with flame sensor and ESP8266?

I want to send tweets with flame sensor and ESP8266. My flame sensor is digital. I think everything is good but it doesn't send.

This is my code:
<!-- language-all: lang-cpp -->

    #define ag_ismi "SSID"
    #define ag_sifresi "PASSWORD"
    #define IP "184.106.153.149" //thingspeak.com IP address

    int sensorPin = 8;
    int smoke_level = HIGH;

    void setup() {
      pinMode(sensorPin, INPUT);
      Serial.begin(115200);
      Serial.println("AT");
      delay(3000);
      if (Serial.find("OK")) {
        Serial.println("AT+CWMODE=1");
        delay(2000);
        String baglantiKomutu = String("AT+CWJAP=\"") + ag_ismi + "\",\"" + ag_sifresi + "\"";
        Serial.println(baglantiKomutu);
        delay(5000);
      }
    }

    void loop() {
      smoke_level = digitalRead(sensorPin); // Arduino reads the value from the smoke sensor
      Serial.println(smoke_level);// prints just for debugging purposes, to see what values the sensor is picking up
      if (smoke_level == HIGH) {
        // if smoke level is greater than 500, the buzzer will go off
        sicaklik_yolla();
      }
      delay(20000);
    }
    void sicaklik_yolla() {
      Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
      delay(1500);
      String tweet = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
      tweet += "Host: api.thingspeak.com\n";
      tweet += "Connection: close\n";
      tweet += "Content-Type: application/x-www-form-urlencoded\n";
      tweet += "Content-Length:67\r\n\r\napi_key=";
      tweet += String("MY API KEY");
      tweet += String("&status=");
      tweet += String("MY TWEET TEXT");
      Serial.print("AT+CIPSEND=");
      delay(100);
      Serial.println(tweet.length());
      if (Serial.find(">")) {
        Serial.println(tweet);
        Serial.println("AT+CIPCLOSE=0");
        delay(100);
      } else {
        Serial.println("AT+CIPCLOSE=0");
      }
    }

This schema is old. Sensor connected to pin 8.

[![old connection][1]][1]

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

body:
I guess your baud rate and network connection with the wifi module is working fine. Have to say that it is a bit difficult to get the data sent to ThingSpeak with ESP8266. I actually did some experiments to get the data sent. The problem is actually with the delay. Adding a delay of 5000 ms between sending the tweet length and the tweet content sorts it out. You can use GET format. Check out [this Instructable][1].

  [1]: http://www.instructables.com/id/Distant-Weather-Monitoring-Using-Arduino-and-ESP82


message:
Arduino Nano problems with ESP8266

this is my first post here because I'm a bit lost at the moment.
I currently have my ESP8266-01 hocked up to the Nano like this:

[![wiring][1]][1]

The issue I'm having is that it won't even turn on, only when I'm using the 3.3V pin the red led on the ESP8266 turns on. If connected to 3.3V and I connect the CH_PD pin to 3.3V aswell, the blue led flashes 2-3 times and then the ESP8266 turns off.

I hope someone is able to help me

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

body:
You need to supply power to the ESP to make it turn on.  What you have done at the moment is got the ESP to supply 3.3V to the level shifter, which you need to do.

You need to supply 3.3V to the ESP from somewhere other than the Arduino, it doesn't have the current necessary.


body:
You have a level shifter, not a voltage regulator. That's fine for switching logic levels of different voltages, but it cannot supply a regulated reduced voltage from one side to the other.

All it does is allow one voltage to switch another on and off in a bi-directional manner.

And those voltages have to come from somewhere for it to switch. You are already giving it the 5V from the Arduino, but you're not giving it the 3.3V for it to switch from anywhere - and so there is no 3.3V - not for the level shifter, nor for the ESP8266.

You need to find some way of getting 3.3V with enough current to power the ESP8266 side of the circuit.


message:
esp8266 not defined in scope while using in class

Below code was working fine without using classes, after using class an error pops up: esp8266 is not defined in this scope

<!-- language: lang-cpp -->

    #include<SoftwareSerial.h>
    #include<ArduinoJson.h>
    #include<Wire.h>
    #include<LCD.h>
    #include<LiquidCrystal_I2C.h>
    #include<SPI.h>

    #define DEBUG true
    // Housekeeping stuff for LCD display
    #define I2C_ADDR    0x3F
    #define BACKLIGHT_PIN     3
    #define En_pin  2
    #define Rw_pin  1
    #define Rs_pin  0
    #define D4_pin  4
    #define D5_pin  5
    #define D6_pin  6
    #define D7_pin  7
    LiquidCrystal_I2C
    lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

    class baseFunctions {
      public:
        baseFunctions() {
          Serial.begin(115200); // Housekeeping stuff
          esp8266.begin(115200);  // Housekeeping stuff
          sendData("AT+RST\r\n", 2000, DEBUG); // reset module

          // Code for display
          lcd.begin (16, 2);
          lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
          lcd.setBacklight(HIGH); // Switch on the backlight
          lcd.home (); // go home
          lcd.print("In development");

          pinMode(8, OUTPUT);
        }

        String sendData(String command, const int timeout, boolean debug) {
          String response = "";
          esp8266.print(command); // send the read characte to esp8266
          long int time = millis();
          while ( (time + timeout) > millis() ) {
            while (esp8266.available()) {
              // The esp has data so display its output to serial window
              char c = esp8266.read(); // read the next character
              response += c;
            }
          }
          if (debug) {
            Serial.print(response);
          }
          return response;
        }

        void connectToWifi() {
          sendData("AT+CWMODE=1\r\n", 3000, DEBUG); // Configure as clint
          sendData("AT+CWJAP=\"moto g\", \"hvats555\"\r\n", 5000, DEBUG);  // Connects to wifi
        }

        String fetchJson() {
          StaticJsonBuffer<200> jsonBuffer;
          char json[] = "{\"power\":\"high\"}";
          JsonObject& root = jsonBuffer.parseObject(json);

          const char* power = root["power"];
          return power;
        }
    };

    void setup() {
      baseFunctions go;
    }

    void loop() {
    }

Here is the error

<!-- language: lang-none -->

    exit status 1
    'esp8266' was not declared in this scope

body:
When you added the class you obviously deleted/moved code into it from elsewhere.

One bit of code that you missed in that moving around will be the code that declares what `esp8266` is:

    SoftwareSerial esp8266(2,3); // for example

Find that in your original code and copy it across.


message:
Arduino uno with microled library; draw shaped

I am really sorry for bothering you but i need help, again, with my arduino code. I am still learning so i make mistakes.

I am trying to draw shaped on i2c screen with Microled library. My code isn`t compiling, error is Unexpected declaration before { . That is one problem. I would also like to draw rectangle without edges, both empty and filled but i am struggling how to declare it, should i declare 4 lines or maybe display bitmap.

Anyway my code is here

    #include <Arduino.h>
    #include <Wire.h>
    #include <MicroLCD.h>

    LCD_SH1106 lcd; /* for SH1106 OLED module */
    //LCD_SSD1306 lcd; /* for SSD1306 OLED module */

    static const PROGMEM uint8_t smile[48 * 48 / 8] = {
    0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0xE0,0xF0,0xF8,0xF8,0xFC,0xFC,0xFE,0xFE,0x7E,0x7F,0x7F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x7F,0x7F,0x7E,0xFE,0xFE,0xFC,0xFC,0xF8,0xF8,0xF0,0xE0,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0xC0,0xF0,0xFC,0xFE,0xFF,0xFF,0xFF,0x3F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x01,0x03,0x07,0x0F,0x1F,0x3F,0xFF,0xFF,0xFF,0xFE,0xFC,0xF0,0xC0,0x00,
    0xFE,0xFF,0xFF,0xFF,0xFF,0xFF,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x1F,0x1F,0x1F,0x3F,0x1F,0x1F,0x02,0x00,0x00,0x00,0x00,0x06,0x1F,0x1F,0x1F,0x3F,0x1F,0x1F,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
    0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xE0,0x00,0x00,0x30,0xF8,0xF8,0xF8,0xF8,0xE0,0xC0,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xC0,0xE0,0xF8,0xF8,0xFC,0xF8,0x30,0x00,0x00,0xE0,0xFF,0xFF,0xFF,0xFF,0xFF,0x7F,
    0x00,0x03,0x0F,0x3F,0x7F,0xFF,0xFF,0xFF,0xFC,0xF8,0xF0,0xE1,0xC7,0x87,0x0F,0x1F,0x3F,0x3F,0x3E,0x7E,0x7C,0x7C,0x7C,0x78,0x78,0x7C,0x7C,0x7C,0x7E,0x3E,0x3F,0x3F,0x1F,0x0F,0x87,0xC7,0xE1,0xF0,0xF8,0xFC,0xFF,0xFF,0xFF,0x7F,0x3F,0x0F,0x03,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x07,0x0F,0x1F,0x1F,0x3F,0x3F,0x7F,0x7F,0x7E,0xFE,0xFE,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFC,0xFE,0xFE,0x7E,0x7F,0x7F,0x3F,0x3F,0x1F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
    };

    static const PROGMEM uint8_t tick[16 * 16 / 8] =
    {0x00,0x80,0xC0,0xE0,0xC0,0x80,0x00,0x80,0xC0,0xE0,0xF0,0xF8,0xFC,0x78,0x30,0x00,0x00,0x01,0x03,0x07,0x0F,0x1F,0x1F,0x1F,0x0F,0x07,0x03,0x01,0x00,0x00,0x00,0x00};

    static const PROGMEM uint8_t cross[16 * 16 / 8] =
    {0x00,0x0C,0x1C,0x3C,0x78,0xF0,0xE0,0xC0,0xE0,0xF0,0x78,0x3C,0x1C,0x0C,0x00,0x00,0x00,0x30,0x38,0x3C,0x1E,0x0F,0x07,0x03,0x07,0x0F,0x1E,0x3C,0x38,0x30,0x00,0x00};

    void setup()
    {
      delay(1000);
      delay(1000);
      lcd.clear();
      lcd.setCursor(40, 1);
      delay(500);
    }

    void line()
    {
    int x0 = 7; int y0 = 7;   // (x0,y0) = (7, 7)
    int x1 = 42; int y1 = 24; // (x1,y1) = (42, 24)
    oled.line(x0, y0, x1, y1);  // Draw a line from (x0,y0) to (x1,y1);
    oled.display(); // Draw to the screen
    }

    void rectangle()
    {
    int x0 = 7; int y0 = 5;
    int width = 24;
    int height = 13;
    oled.rect(x0, y0, width, height);
    oled.display();
    }

    void filled()
    {
    oled.rectFill(7, 5, 35, 5); // Fill a rectangle from (7, 5) to (42, 10)
    int radius = 13;
    }

    void circle()
    oled.circle(LCDWIDTH/2, LCDHEIGHT/2, radius);
    oled.display(); // Draw to the screen

    oled.circleFill(42, 20, 7); // Fill a circle, 7 radius, centered at (42, 20)
    oled.display(); // Draw to the screen
    }

    void loop()
    {
      line();
      rectangle();
      filled();
      circle();
    }
    void printTitle(String title, int font)
    {
      int middleX = oled.getLCDWidth() / 2;
      int middleY = oled.getLCDHeight() / 2;

      oled.clear(PAGE);
      oled.setFontType(font);
      oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
                     middleY - (oled.getFontWidth() / 2));
      oled.print(title);
      oled.display();
      delay(1500);
      oled.clear(PAGE);
    }

---

Full error is this

    Arduino: 1.8.6 (Linux), Board: "Arduino/Genuino Uno"

    In file included from /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino:3:0:
    /home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:38:43: warning: '__progmem__' attribute ignored [-Wattributes]
         virtual void draw(const PROGMEM byte* buffer, byte width, byte height) {}
                                               ^
    In file included from /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino:3:0:
    /home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:67:35: warning: '__progmem__' attribute ignored [-Wattributes]
         void draw(const PROGMEM byte* buffer, byte width, byte height);
                                       ^
    /home/lutherus/builds/Arduino/build/linux/work/libraries/MicroLCD/MicroLCD.h:84:35: warning: '__progmem__' attribute ignored [-Wattributes]
         void draw(const PROGMEM byte* buffer, byte width, byte height);
                                       ^
    /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void line()':
    sketch_nov14a:39: error: 'oled' was not declared in this scope
     oled.line(x0, y0, x1, y1);  // Draw a line from (x0,y0) to (x1,y1);
     ^
    /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void rectangle()':
    sketch_nov14a:48: error: 'oled' was not declared in this scope
     oled.rect(x0, y0, width, height);  // Draw a rectange from (7,5) to (31,18)
     ^
    /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: In function 'void filled()':
    sketch_nov14a:54: error: 'oled' was not declared in this scope
     oled.rectFill(7, 5, 35, 5); // Fill a rectangle from (7, 5) to (42, 10)
     ^
    /home/lutherus/scripts/sketch_nov14a/sketch_nov14a.ino: At global scope:
    sketch_nov14a:61: error: expected initializer before 'oled'
     oled.circle(LCDWIDTH/2, LCDHEIGHT/2, radius);
     ^
    sketch_nov14a:62: error: 'oled' does not name a type
     oled.display(); // Draw to the screen
     ^
    sketch_nov14a:64: error: 'oled' does not name a type
     oled.circleFill(42, 20, 7); // Fill a circle, 7 radius, centered at (42, 20)
     ^
    sketch_nov14a:65: error: 'oled' does not name a type
     oled.display(); // Draw to the screen
     ^
    sketch_nov14a:67: error: expected declaration before '}' token
     }
     ^
    exit status 1
    'oled' was not declared in this scope

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

body: I notice that the circle function is missing an opening brace.  Not sure if that's the one that caused the error you see now but it definitely needs to be fixed.


message:
Sending serial data in an interrupt

An ATMEGA328-P chip is used with a toggle switch attached to pin 8 and a momentary switch attached to pin 9. My objective is to send the following information over serial:

1. The status of pin 8, every second.
2. Count the number of presses of pin 9, sending the value as the counter increments

I understand that to achieve point 2 I will need to utilise interrupts, but I have become stuck in the way I am trying to use them.

I am familiar with the following code's simple style:

1. Within the loop...
2. Poll the status of the input
3. Send status over serial

Code A:

    const int SWITCH_1 = 8;
    const int READ_INTERVAL = 1000;

    int val_s1 = 0;

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

     pinMode(SWITCH_1, INPUT);
     digitalWrite(S1, HIGH);
    }

    void loop() {
     val_s1 = digitalRead(SWITCH_1);
     Serial.print("S1:");
     Serial.print(val_s1);
     Serial.print("\n");

     digitalWrite(LED_BUILTIN, HIGH);
     delay(10);
     digitalWrite(LED_BUILTIN, LOW);
     delay(READ_INTERVAL);
    }

When introducing the concept of interrupts, I have tried to retain the simplistic style of code A for testing purposes. The next snipped attempts to achieve the following:

1. Attach an interrupt to pin 9 when the voltage rises
2. No need for loop function (?)
3. Within interrupt callback function...
4. Increment the counter
5. Send the counter value over serial

Code B:

    void c1_rise();

    const int COUNTER_1 = 9;
    const int READ_INTERVAL = 1000;

    volatile int val_c1 = 0;

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

     pinMode(COUNTER_1, INPUT_PULLUP);
     attachInterrupt(COUNTER_1, c1_rise, RISING);
    }

    void loop() {
    }

    void c1_rise() {
     val_c1 ++;
     Serial.print("C1:");
     Serial.print(val_c1);
     Serial.print("\n");
    }

I've tried to learn where I'm going wrong, but I have become stuck and have decided to ask my questions here.

+ Observation: I expect to see some data sent over serial when the button is pressed, but actually nothing observable happens.
+ Problem 1: This might be because the interrupt isn't being attached at all.
+ Problem 2: This might be because I misunderstand the limitations of interrupt callback functions.

While trying to solve problem 1, [Arduino documentation implies][1] that to use the `attachInterrupt` function, parameter 1 must be an interrupt, from `digitalPinToInterrupt`, but if I use that function I receive the following error message: **error: ‘digitalPinToInterrupt’ was not declared in this scope**.

From reading up about how interrupts behave, I found problem 2: it seems that even though I have declared the integer as **volatile**, using Serial from within a callback function isn't allowed. This is the limit of my knowledge currently, I hope that someone can help me out.

  [1]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

body:
You cannot use Serial inside an interrupt. Transmitting Serial relies on interrupts being available, and from inside an interrupt they aren't.

All Serial communication must be done from `loop()`.

So you need to just count the switch toggles and check to see if that value has changed in your loop.

    volatile uint32_t toggles = 0;
    uint32_t old_toggles = 0;
    uint32_t ts = 0;

    void setup() {
        pinMode(2, INPUT_PULLUP);
        pinMode(3, INPUT_PULLUP);
        attachInterrupt(0, toggle, RISING);
    }

    void loop() {
        if (toggles != old_toggles) {
            old_toggles = toggles;
            Serial.print("C1: ");
            Serial.println(toggles);
        }

        if (millis() - ts >= 1000) {
            ts = millis();
            Serial.print("S1: ");
            Serial.println(digitalRead(3));
        }
    }

    void toggle() {
        toggles++;
    }


body:
**Problem**

In essence, attachInterrupt uses a macro called `ISR` (stands for Interrupt Service Routine) to register a user provided function to handle an external interrupt event.

The issue you are encountering is that `ISR` also wraps the call to your function with special instructions to clear the global interrupt flag of your microcontroller, and  set it again after your function returns. This is a good idea, and almost always what you want, because it prevents the possibility of infinitely recursive interrupts.

However, this behaviour will prevent `Serial` from working correctly, since it relies on interrupts being enabled to do its thing.

**Solution**

Although this is the default behaviour, there is nothing stopping you from enabling interrupts again inside your `c1_rise` function, as in:

    void c1_rise() {
        val_c1 ++;
        interrupts();
        Serial.print("C1:");
        Serial.print(val_c1);
        Serial.print("\n");
    }

Alternatively, but perhaps more involved, you can use the `ISR` macro directly by including `avr/interrupt.h`, and use `ISR(vect, NO_BLOCK)` to override the default behaviour.

Of course, you should be careful when overriding the default behaviour --- its there for a reason!

For more details about working with interrupts, I recommend reading [this documentation][1].

  [1]: https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html


message:
Using a button to toggle an LED ON/OFF

I'm fairly new to Arduino and am trying to use a push button to toggle an LED on and off using a momentary press of the button. This code is lifted straight off the tutorial on the Arduino website but is not working for me. It seems to send the LED on a loop - switching between on and off by itself, and pressing the button pauses the cycle.

Any ideas as to why it is doing that?

    int buttonPin = 2;         // the number of the input pin
    int ledPin = 13;       // the number of the output pin

    int state = HIGH;      // the current state of the output pin
    int reading;           // the current reading from the input pin
    int previous = LOW;    // the previous reading from the input pin

    // the follow variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    void setup()
    {
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);

    }

    void loop()
    {

      reading = digitalRead(buttonPin);

      // if the input just went from LOW and HIGH and we've waited long enough
      // to ignore any noise on the circuit, toggle the output pin and remember
      // the time
    if (reading == HIGH  && previous == LOW && millis() - time > debounce) {
      if (state == HIGH)
        state = LOW;
      else
        state = HIGH;
    time = millis();
    }

    else
      if (state == LOW)
        state = LOW;
      else
        state = HIGH;
      digitalWrite(ledPin, state);
     //Serial.println(buttonPin);
      //
     Serial.println(reading);
    previous = reading;
    }

body:
I tested your sketch and it works. I simplified it; it's the same logic, but in a more concise way:

    void loop()
    {
     reading = digitalRead(buttonPin);

     // if the input just went from LOW and HIGH and we've waited long enough
     // to ignore any noise on the circuit, toggle the output pin and remember
     // the time
     if(reading == HIGH  && previous == LOW && millis() - time > debounce) {
      state = !state;
      time = millis();
     }

     digitalWrite(ledPin, state);
     Serial.println(reading);
     previous = reading;
    }

`setup` is still the same.


body: The problem is in the "else" part. Just remove it and you are ready to go ! Also make sure that in the circuit, the digital read would be low, when not pressing button.


body:
My one line answer

  If (isPressed(BTN)) digitalWrite(LED, ~digitalRead(LED));

Is all you need to flip an led when a button is pressed.


body:
    pinMode(buttonPin, INPUT);

Do you have an external pull-down resistor?  Without one, the pin is floating when the button isn't pressed so it might read anything and you may be picking up spurious noise.

It is much more common to wire a button so that it connects to ground and reads LOW when pressed.  If you wire it that way, you can use the internal pull-up resistors by using pinMode(pin, INPUT_PULLUP) and you won't need any external resistor for the button.


message:
Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip?

Is there any way to have an arduino detect how many LEDs are on a connected strip? I have a 60 strip and 144 strip. The code is identical for both, aside from setting the number of LEDs in a variable to iterate over.

body:
Neopixels only have one-way communication. Some possible ways to detect the quantity are:

 1. Bring the Data-Out of the last pixel back to the arduino and activate an interrupt on an input pin connected to that. If you write 144 LEDs worth of data to the 144-LED strip, the pin doesn't change. If you write 144 LEDs worth to a 60-LED strip, the pin changes. So your code has a startup routine to write data and detect it. You can even write all "black" colors, since the data will still have HIGH and LOW values, and your detect routine won't show any light patterns.

 2. Pass the ground line that goes to the LED strip through a low-value resistor (A current-sense resistor) and use an analog input to read the voltage across the resistor. Write an all-white color to all NeoPixels and sense the current draw. Pre-calculate the 144-LED current draw and 60-LED current draw and set a cutoff value for knowing which strip is connected.

 3. Make your LED-strip connector to have more pins than necessary strictly for the LED strip connections. For example, have 1 extra pin. On the 144-LED strip side of the connector, tie this connection to the 5V line. On the 60-LED strip, connect it to GND. Read HIGH or LOW on an extra digital input on your arduino.


body: Not without effort. You could take the DOUT from the last LED, feed it back into the MCU, and then detect how long it takes to get some sort of signal from it, but this requires either the end of the chain being very close to the MCU or a long wire to connect them. Easier to just have a DIP switch to set the number of Pixels in the chain and go from there.


body: Also see  [Is it possible to infer the length of a neopixel string using 1-wire protocol?](https://arduino.stackexchange.com/q/21034).  For example, [one of Nick Gammon's answers](https://arduino.stackexchange.com/a/21668/3917) includes code that detects   NeoPixel string length via a binary search; [Craig's answer](https://arduino.stackexchange.com/a/21059/3917) refers to a [Bunnie  Huang blog with code and a library](http://www.bunniestudios.com/blog/?p=3345) to detect lengths; and [my answer](https://arduino.stackexchange.com/a/21041/3917) includes datasheet links and quotes, and points out that if you put *m* packets of data into a chain and *k* packets come out the last unit, the chain length is *m-k* or more, using which fact can markedly speed up length detection.  (All of these methods depend on reading data that flows out of the last unit of the chain; some of them use interrupts, some don't.)


message:
Infra Red sketch "not declared in this scope"

I'm pretty new at Arduino and I'm trying to upload a sketch with IR sensor to control LED-s.
I copy the code from internet,download library,I put my infrared codes for TV remote where I want and it says:"not declared in this scope"

Code and error:

    #include <IRremote.h>

    const int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    const int redPin = 6;
    const int greenPin = 9;

    void setup(){
      irrecv.enableIRIn();
      irrecv.blink13(true);
      pinMode(redPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
    }

    void loop(){
        if (irrecv.decode(&results)){

            switch(results.value){
              case E0E036C9: //Keypad button "5"
              digitalWrite(redPin, HIGH);
              delay(2000);
              digitalWrite(redPin, LOW);
              }

            switch(results.value){
              case E0E028D7: //Keypad button "2"
              digitalWrite(greenPin, HIGH);
              delay(2000);
              digitalWrite(greenPin, LOW);
              }

            irrecv.resume();
        }
    }

Error:

    C:\Users\Kandzija\Desktop\saneta\saneta.ino: In function 'void loop()':
    saneta:21: error: 'E0E036C9' was not declared in this scope
               case E0E036C9: //Keypad button "5"
                    ^
    saneta:28: error: 'E0E028D7' was not declared in this scope
               case E0E028D7: //Keypad button "2"
                    ^
    exit status 1
    'E0E036C9' was not declared in this scope

Can you help me guys pls?
Thank You!

body:
Numeric values in HEX need to be prefixed with `0x`:

    case 0xE0E036C9: //Keypad button "5"

and

    case 0xE0E028D7: //Keypad button "2"


message:
MQTT (was WiFi) interference when using two nodeMCU devices

I have two nodeMCU boards, one from LoLin (192.168.1.52) and one from Amica (192.168.1.53). For each nodeMCU, I have mapped its MAC address to a fixed IP address using my Movistar WiFi router. I confirm from the serial monitor that each nodeMCU is being correctly assigned to the correct IP address

My sketch is a simple IoT/MQTT client.

**My problem is that if I power up both nodeMCUs, the WiFi connection is broken on both**.

The WiFi portion of my sketch is

    void setup_wifi() {
      Serial.println(" Booting..");
      WiFi.mode(WIFI_STA);
      WiFi.begin(SSID, PASSWORD);
      while (WiFi.waitForConnectResult() != WL_CONNECTED) {
        Serial.println("Connection Failed! Rebooting...");
        myBlink(LED_PIN, 20, 100);
        delay(5000);
        ESP.restart();
      }
      WiFi.printDiag(Serial);
      Serial.println(WiFi.localIP());
    }

The output is

    Mode: STA PHY mode:
    N Channel: 1
    AP id: 0
    Status: 5
    Auto connect: 1
    SSID (13): MOVISTAR_xxxx
    Passphrase (20): 509A8EC4Exxxxxxxxx
    BSSID set: 0

    192.168.1.53 (or .52 on the other device)

I realise that the symptoms are consistent with clashing IP addresses, but to confirm, both the serial diagnostics and the DHCP report from my router confirm that the two devices are on different IP addresses.

body:
My bad!

Although my symptoms were consistent with WiFi interference, the interference was actually at the MQTT level.

The root cause was that **I hadn't realised that each MQTT client must have a unique client ID**. When the 2nd nodeMCU connected, it disconnected the first nodeMCU from MQTT, which then went into a reboot sequence to recover, which then returned the favour to the other nodeMCU.


message:
Need help to find code error to send AT command response in sms

I know that there is something wrong in my code bellow because I don't get "OK" as response in the SMS when I use Serial.print ("AT") . "AT" is an AT command.
I am using the example 2 of http://forum.arduino.cc/index.php?topic=396450.0

I tested the code bellow on the serial monitor and I am able to see the response of the AT commands on the serial monitor with Debug.println(receivedChars);. However, I am unable to receive the command's response in the SMS and would like to know what is wrong in this procedure. When I upload this code bellow, I only see "AT" in the SMS without the "OK". I think that SW_Serial.print(receivedChars); should show give OK in the SMS but I don't see it.Do you kmow why?

body:
You are making the mistake of hoping the serial response will come very quickly. You are checking for serial available, which is good, but the function PrintModemResponse gives up once no serial is available. This is quite likely to be before all of the data has arrived. Imagine you are listening to me talking, and you assume that if there is a brief pause (as I take a breath) that my sentence is over. You are better off reading until you get a definite "end marker" like a newline.

I notice you are doing something like that in recvWithEndMarker.

You may find my page about [how to process incoming serial data without blocking](http://www.gammon.com.au/serial) helpful. Example code from that page:

    /*
    Example of processing incoming serial data without blocking.

    Author:   Nick Gammon
    Date:     13 November 2011.
    Modified: 31 August 2013.

    Released for public use.
    */

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop


message:
After burning bootloader, Windows 10 doesn't recognize the USB device

I just built my own version of an Arduino Micro, using the ATMEGA32u4 chip. I burned the bootloader to it via another Arduino (Arduino Nano from [banggood.com][1]).

The Arduino Nano uses an ATMEGA328 chip, so it _should_ work as an ISP programmer. None the less, I hooked up the Nano to my custom board, according to Sparkfun's Guide, and proceeded to burn the bootloader. The Arduino IDE says that I have successfully burned the bootloader.

However, when I plug in the newly burned custom board, Windows 10 throws the error, saying, `USB Device Not Recognized` followed by `The last USB device you connected to this computer malfunctioned and Windows does not recognize it`.

I have searched for a solution, but none seem to come up. My question is, what do I need to do in order to get this custom board working as an Arduino? Thanks!

  [1]: https://www.banggood.com/

body:
You need a number of things to be true before the (new) bootloader will work:

* The hardware needs to be wired correctly
* You have used an appropriate crystal as the clock
* You have installed the correct bootloader (ie. one for the Atmega32U4)
* The fuses are set to boot into the bootloader
* The fuses are set for the correct bootloader size
* The fuses are set correctly for the clock type and the clock speed (for example, don't have the "divide clock by 8" bit set)

I have a [sketch that analyses your chip signature and fuses](http://www.gammon.com.au/forum/?id=11633) which will also report on what bootloader it detected (assuming it is one from a recognized list). You could run that and amend your question to post the resulting display from the serial monitor.

I also have a [sketch that programs a bootloader](http://www.gammon.com.au/bootloader) for various chips including the Atmega32U4. This sketch also sets the appropriate fuses.


body: I figured out my own problem. After further testing, I found that my ATMEGA32u4 from DIGIKEY was damaged. Most likely I damaged it by accident, but I can't be sure. Oh man, wouldn't it be nice if life had a CTRL+Z on it?


message:
Counting number of people inside a room

I want to count the number of people in a room using a microcontroller (Arduino Uno).

I have 2 ultrasonic sensors at a doorway about a 1.5m apart from each other. I want to increment the number when someone walks into the room and decrement that number when someone walks out.

To do this:
If sensor 1 detects a disturbance and then sensor 2 detects a disturbance then increment the counter.
If sensor 2 detects a disturbance and then sensor 1 detects a disturbance then decrement the counter.

However, my code is not working

    #include<Ultrasonic.h>

    Ultrasonic ultrasonic(5,6);

    Ultrasonic ultrasonic2(11,10);

    unsigned long currentMillis =0,t1,t2;

    int d1,d2,c;

    boolean ex=0,en=0,in;

    void setup()
    {
      pinMode(4,OUTPUT);
      digitalWrite(4,HIGH);
      Serial.begin(9600);
      delay(5000);
      Serial.println("WELCOME TO AUTOMATION !!");
      Serial.println(ultrasonic.distanceRead());
      Serial.println(ultrasonic2.distanceRead());
    }

    void loop()
    {
      currentMillis=(millis())0;
      d1=ultrasonic.distanceRead();
      d2=ultrasonic2.distanceRead();

      if(currentMillis==0)
      {
        Serial.print("Count is :");
        Serial.println(c);
        Serial.println(d1);
        Serial.println(d2);
      }

      if(d1<=15 && d2<=15)
      {
        c=c;
      }
      else if(d1<=15)
      {
        if(en==1)
        {
          c++;
          en=0;
        }
        else ex=1;
      }

      else if(d2<=15)
      {
        if(ex==1)
        {
          c--;
          ex=0;
        }
        else en=0;
      }

    }

body:
Considering abandoning the ultra sonic sensors.  Instead use 2 light beams positioned so a moving person would block one beam then both as they passed.  This problem has been commercially solved for decades using this method.

The technique used for counting people is similar to the technique used in older mouse-pointing-devices to detect direction.  The technique is called [quadrature decoding][1] such as used by an [incremental rotary encoders][2].

Specifically, you need to detect if someone is walking in or is walking out of a room.  But, to do this, you need to assure that first one then both beams will be block by the person.  It is likely this requirement will be easier to meet using light beams rather than ultrasonic sensors.

Consider [looking here][3] for example Arduino code and an explanation how to use an Arduino with a quadrature encoded knob.

  [1]: http://www.fpga4fun.com/QuadratureDecoder.html
  [2]: https://en.wikipedia.org/wiki/Rotary_encoder#Incremental_rotary_encoder
  [3]: https://playground.arduino.cc/Main/RotaryEncoders


body:
> I want to count the number of people in a room using a microcontroller (Arduino Uno).

a few ways:

1) have sensors on the entrance + exit;

2) require people in the room to push a button periodically;

3) embed sensors on the people. rfid would work for example;

4) have an image sensor and put a super-computer to analyze the picture;

5) weigh those people on a scale;

6) route those people through a single file gate and count pulses;

...

just for starters.


message:
Delay() is not working outside of interrupt

Delay() doesn't work inside ISR routines, but here I have used it in loop and outside interrupt section still Delay is not working, however there isn't any error coming. What is wrong?

    int L = 2;
    volatile int done0=0;                                //ISR variables
    void recordL();                                              //ISR 1

    void setup() {
    Serial.begin(9600);
    Serial.println("Start");

    pinMode(L,INPUT);
    }

    void loop() {

    interrupts();
    attachInterrupt(0,recordL,RISING);
    done0=0;

    while(!done0)
    {
        Serial.println(millis());
    }
    noInterrupts();

    Serial.println("Detected");
    delay(5000);
    Serial.println("After Delay");
    }

    void recordL()
    {
      Serial.println("in Interrupt0");
      done0=1;
    }

body:
    noInterrupts();

    Serial.println("Detected");
    delay(5000);

`delay()` won't work with interrupts turned off.


body:
> Do I need interrupts() noInterrupts() in the loop section?

Yes, you do. Always.

The optimal workflow is

 1. In the ISR itself, just raise a flag or directly change some global
variable.
 2. In the `loop` you first copy that flag/variable to a local variable, using interrupts/noInterrupts to prevent the ISR changing the value while you are using/copying it.

Assignment are not atomic in Arduino World. That means that the value you are copying can change while you are doing it, and you end with garbage in your variables. Or, worse, it can change between one statement and the next. Try to debug that.

This is how you do it. In this example, I'm using an interrupt to manage a button (with debouncing). I need to detect state (pressed/not pressed) and timing (how long you pressed it). I can't directly use `lastFallingEdge` in `loop`; I copy it first so it won't change while I'm using it.

    volatile unsigned long lastFallingEdge = 0; // For debouncing.
    volatile boolean bPressed = false;

    void buttonInterrupt(void)
    {
     lastFallingEdge = millis();
     bPressed = true;
    }

    void loop()
    {

     if(bPressed) {
      noInterrupts();
            bPressed = false;
      unsigned long falling = lastFallingEdge;
      interrupts();
      unsigned long len = millis() - falling;

      // Do something.
     }
    }


body: Delay() function works by using timer interrupts internally. If you disable all interrupts using NoInterrupt function , then how will it work. Using that function is not recommended in code, as it causes unexpected misbehaviors.


message:
How to power up this LCD 7 segments display

I got two of these type of 7 segments display in LCD material.

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

And here is the datasheet
[![enter image description here][2]][2]

I tried to power up to UNO, it can make the segment on, while a second, the segment go off, but the pinMode does not changed.

  [1]: https://i.stack.imgur.com/5UdNk.jpg
  [2]: https://i.stack.imgur.com/4ZHO5.jpg

body:
Driving an LCD display is nothing like driving an LED display. You need to provide an alternating current to the right segments at the right time.

It is possible with an Arduino on a simple display like this, but not easy. Better is to use a chip that has a proper LCD display interface, such as the MSP430 "F" series (the FRAM ones).

To do it on an Arduino you need to treat it like a common anode matrix on one pass, and a common cathode matrix on the next pass, and do that repeatedly and rapidly.

That is, set COM1 HIGH and the other COMx pins LOW,  and the segments you want on LOW and the others HIGH, then do the same with COM2, etc. Then go back to the start and invert the logic, so set COM1 LOW and the other COMx HIGH, and your chosen segments HIGH.

It is best to do this from within a timer interrupt so that you can get good regular updates without your program causing delays.


body:
that's a controller-less dynamic (mutiplexed) display, with 4 coms.

So you will to program the mcu to do a lot:

1) the com pins are driven with 1/4 dc signal sequentially;

2) the seg pins are driven with 1/3 bias voltage. out-of-phase to be dark and in-phase to be transparent (not lit).

the way to do it is to:

1. put segment info in a buffer;

2. write a display update routine that scans digits and updates the com/seg pins according to the current digit's segment information;

3. call that display update routine periodically, preferrably from a timer isr.

the display update routine would be similar to an led display routine - an example of that (for led) would be here (https://dannyelectronics.wordpress.com/2017/06/30/a-more-flexible-driver-for-7-segment-leds/), but more complex due to the 4 com pins and bias generation.

it is much easier to pick a mcu with built-in lcd driver and program that mcu as a display controller / slave taking in information from a master (in this case your arduino).


message:
Setting a default arduino program in NodeMCU

Just after saying farewell to my old broken D1 mini I could not resist myself and bought a brand new nodemcu in the morning. I tried my previous arduino sketches to board and everything works fine, just needed to change the pin setup.
I was wondering is it possible to set a default arduino program to nodemcu? such that every time I turn on my Nodemcu 12-E it runs it as a default program.
Searching the internet I cam across this [link][1]. Downloaded the flasher,selected the port to which 12-E is connected and flashed it.
After following all instructions and connecting to AP and 192.168.4.1/edit I tried to setup an arduino code as default code but failed. Is that because original firmware on supports **Lua programming language**? Is it possible to setup an arduino sketch as a default program? If not is it possible to convert arduino sketch to Lua programming language? as I have zero knowledge of Lua

  [1]: https://www.esp8266basic.com/flashing-instructions.html

body: GPIO `D3` on the NodeMCU is the ESP8266's `GPIO0`, which does put the device in flash mode when pulled low on power-up. Either put a pull-up resistor on that pin, or use a different pin for IO.


message:
Make 3 servos move like a wave

I am having some trouble programming 3 servos to move like a wave.  So, for instance, all my servos start at 90 degrees. I want my first servo to move and when it reaches 135 degrees I want my second servo to move, with the first, then when it reaches 135 degrees I want my third servo to move, with the first and the second. Then go backwards. Does that make sense?

Here is what I have so far.

    #include <Servo.h>

    //Create servo object to control a servo
    Servo left;
    Servo middle;
    Servo right;

    //Variables to store the servo position
    int post = 180;
    int post2 = 90;
    int back = 90;
    int forward = 135;

    int firstTriggerAngle = 135;
    int secondTriggerAngle = 180;

    //Delay
    int mid = 4;

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

      //Attaches the servos on the pins of the arduino to the servo object
      left.attach(4);
      middle.attach(3);
      right.attach(2);

      //Starting position
      left.write(back);
      middle.write(back);
      right.write(back);
    }

    void loop()
    {
      for (int i=back; i>=forward; i+=1)
      {
        left.write(i);
        if( i > firstTriggerAngle)
        {
          post = map(i, 90, 135, 135, 90);
          middle.write(post);
        }
        if(post > secondTriggerAngle)
        {
          post2 = map(post, 90, 135, 135, 90);  // depends on the angles you use
          right.write(post2);
        }
        delay(mid);
     }
    }

body:
The easiest way is to define how many degrees you want to move totally .

In your case it is 180 steps (from 90 to 180, which is 90 steps, and 180 to 90, which is another 90 steps).

Than use a for loop with a 180 step-counter and make 3 simple formulas to map the 180 possible degrees to the wanted servo position.

So the first formula will look like (step 0..90 -> move from 90 to 180, step 90..180-> move 180 to 0).

    int calcServo1(int step)
    {
        if (step < 90)
        {
            return 90 + step;
        }
        else
        {
            return 270 - step; // 180 - (step - 90);
        }
    }

For the second it should be:

-  step is 0..45: first iteration: 90, otherwise 135..90
-  step is 45..135: 90..180
-  step is 135..180: 180..135

The code will be something like:

    int calcServoPos2(int iteration, int step)
    {
        if (step < 45)
        {
            if (iteration == 0)
            {
                return 90;
            }
            else
            {
                return 135 - step;
            }
       else if (step < 135)
       {
             return step + 45;
       }
       else
       {
           return step - 45; //  step - 180 + 135
       }
    }

Servo 3 I will leave up to you.

From your main loop you call the positions:

     int iteration = 0;

     while (loop)
     {
          for (int step = 0; step < 180; step++)
          {
             int servo1pos = CalcServo1(iteration, step);
             servo1.write(servo1pos);

             int servo2pos = CalcServo2(iteration, step);
             servo2.write(servo2pos);

             int servo3pos = CalcServo2(iteration, step);
             servo3.write(servo3pos);

             delay(mid);
         }
         iteration++;
      }


message:
Is there a way to update Arduino uno Over The Air

I have the Arduino uno with a Ethernet W5100 Shield and would like to remotely sketches.  Is there a way to update Arduino uno over the air?  If not, is there a wired network arduino solution that will allow update over the air.

I've done this on the esp8266 using there tools but I can't find one for the Uno.

Thanks

body:
Not with WiFi, nor with Ethernet. People have managed it with Bluetooth, but only because it can create a transparent serial bridge. The bootloader only talks serial, so you have to use something that is serial to program it.

The only possible way is to use another WiFi (or Ethernet) device, such as the ESP8266, to act as a serial bridge to connect the Arduino's serial port (and reset signal) to your computer over WiFi. A bit of a waste of an ESP8266 since that is then the sole task it would have (unless you craft a far more complex sketch for the ESP8266 to allow it to do other things as well).


body:
The [Ariadne bootloader project][1] enables upload over Ethernet to AVR boards with Ethernet shield.

  [1]: https://github.com/per1234/Ariadne-Bootloader


message:
Having trouble with 74HC595 and Uno

Just picked up a couple of 74HC595 shift registers to use for my Arduino Uno, and I'm having trouble getting it working 100% of the time. My code is to get a value from the Serial monitor and shift it into the register. The issue is that bits 4 and 5 are always on no matter what I put into the monitor, but when I clock a 0 into the register during setup(), it works as expected, i.e. all LEDs go off

Here is the code:

    int dataPin = 2;
    int latchPin = 3;
    int clockPin = 4;

    void setup() {
        Serial.begin(9600);
        pinMode(dataPin, OUTPUT);
        pinMode(latchPin, OUTPUT);
        pinMode(clockPin, OUTPUT);

        digitalWrite(latchPin, LOW);
        shiftOut(dataPin, clockPin, MSBFIRST, 0);
        digitalWrite(latchPin, HIGH);
    }

    void loop() {
        if(Serial.available()) {
            digitalWrite(latchPin, LOW);
            shiftOut(dataPin, clockPin, MSBFIRST, Serial.read());
            digitalWrite(latchPin, HIGH);
        }
    }

Is it the code that is wrong? Do i have a busted shift register? Or something else?
Thanks

body:
`Serial.read()` is going to give you ASCII codes.  So when you send 1 from the serial monitor the Arduino receives 49.  Note that the ASCII code for a digit is the same as the digit plus 48, so that sets bits 4 and 5 high.

You can use `Serial.read() - '0'` to get the actual number from the ascii code.


message:
What values are the Atmel MCUs EEPROMs preloaded with?

I have checked with two datasheets: one for some ATMegas and one for some ATTinys MCUs and could not find what the `EEPROM.get()` call would read back if the EEPROM was empty (or contained default factory values). I have written a program in order to find out and it looks like on Arduino Uno the EEPROM bytes are all `FF` by default.

Is this the case with every Arduino board or just some of them ? Or perhaps we can not assume that all the MCUs of a certain type (such as ATMega328) will have this factory preloaded value of `FF` for the EEPROM bytes ?

**edit**

Following the fuses - thanks @Chris Stratton - I was able to find this in the datasheet:

> Skip writing the data value 0xFF, that is the contents of the entire
> EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip
> Erase.

Seems like we could get the factory pre-loaded value by not programming the EESAVE fuse, which is what the Arduino Uno does by default, and just reading them.

> uno.bootloader.low_fuses=0xFF
> uno.bootloader.high_fuses=0xDE
> uno.bootloader.extendedfuses=0xFD

However, having a way to set them to a known value is fine too for my needs, so I shall just write that fuse and havea  guaranteed `0xFF` all over the EEPROM.

body: They're all set to 0xFF by default.


body:
When you erase an EEPROM it sets the cells to 0xFF. When you write a byte to a cell any 0 bits are set to 0 and the 1 bits are left alone.

0xFF is the normal erased state for most EEPROMs.


message:
Unstable ESP8266 - flickering lights

A while ago I have bought NodeMCU board along with few sensors to play with. I have coded everything, and, when powered via USB, works like a charm. Problem begins, when I try to use my contraption as a standalone system. It works for few minutes, then it starts giving me false readings from the sensors (like, luminosity of few thousands in a dark room).

I am powering the system with (pics at the bottom of the post) AC-DC step down module, 230v -> 5v (1A of current), which then I am stepping down with DC-DC step down module, 5v -> 3v (800mA of current). Using only these two modules, I power NodeMCU and all of my sensors - currently luminosity, temp&humid, motion, SSR (I had led matrix too. I thought that maybe it drags too much current, but no luck there - after disconnecting it I have same problems).

**My main indicator that something is not right, is SSR module**. It has a built-in diode of the same size that NodeMCU has. It lights immediately as I start the system, and it (it's diode) flickers (it's intensity changes). It does not flicker, when I connect everything through USB.

I have also tried to put 50uF capacitor into the wiring, but no luck either, system is still unstable. **What am I doing wrong? Why does the light flickers? Is 1A/800mA not enough power for my system?**

**Edit**: I know what is the cause. I just do not know how to fix it. I just kept my multimeter on for 10mins for both of the step down modules. 5V -> 3V step down (2nd item in the pics below) is initially giving me 800mA, but then gradually losing current (right now it's at 350mA after just few minutes of work). Is there anything I can do here? Or just throw the thing away and look for some other power supply? It's a standard AMS 1117 with some capacitors on it.

Below are the pictures, of my step-down modules and SSR module:

[![230V AC to 5V DC (1A out)][1]][1]
[![230V AC to 5V DC (1A out) - back][2]][2]
[![5V DC to 3V DC (800mA out)][3]][3]
[![5V DC to 3V DC (800mA out) - back][4]][4]
[![SSR][5]][5]

  [1]: https://i.stack.imgur.com/60wpi.jpg
  [2]: https://i.stack.imgur.com/0xkox.jpg
  [3]: https://i.stack.imgur.com/WvXUm.jpg
  [4]: https://i.stack.imgur.com/YMnLr.jpg
  [5]: https://i.stack.imgur.com/S2GkK.jpg

body:
Take care how you power the nodemcu. the VU pin is 5v from USB and i am not sure it can be powered with this pin. I do think it is safe to power your device with the 3.3v pins.

does that solid state relay want 5v?

it may be best to put 5v (upto 20v max) into the VIN pin (which goes to the on-board voltage regulator).


body:
The VIN pin on the NodeMCU board can take the 5V directly. Had no problem with that way until now.

What is strange to me is that the current from your 5V to 3V regulator  is degrading. The regulator on the board it's self is basically the same (maybe another manufacturer). What may be the cause is that the regulator is overheating and somehow that the effects the output current and/or voltage.

What you can also try is a LM2596 step down regulator.
Those are pretty cheap as well and have a good output capacitance. They can deliver up to 3A at down to ~1.3V. Input voltage is somewhere between 40V and your output voltage plus 1 or 2 volts to let it properly regulate.
You can use that module to transform your 5V down to 3.3V easily - i've done it so often with it, i lost count.


message:
Arduino UNO Intro to Engineering Project

I am a college student in an intro to engineering class looking to create a final project. My goal is to create a small "present" that opens its lid via a servo and plays jingle bells with LEDs flashing (as shown in the youtube video linked below), before closing the lid once again until a further button press.
https://www.youtube.com/watch?v=V6TcAhXCL6w

The code that this video uses is:

    /*
      "Jingle Bells" Melody

     Plays "Jingle Bells"

     circuit:
     * 8-ohm speaker on digital pin 7

    #define NOTE_C4  262
    #define NOTE_D4  294
    #define NOTE_E4  330
    #define NOTE_FS4 370
    #define NOTE_G4  392
    #define NOTE_A4  440
    #define NOTE_B4  494
    #define NOTE_C5  523
    #define NOTE_D5  587
    #define NOTE_E5  659

    // notes in the melody:
    int melody[] = {
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
      NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
      NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
      NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
      NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
      NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
      NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
      NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
      NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

    // note durations: 4 = quarter note, 8 = eighth note, etc.:
    int noteDurations[] = {

      8, 8, 8, 8, 3, 16, 16,
      8, 8, 8, 8, 2,
      8, 8, 8, 8, 2,
      8, 8, 8, 8, 3, 8,
      8, 8, 8, 8, 3, 16, 16,
      8, 8, 8, 8, 3, 8,
      8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 2,
      8, 8, 4, 8, 8, 4,
      8, 8, 6, 16, 2,
      8, 8, 6, 16, 8, 8, 8, 16, 16,
      8, 8, 8, 8, 4, 4,
      8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
      8, 8, 6, 16, 8, 8, 8, 16, 16,
      8, 8, 8, 8, 2 };

    void setup() {
        pinMode(3,OUTPUT);
        pinMode(6,OUTPUT);
        pinMode(9,OUTPUT);
        pinMode(11,OUTPUT);
        digitalWrite(3, LOW);
        digitalWrite(6, LOW);
        digitalWrite(9, LOW);
        digitalWrite(11, LOW);
      // iterate over the notes of the melody:
      for (int thisNote = 0; thisNote < 100; thisNote++) {

        // to calculate the note duration, take one second
        // divided by the note type.
        //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
        int noteDuration = 1800/noteDurations[thisNote];
        // I found that by lengthening the noteDuration,
        // I was able to "slow" the song down.
        tone(7, melody[thisNote],noteDuration);
        LEDon();

        // to distinguish the notes, set a minimum time between them.
        // the note's duration + 30% seems to work well:
        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);
        // stop the tone playing:
        noTone(7);
        LEDoff();
      }
    }

    void loop() {
      // no need to repeat the melody.
    }

    int currentLEDpin=3;
    void LEDon()
    {
        digitalWrite(currentLEDpin, HIGH);
    }

    void LEDoff()
    {
        digitalWrite(currentLEDpin, LOW);
        if (currentLEDpin==3) currentLEDpin=6;
        else if (currentLEDpin==6) currentLEDpin=9;
        else if (currentLEDpin==9) currentLEDpin=11;
        else currentLEDpin=3;
    }

My general outline for the project looks like this:

 1. Set LEDs, Piezo, and Servo to OUTPUT
 2. Set pushbutton to INPUT
 3. Start all LEDs off/LOW
 4. Start a loop that has if statement for button push
 5. Open the lid (servo motor about 100 degrees)
 6. Start the song/LED sequence using code borrowed from the youtube video
 7. After finishing the song, close the lid (servo motor back 100 degrees)

I am very much a beginner to coding Arduino, so I was wondering if my uploaded sketch seems correct...

    //Notes for Jingle Bells
    #define NOTE_C4  262
    #define NOTE_D4  294
    #define NOTE_E4  330
    #define NOTE_FS4 370
    #define NOTE_G4  392
    #define NOTE_A4  440
    #define NOTE_B4  494
    #define NOTE_C5  523
    #define NOTE_D5  587
    #define NOTE_E5  659

    //Notes in melody Command
    int melody[] = {
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4,
      NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_FS4,
      NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_B4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_D4, NOTE_D4, NOTE_D4,
      NOTE_D4, NOTE_B4, NOTE_A4, NOTE_G4, NOTE_E4, NOTE_E4,
      NOTE_E4, NOTE_C5, NOTE_B4, NOTE_A4, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_D5,
      NOTE_E5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4,
      NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
      NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_A4, NOTE_A4, NOTE_B4, NOTE_A4, NOTE_D5,
      NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_B4, NOTE_D5, NOTE_G4, NOTE_A4, NOTE_B4,
      NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_C5, NOTE_B4, NOTE_B4, NOTE_B4, NOTE_B4,
      NOTE_D5, NOTE_D5, NOTE_C5, NOTE_A4, NOTE_G4 };

    // Note Durations (4 = quarter note, 8 = eighth note, etc.)
    int noteDurations[] = {
      8, 8, 8, 8, 3, 16, 16,
      8, 8, 8, 8, 2,
      8, 8, 8, 8, 2,
      8, 8, 8, 8, 3, 8,
      8, 8, 8, 8, 3, 16, 16,
      8, 8, 8, 8, 3, 8,
      8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 2,
      8, 8, 4, 8, 8, 4,
      8, 8, 6, 16, 2,
      8, 8, 6, 16, 8, 8, 8, 16, 16,
      8, 8, 8, 8, 4, 4,
      8, 8, 4, 8, 8, 4, 8, 8, 6, 16, 2,
      8, 8, 6, 16, 8, 8, 8, 16, 16,
      8, 8, 8, 8, 2 };

    #include <Servo.h>      //Include built-in Servo sketch
    Servo servo;            //Servo sketch reference for setup
    const int servoPin=5;   //Set servoPin to 5
    int angle = 0;          //Set initial servo angle to 0 degrees

    const int buttonPin=2;   //Set buttonPin to 2
    int buttonState=0;       //variable for reading pin status

    int currentLEDpin=3;    //Set LED pin variable for LED flashes
    void LEDon()            //Define LEDon for turning on LED to music
    {
        digitalWrite(currentLEDpin, HIGH);
    }

    void LEDoff()           //Define LEDoff for turning off LED when music off
    {
        digitalWrite(currentLEDpin, LOW);
        if (currentLEDpin==3) currentLEDpin=6;
        else if (currentLEDpin==6) currentLEDpin=9;
        else if (currentLEDpin==9) currentLEDpin=11;
        else currentLEDpin=3;
    }

    void setup() {
        pinMode(3,OUTPUT);           //Set LED Pins to OUTPUTs
        pinMode(6,OUTPUT);
        pinMode(9,OUTPUT);
        pinMode(11,OUTPUT);
        digitalWrite(3, LOW);        //Start all LED lights off
        digitalWrite(6, LOW);
        digitalWrite(9, LOW);
        digitalWrite(11, LOW);

        pinMode(buttonPin,INPUT);   //Set button to INPUT

        servo.attach(servoPin);     //Servo setup

    }

    void loop() {
     buttonState=digitalRead(buttonPin);     //read input value

      if (buttonState == HIGH) {              //check if pushbutton is pressed

      for(angle = 0; angle <110; angle++)    //rotate servo 110 degrees, opening present box lid
        {
        servo.write(angle);
        delay(15);
        }

      for (int thisNote = 0; thisNote < 100; thisNote++) {
        int noteDuration = 1800/noteDurations[thisNote];    //define note duration
        tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
        LEDon();                                            //Flash LEDs to tune
        int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
        delay(pauseBetweenNotes);
        noTone(7);                                          //Stop playing music when melody over
        LEDoff();                                           //Stop flashing LEDs when melody over
    }

      for(angle = 110; angle > 0; angle--)                  //Close present box lid
        {
        servo.write(angle);
        delay(15);
        }
       }

    }

So when you say to erase the LEDon and LEDoff calls, is that in this section of the code?:

     for (int thisNote = 0; thisNote < 100; thisNote++) {
        int noteDuration = 1800/noteDurations[thisNote];    //define note duration
        tone(7, melody[thisNote],noteDuration);             //Play melody of Jingle Bells
        LEDon();                                            //Flash LEDs to tune
        int pauseBetweenNotes = noteDuration * 1.30;        //Pause between notes to annunciate each note
        delay(pauseBetweenNotes);
        noTone(7);                                          //Stop playing music when melody over
        LEDoff();                                           //Stop flashing LEDs when melody over
    }

body:
LEDon and LEDoff are defined in the Jingle Bell sketch. They just lit on/of the leds.

You don't need them for your project, just erase the calls. Otherwise, copy the LEDon/off functions:

    int currentLEDpin=3;
    void LEDon()
    {
        digitalWrite(currentLEDpin, HIGH);
    }

    void LEDoff()
    {
        digitalWrite(currentLEDpin, LOW);
        if (currentLEDpin==3) currentLEDpin=6;
        else if (currentLEDpin==6) currentLEDpin=9;
        else if (currentLEDpin==9) currentLEDpin=11;
        else currentLEDpin=3;
    }

You made a mistake:

 if(buttonState = HIGH) {               //check if pushbutton is pressed

Here you **assign** HIGH to `buttonState`.

The "=" is assignment operator. What you were thinking is "==", the equality-comparison operator (a common mistake). Replace it with

 if(buttonState == HIGH) {               //check if pushbutton is pressed

Also, you need to debounce you button. Read about it in this excelent tutorial by Nick Gammon: [Switches tutorial][1]. Well, read his whole blog if you have the time.

Otherwise, you are doing well.

  [1]: http://www.gammon.com.au/switches