message:
Arduino Mega and gyroscope erroneous values

I have Arduino mega2560 and MPU6050.

I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.

[I used this code:][1]

    #include<Wire.h>

    const int MPU=0x68; //I2C address of MPU
    int GyX,GyY,GyZ;
    float pitch=0;
    float roll=0;
    float yaw=0;

    float v_pitch;
    float v_roll;
    float v_yaw;
    float a_pitch;
    float a_roll;
    float a_yaw;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU);
      Wire.write(0x6B); //power management register 1
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MPU);
      Wire.write(0x43);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,6,true);
      GyX=Wire.read()<<8|Wire.read();
      GyY=Wire.read()<<8|Wire.read();
      GyZ=Wire.read()<<8|Wire.read();
      v_pitch=(GyX/131);
      if(v_pitch==-1) {
        v_pitch=0;
      }
      v_roll=(GyY/131);
      if(v_roll==1) {
        v_roll=0;
      }
      v_yaw=GyZ/131;
      a_pitch=(v_pitch*0.046);
      a_roll=(v_roll*0.046);
      a_yaw=(v_yaw*0.045);
      pitch= pitch + a_pitch; roll= roll + a_roll;
      yaw= yaw + a_yaw;
      Serial.print(" | pitch = ");
      Serial.print(pitch);
      Serial.print(" | roll = ");
      Serial.print(roll);
      Serial.print(" | yaw = ");
      Serial.println(yaw);
    }

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

[![Output][2]][2]

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

  [1]: https://www.circuitstoday.com/interfacing-gyroscope-arduino
  [2]: https://i.stack.imgur.com/hMpMx.png

body:
It is possible to use your sketch and get angle information. It is not very accurate and it drifts.

I started with your sketch, and improved it until I had the angle.
The `Serial.println` functions take time and they are printed too often. To measure the interval between the samples, I used `millis`.

This test is done with:

 - arduino M0 board (with 3.3v i2c bus)
 - gy-521 module with onboard voltage regulator, but no level shifter
 - vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.

    // test with arduino M0 board
    #include <Wire.h>

    #define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

    const int MPU = 0x68;   // I2C address of MPU

    int16_t x_offset = 0;
    int16_t y_offset = 0;
    int16_t z_offset = 0;

    float pitch = 0.0;
    float roll  = 0.0;
    float yaw   = 0.0;

    unsigned long previousMillisSample;
    unsigned long previousMillisOutput;
    const unsigned long intervalOutput = 500;  // half a second update to serial monitor

    void setup() {
      SER.begin(9600);
      while(!SER);         // wait for serial monitor to open for Leonardo and M0
      SER.println("Angle from gyro");

      Wire.begin();

      Wire.beginTransmission(MPU);
      Wire.write(0x6B); //power management register 1
      Wire.write(0);
      Wire.endTransmission();

      // get the values of the gyro and use them as offset
      GetXYZ(x_offset, y_offset, z_offset);
    }

    void loop() {

      int16_t GyX;
      int16_t GyY;
      int16_t GyZ;

      GetXYZ(GyX, GyY, GyZ);

      unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

      // remove offset
      GyX -= x_offset;
      GyY -= y_offset;
      GyZ -= z_offset;

      float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
      float v_roll  = float(GyY) / 131.0;
      float v_yaw   = float(GyZ) / 131.0;

      // calculate time in milliseconds between previous and current sample
      unsigned long t = currentMillisSample - previousMillisSample;

      // time in seconds as a float
      float float_t = float(t) / 1000.0;

      // adjust the number of degrees during the time
      float a_pitch = v_pitch * float_t;
      float a_roll  = v_roll  * float_t;
      float a_yaw   = v_yaw   * float_t;

      // remember the time in millis when the sample was taken for the next time
      previousMillisSample = currentMillisSample;

      pitch += a_pitch;
      roll  += a_roll;
      yaw   += a_yaw;

      // Once in a while, print the output
      if(millis() - previousMillisOutput >= intervalOutput) {
        previousMillisOutput = millis();

        SER.print("pitch = ");
        SER.print(pitch);
        SER.print(" | roll = ");
        SER.print(roll);
        SER.print(" | yaw = ");
        SER.println(yaw);
      }
    }

    void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
      // Get the gyro values
      Wire.beginTransmission(MPU);
      Wire.write(0x43);     // first register of gyro values
      Wire.endTransmission(false);

      Wire.requestFrom(MPU,6);
      x = Wire.read() << 8 | Wire.read();
      y = Wire.read() << 8 | Wire.read();
      z = Wire.read() << 8 | Wire.read();
    }

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.


sender: user

message:
How to randomize the delay in Arduino Stepper code?

How does one add a random DELAY between 10 and 20 seconds?

For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).

What would I need to add (or modify) so this is randomized between 10 and 20 seconds?

    //#define IN1  8
    //#define IN2  9
    //#define IN3  10
    //#define IN4  11

    int Steps = 0;
    boolean Direction = true;
    unsigned long last_time;
    unsigned long currentMillis ;
    int steps_left=4095;
    long time;

    void setup()
    {
    Serial.begin(115200);
    pinMode(IN1, OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);

    }
    void loop()
    {
      while(steps_left>0){
      currentMillis = micros();
      if(currentMillis-last_time>=1000){
      stepper(1);
      time=time+micros()-last_time;
      last_time=micros();
      steps_left--;
      }
      }
       Serial.println(time);
      Serial.println("Wait...!");
      delay(11000);                     // delay timing
      Direction=!Direction;
      steps_left=4095;
    }

Forgive the appearance of the code.  Everytime I post it gets butchered.  Hopefully it's understandable.

sender: assistant

body:
In `setup()`, add

    randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your `delay()` call, just replace the fixed value with a call to the `random(min, max)` function, as:

    delay(random(10000, 20000));


message:
shift register 74HC595 enable specific pin

Its driving me crazy for some couple of days now and i don't get the answer.
I'm busy to setup a irrigation system with a shift register 74HC595 and a 8 channel relay board.
I see a lot of sketches where it looks like you can turn a specific relay on but i dont get the clue.

I like to turn on a specific relay based on a button press.
Is it possible to turn on a specific relay based on the representing button?

Im using the shiftOut option. The code im using now is :

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;
    byte data;
    byte dataArray[10];

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 49); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 50); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, HIGH);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, LOW);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin, int whichState) {
    // the bits you want to send
      byte bitsToSend = 0;

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // turn on the next highest bit in bitsToSend:
      bitWrite(bitsToSend, whichPin, whichState);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

Sander

---

i've change the code. Now the result is the led is turning on but only one led. After pressing led 2 the other one is turning on..
Im not able to turn them off.

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 1); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 4); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet);
          Serial.println(bitToSet);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin) {
    // the bits you want to send
       uint8_t data = 1<<whichPin ;
      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

---

Im using the shiftOut option.
The code im using now is :

    //#define BLYNK_DEBUG
    #define BLYNK_PRINT Serial

    #include <ArduinoOTA.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <TimeLib.h>
    #include <WidgetRTC.h>

    #include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
    #include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
    #include <SPI.h>            // For SPI comm (needed for not getting compile error)

    #include "settings_base.h"
    #include "globals.h"
    //#include "functions.h"
    //#include "blynk_writes.h"

    //Pin connected to ST_CP of 74HC595
    const int latchPin = 15; //D8
    //Pin connected to SH_CP of 74HC595
    const int clockPin = 14; //D5
    //Pin connected to DS of 74HC595
    const int dataPin = 13; // D7

    int totalRelays = 2; // Number of relays
    int relayState = 0; // default state = off
    int relayArr[] = {12, 16}; // Pins on the Wemos
    char vbutton1 = V1; char vbutton2 = V2;
    char relayVButtons[] = {V1,V2};
    int zone = 0;
    int relayVButton = 0;
    byte data;
    byte dataArray[10];

    /*
       SETUP
    */
      BLYNK_WRITE(V1)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 12, 49); // Test led on Wemos pin
        //int bitToSet = 49;

        Serial.println("V1 pressed");
      }

      BLYNK_WRITE(V2)
      {
        // Get the state of the VButton
        relayVButton = param.asInt();
        relayControl(relayVButton, 16, 50); // Test led on Wemos pin
        Serial.println("V2 pressed");
      }

    void setup() {

      pinMode(dataPin, OUTPUT);   // All 3 pins are output
      pinMode(clockPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      // Do some loop through all the relays and buttons for pinMode
      for (int i=0; i<=totalRelays; i++){
        pinMode(relayArr[i], OUTPUT);
        digitalWrite(relayArr[i], 0);
        pinMode(relayVButtons[i], INPUT);
      }

      // COMMUNICATIONS
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      // CONNECT TO BLYNK
      Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
      while (Blynk.connect() == false) {}
      // OVER THE AIR UPDATES
      ArduinoOTA.setHostname(OTA_HOSTNAME);
      ArduinoOTA.begin();

      Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
    }
    /*
       LOOP
    */
    void loop() {
      Blynk.run();
      ArduinoOTA.handle();
      timer.run();
    }

    void relayControl(int onoff, int relayNumber, int bitToSet){
    if(onoff == 1) // Virtual button set to on
        {
          digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, HIGH);
          relayState = 1;
        }
        else
        {
          digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
          registerWrite(bitToSet, LOW);
          relayState = 0;
        }
    }
    void registerWrite(int whichPin, int whichState) {
    // the bits you want to send
      byte bitsToSend = 0;

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // turn on the next highest bit in bitsToSend:
      bitWrite(bitsToSend, whichPin, whichState);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);

    }

body:
Working from `shiftOut()` backwards:

Parameters for `shiftOut()`:

> **Syntax**
>
> `shiftOut(dataPin, clockPin, bitOrder, value)`
>
> **Parameters**
>
> `dataPin`: the pin on which to output each bit (int)
>
> `clockPin`: the pin to toggle once the dataPin has been set to the
> correct value (int)
>
> `bitOrder`: which order to shift out the bits; either MSBFIRST or
> LSBFIRST. (Most Significant Bit First, or, Least Significant Bit
> First)
>
> `value`: the data to shift out. (byte)

The important part to notice is the `value` parameter, which is one 8-bit value, and along with the `dataPin` and `clockPin`, sets the 8 registers of the shift register to the 8 bits shifted in. Then, as you have in your code, you pull the `latchPin` high to latch the register values to the output pins.

Binary values can be represented in C++ as `b00001010`, where the `b` prefix notes that the number following is in binary notation, and not "one-thousand ten". If the least-significant bit refers to relay-0 and the most-significant bit refers to relay-7, then to turn on relay-0, you would make sure the last digit (least-signficant) is a one: `b00000001`. To turn on relays 0 and 1, send 'b00000011', and so on.

In your `registerWrite()` function, you call `shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);`, thus `bitsToSend` should be an 8-bit value, with each bit representing the state of one of the 8 relays on your relay board.

within `registerWrite()`, `bitsToSend` is set by the `bitWrite()` function, which sets the bit number identified by `whichPin` to the value represented by `whichState`, which are both parameters passed in from the function call. It's worth noting that `bitsToSend` is initialized to `b00000000` and `bitWrite()` is called only once, and so there can be at most **one** bit turned on in the value to write; and thus only one relay active at a time.

`registerWrite()` is called from within `relayControl()`, and the `whichPin` value in `registerWrite()` comes from the `bitToSet` value in `relayControl()`, which in turn is called by the `BLYNK_WRITE(V1)` or `BLYNK_WRITE(V2)` functions. In both of those functions, you pass `49` or `50` as the `bitToSet` parameter, but there are only 8 bits in a byte, so the value passed should be between 0 and 7. You cannot set bit 49 of an 8-bit value.

Probably `relayControl()` should be called with a value between 0 and 7 for the last parameter.

----------

**EDIT Based on New Code**

Your latest code shows some changes to the `registerWrite()` function:

    void registerWrite(int whichPin) {

You have removed the parameter which contains the value to write to the particular bit position. Now you have no way to tell the function whether to turn the pin on or off.

    // the bits you want to send
       uint8_t data = 1<<whichPin ;

By shifting a `1` to a particular bit position, you have no way to clear a bit, which is probably why you now cannot get an LED to turn off except by turning on the alternate LED.

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);
    }

If you wish to maintain the current state of bits, you will need to declare `data` as a `static` variable, which means that it's value is retained even when the function ends and is again available when the function is called again. Further, by using the assignment (`=`) operator, all you are able to do is overwrite the existing data with the new data, erasing the previous data.

You can use the `bitSet()` and `bitClear()` functions to set (make equal to 1) and clear (make equal to zero) individual bits in a byte.

A new `registerWrite()` function might look like:

    void registerWrite(int whichPin, int pinValue) {
      // the bits you want to send
      static uint8_t data;

      if (pinValue==1) {
        bitSet(data, whichPin);    // Turn on the bit at whichPin
      } else {
        bitClear(data, whichPin);  // Turn off the bit at whichPin
      }

      // turn off the output so the pins don't light up
      // while you're shifting bits:
      digitalWrite(latchPin, LOW);

      // shift the bits out:
      shiftOut(dataPin, clockPin, MSBFIRST, data);

        // turn on the output so the LEDs can light up:
      digitalWrite(latchPin, HIGH);
    }

You noted you have been frustrated for days working on this, and your code examples have mixed coding conventions, so perhaps you are finding many different code examples and trying various ones until you find something that works. I would encourage you, however, to take it slow and read through each line of code you have and make sure you understand exactly what it does, and be sure you can explain to yourself why each statement or command is there. This will help you to see the path of execution for your code and be able to diagnose bugs and come up with solutions that directly fix the problem, rather than swapping and and out a multitude of snippets from websites and forums.


body:
You already had SPI in use. You can connect SCK to SRCLK, MOSI to Serial data in, and pick a pin for RCLK. D10 needs to be an output for the device to be SPI master. If it's used already, use that.

Then simply clock in the needed data:

    digitalWrite (rclk, LOW);
    SPI.transfer (yourData);
    digitalWrite (rclk, HIGH); // outputs update on this rising edge

MRCLR connects to +5, OE/ connects to Gnd.

    SPI.begin();

in setup() turns on the defaults of 4 MHz clock rate, MSBFIRST, and SPI Mode 0, that's all you need.


message:
how to read all line except the first line?

is there a way to read only 2nd up to the last line except for the first line?

here's my sample code

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

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      // re-open the file for reading:
      myFile = SD.open("test.txt");
      if (myFile) {
        Serial.println("test.txt:");

        // read from the file until there's nothing else in it:
        while (myFile.available()) {
          Serial.write(myFile.read());

        }
        // close the file:
        myFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
    }

    void loop() {
      // nothing happens after setup
    }

body:
Why don't you do reads for the first line, ignore them and start the while thus:

    while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
    while (myFile.available()) {
      Serial.write(myFile.read());
    }


body:
skip first line

    bool firstLine = true;
    while (myFile.available()) {
      int c = myFile.read();
      if (firstLine) {
        if (c == '\n') {
          firstLine = false;
        }
      } else {
        Serial.write(c);
      }
    }


message:
Custom atmega32u4 board crystal issue

So I built an custom board based on the Atmega32u4. Schematics attached.

I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.

The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..

The crystal I'm using is an Epson X1G004451000212.

Any idea why is this happening?

[![Circuit schematic][1]][1]

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

body:
That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.

Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?

Is the part oriented the correct way so it receives power and Gnd correctly?

Also, is it's performance any better than if you had just used a crytal?

https://support.epson.biz/td/api/doc_check.php?dl=brief_SG7050CAN&lang=en

vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6)
https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25


message:
Determining direction from IMU accelerometer data

I am learning how to integrate sensors on arduinos and read their data.

My ultimate purpose is to place the IMU on a robot and use it in determining the robots location in an environment.

Using the following code, I am able to get accelerometer and temperature data:

    // (c) Michael Schoeffler 2017, http://www.mschoeffler.de

    #include "Wire.h" // This library allows you to communicate with I2C devices.

    const int MPU_ADDR = 0x68; // I2C address of the MPU-6050. If AD0 pin is set to HIGH, the I2C address will be 0x69.

    int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
    int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
    int16_t temperature; // variables for temperature data

    char tmp_str[7]; // temporary variable used in convert function

    char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
      sprintf(tmp_str, "m", i);
      return tmp_str;
    }

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
      Wire.write(0x6B); // PWR_MGMT_1 register
      Wire.write(0); // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
    }
    void loop() {
      Wire.beginTransmission(MPU_ADDR);
      Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
      Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
      Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

      // "Wire.read()<<8 | Wire.read();" means two registers are read and stored in the same variable
      accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
      accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
      accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
      temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
    //  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
    //  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
    //  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

    //  // print out data
      Serial.print("aX = "); Serial.print(convert_int16_to_str(accelerometer_x));
      Serial.print(" | aY = "); Serial.print(convert_int16_to_str(accelerometer_y));
      Serial.print(" | aZ = "); Serial.print(convert_int16_to_str(accelerometer_z));
    //  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]
      Serial.print(" | tmp = "); Serial.print(temperature/340.00+36.53);
    //  Serial.print(" | gX = "); Serial.print(convert_int16_to_str(gyro_x));
    //  Serial.print(" | gY = "); Serial.print(convert_int16_to_str(gyro_y));
    //  Serial.print(" | gZ = "); Serial.print(convert_int16_to_str(gyro_z));
      Serial.println();

      // delay
      delay(1000);
    }

Giving me output like the following:

    aX =   3526 | aY =   -968 | aZ = -11988 | tmp = 25.89
    aX =   3478 | aY =   -936 | aZ = -12020 | tmp = 25.91
    aX =   3530 | aY =   -922 | aZ = -12002 | tmp = 25.91
    aX =   3490 | aY =   -896 | aZ = -12006 | tmp = 25.94
    aX =   3498 | aY =   -898 | aZ = -12036 | tmp = 25.91
    aX =   3520 | aY =   -916 | aZ = -12050 | tmp = 25.91
    aX =   3466 | aY =   -924 | aZ = -11960 | tmp = 25.91
    aX =   3492 | aY =   -944 | aZ = -12026 | tmp = 25.92
    aX =   3510 | aY =   -924 | aZ = -12048 | tmp = 25.91
    aX =   3440 | aY =   -942 | aZ = -11980 | tmp = 25.91
    aX =   3514 | aY =   -924 | aZ = -12066 | tmp = 25.91
    aX =   3484 | aY =   -944 | aZ = -11968 | tmp = 25.92
    aX =   3490 | aY =   -944 | aZ = -12012 | tmp = 25.92
    aX =   3458 | aY =   -952 | aZ = -11944 | tmp = 25.92

**What I need to know is how do I determine what direction my robot is moving in based on the accelerometer output?**

body:
First you have to test, in which orientation the sensor on the IMU board is mounted. You can use your test sketch for this. If you don't move the sensor it will show you the gravitational force, which always points down. Orientate the IMU in such a way, that aX and aY are near zero. Now you know where up and down are. Move the IMU to the sides, until you found the direction, where only aX changes considerably, while aY is staying near zero. Then you have found the next direction.

Finally mount the IMU in your robot in the found orientation. Since you know, which of aX, aY and aZ change with which direction, you know the direction of the robots movement.


body:
You can't with any great accuracy.

The acceleration vector from the accelerometer is a combination of two things:

* Gravitational acceleration
* Acceleration due to change in the robot's velocity.

If the robot is travelling at a constant speed, there is no acceleration due to change in velocity, so the accelerometer will only be measuring gravity. No idea then how far the robot has gone.

If the robot is turning on the spot, again there is not acceleration change. So you don't know which direction the robot is facing!

You can get a rough idea of speed by integrating the acceleration, and distance by integrating speed. However any errors quickly accumulate, and thus the absolute distance may be very poor.

To get velocity (speed with a direction) or absolute position, you will need a magnetometer or gyroscope to estimate rotation.


body:
You haven't described your robot but if it is a typical wheeled vehicle that can drive forward and backward, the accelerometer can give you one of those two directions (which is already known because you or your sketch commanded it). If in addition your robot can steer, the the accelerometer will give show a side force (aka centripetal acceleration or centrifugal force) in the direction of the turn.

Figuring out how much the robot turned (in order to get its current direction) is mathematically straight-forward but practically, it is noisy and subject to accumulating errors, as already pointed out.

If knowing orientation, thus direction of travel, is your goal, wouldn't a electronic compass (magnetometer) be of more help?


message:
Arduino IDE 1.8.6 not starting.

My Arduino IDE is not getting started. It just crashes before opening up. I don't know what the problem is. It was working well enough before without any issues.

This is what I see after running the arduino_debug.exe in the command line

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

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

Note: I added a library (DHT) to work with my humidity and temperature sensor and since after then, this issue comes up. I tried to reinstall it like more than 7 times, but the issue still persists.

Please help me with it. Thanks.

body:
The cause of the problem is that you have a corrupted library index file. The solution is to delete the file, which will force the Arduino IDE to download a (hopefully) uncorrupted fresh version from the Internet:

1. Open the C:\Users\JK\AppData\Local\Arduino15 folder
1. Delete the file library_index.json
1. Try starting the Arduino IDE again

---
For anyone encountering this problem who is using an operating system other than Windows, the location of library_index.json is different:

On Linux:

`/home/{username}/.arduino15` (a.k.a. `~/.arduino15`)

On macOS:

`/Users/{username}/Library/Arduino15`

If using the Arduino IDE in [portable mode](https://www.arduino.cc/en/Guide/PortableIDE):

`{Arduino IDE installation folder}/portable`

---

The issue of a corrupted library index file preventing the Arduino IDE from starting has been reported to the Arduino developers and they are already working on a fix:

https://github.com/arduino/Arduino/issues/7937


body:
Had same issue when migrating from Arduino IDE 1.8.2 to 1.8.9

In my case, deleting just the library_index.json was not enough but a good hint.

I did also delete the subdirectories of "packages" directory (boards which I downloaded- the ESP32 board and the ESP8266 board), and all files (not folders) in C:\Users\\%username%\AppData\Local\Arduino15\ except the preferences.txt

This solved the issue for me.


body:
I had the same problem this morning when trying to launch the IDE (1.8.3).
I'm running Linux Mint 18.

Running the IDE from the command line showed the following errors:

[![Arduino IDE 1.8.3 launch errors][1]][1]

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

The output hints at a problem with 'packages' so I renamed ~/.arduino15/package_index.json to package_index.json.old. The IDE was then able to be launched. 'package_index.json' can then be rebuilt by starting your boards manager through 'Tools->Board'.


message:
Flickering LED when servo moves

I just got to play around with Arduino lately so I'm really new on this stuff and sorry for the grammar error.

I got a work where I need to turn the LED on all the time, my plan is to add a slow fade in and fade out later but the problem occurs when I add the servo.

Everytime servo starts moving slowly or fast the LED kinda flickering/dim like it lost power and come back to normal after the servo stops moving.

Here's the scheme I used and the code, I only change some delay to 5ms and so to test it out but no matter what the led is keep flickering.

Im using nano v.3 clone if its matter.

[![exactly like this, I tried to add a resistor but no luck][1]][1]

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

    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 100;    // variable to store the servo position
    int ledpin3 = 3;

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      pinMode(ledpin3, OUTPUT);
    }

    void loop() {
      digitalWrite(ledpin3, HIGH);
      delay(1000);

      for (pos = 99; pos <= 150; pos += 1) { // goes from 0 degrees to 180 degrees
                                             // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable ‘pos’
        delay(15);                       // waits 15ms for the servo to reach the position
      }

      for (pos = 150; pos >= 30; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable ‘pos’
        delay(15);                       // waits 15ms for the servo to reach the position
      }

      for (pos = 30; pos <= 99; pos += 1) { // goes from 0 degrees to 180 degrees
                                            // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable ‘pos’
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

body: If you are powering the arduino via usb try not to do that or plug it in to an usb 3.0 (and higher) port. The reason for this is that the servo draws a lot of power and the standard usb 2.0 with 0.5A can't handle the load and you got an voltage drop. And in that period of time the led goes off. usb 3.0 (and higher) can handle up to 1.5A so this souldn't be an error.


message:
How to avoid electromagnetic interference on ESP32 input

I've realized a simple circuit like the following, in order to implement a rain gauge that I can access via HTTP:

[![image][1]][1]

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

With the following sketch:

    #include <WebServer.h>
    #include <WiFi.h>
    #include <WiFiClient.h>

    /**
     * This constant is calculated with the following procedure:
     * - Area of pluviometer is 55 cm^2
     * - Volume of test water is 100 cm^2
     * Resulting height of water is 1.82 cm. Using this water quantity, generates 40 ticks of the pluviometer. So every tick is 0.455 mm of rain.
     */
    const double millimetersPerTick = 0.455;
    const char* ssid = "*********";
    const char* password = "*********";

    WebServer server(80);

    /* LED pin */
    byte ledPin = 2;
    /* pin that is attached to interrupt */
    byte interruptPin = 14;
    /* hold the state of LED when toggling */
    volatile byte state = LOW;
    volatile int interruptCounter = 0;
    int numberOfInterrupts = 0;
    portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

    void IRAM_ATTR handleInterrupt() {
      portENTER_CRITICAL_ISR(&mux);
      interruptCounter++;
      portEXIT_CRITICAL_ISR(&mux);
    }

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

      // WIFI initialization
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      pinMode(ledPin, OUTPUT);
      /* set the interrupt pin as input pullup*/
      pinMode(interruptPin, INPUT_PULLUP);
      /* attach interrupt to the pin
      function blink will be invoked when interrupt occurs
      interrupt occurs whenever the pin change value */

       // Notify wifi connection
      digitalWrite(ledPin, HIGH);
      delay(2000);
      digitalWrite(ledPin, LOW);

      attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, RISING);

      server.on("/", []() {
        server.send(200, "text/plain", String(millimetersPerTick * numberOfInterrupts));
        numberOfInterrupts = 0;
      });

      server.onNotFound([]() {
        server.send(404, "text/plain", "Not found");
      });

      server.begin();
    }

    void loop() {
      server.handleClient();

      if(interruptCounter>0) {
        portENTER_CRITICAL(&mux);
        interruptCounter--;
        portEXIT_CRITICAL(&mux);

        numberOfInterrupts++;
        Serial.print("An interrupt has occurred. Total: ");
        Serial.println(numberOfInterrupts);
        state = !state;
        digitalWrite(ledPin, state);
        delay(100);
        state = !state;
        digitalWrite(ledPin, state);
      }
    }

The main issue of this circuit is that if I connect the AC plug it suffers from interferences from the household electricity. For example if I turn on the light, the interrupt is called. I tried also to buy an EMI filter like [this][3] but it doesn't reduce the problem. What can I do to avoid this?

  [1]: https://i.stack.imgur.com/RMIwx.png
  [2]: https://i.stack.imgur.com/9DsTI.jpg
  [3]: https://www.aliexpress.com/item/1PCS-LOT-EMI-Filter-CW1B-10A-L-10A-115V-250V-CW1B-50-60Hz/32852691198.html

body:
I researched the power supply shown in your photo and found this comment:
[![from randomnerdtutorials][1]][1]

[esp8266 hilink][2]

  [1]: https://i.stack.imgur.com/2ttVJ.jpg
  [2]: https://randomnerdtutorials.com/esp8266-hi-link-hlk-pm03/


message:
Two serials can't work on the same speed

I have a device which sits on pins 10/11 of Arduino UNO. I am trying to send commands from my PC using Arduino to relay my commands to the device via Serial.

The problem is that if I use speed 9600 both for device and USB communication, then my commands gets damaged. Some letters are replaced by strange symbols, etc. The device uses 9600 baud rate.

If I change speed of the PC communication to 4800 (or any speed other than 9600), everything is fine. But I have to use different speeds for the communication.

I am not comfortable with the workaround, because I don't understand what's going on. Could somebody explain why the same serial port speeds causes problems?

Here is my code:

    #include <SoftwareSerial.h>

    #define rxPin 11
    #define txPin 10

    SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

     void setup()
     {
       digitalWrite(4,HIGH); // 1 - disable
       mySerial.begin(9600);
       Serial.begin(19200);
       while (!Serial) {;}  // wait for serial port to connect. Needed for native USB port only
       Serial.println("Begin");
     }

     void loop()
     {
      if (mySerial.available())
      {
        char c = mySerial.read();
        Serial.write(c);
      }
      if (Serial.available())
      {
        char c = Serial.read();
        mySerial.write(c);
      }
     }

body:
If you are confident with the device you connected to your Arduino Uno in terms of it has a reliable serial communication firmware running on it, You might need some buffering before relaying your commands;

    #define RECORD_SIZE 100
    void loop()
    {
     RelayDataIfAvaliable();
    }
    void RelayDataIfAvaliable() {
     static char buffer[RECORD_SIZE];
     if (Serial.available())
     {
      if (readline(Serial.read(), buffer, RECORD_SIZE) > 0) {
       mySerial.write(buffer);
      }
     }
    }
    //Reads entire incoming data into buffer once
    int readline(int readch, char *buffer, int len)
    {
     static int pos = 0;//This was zero initially. But, it was missing first character!
     int rpos;
     //Serial.print(readch);
     if (readch > 0) {
      switch (readch) {
      case '\n': // Ignore new-lines
       break;
      case '\r': // Return on CR
       rpos = pos;
       pos = 0;  // Reset position index ready for next time
       return rpos;
      default:
       if (pos < len - 1) {
        buffer[pos++] = readch;
        buffer[pos] = 0;
       }
      }
     }
     // No end of line has been found, so return -1.
     return -1;
    }


body:
I spent some time playing with your code and it seems your code actually loops the serial therefore if they are both set at 9600 as example and you print what the other one is sending like in your code you end up in a loop if you want to read what your serial is sending it is better put that values in a variable and send it

if you load your code you will get the following message in the arduino IDE once you try to connect to the serial monitor:

Error opening serial port 'COM8'. (Port busy),

your port is busy because the one serial port is reading the other all the time

one more thing I would use the following if you want to repeat a serial port:

  if (mySerial.available())
  {
    //char c = mySerial.read();
    Serial.write(mySerial.read());
  }

Hope this hels you


message:
Cannot run WiFi sketch on ESP-01

I can upload simple sketch on my ESP-01 like:

    void setup() {
      Serial.begin(115200);
      Serial.println("Hello there");
    }
    void loop() {
      Serial.println("Hello from loop");
      delay(1000);
    }
I also ran successfully the sample ESPWebServer -> HelloServer

But if just modify my sketch to include `#include <ESP8266WiFi.h>`

    #include <ESP8266WiFi.h>

    void setup() {
      Serial.begin(115200);
      Serial.println("Hello there");
    }
    void loop() {
      Serial.println("Hello from loop");
      delay(1000);
    }
I got this result in the serial monitor:

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

    wdt reset
    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    vbb28d4a3
    ~ld

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

-          FTDI GND - GND
- ESP TX - FTDI RX
- ESP RX - FTDI TX
- ESP VCC - VCC 3.3V
- ESP GND - GND
- ESP CH_PD - VCC
- ESP GPIO2 - VCC
- ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

[![Cabling ESP-01 to TTL][1]][1]

Also, regularly my sketch fails to load correctly:

-Sometimes it does not load at all and I get this after compilation before uploading starts:

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed
- Sometimes it fails at the end of the upload:

    Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
    ................................................................................ [ 31% ]
    ................................................................................ [ 63% ]
    ................................................................................ [ 95% ]
    ..........warning: espcomm_send_command: didn't receive command response
    warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
    warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed
Any idea about what is wrong ?

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

body:
FTDI adapters often don't provide enough current to run the power-hungry wifi features of the ESP8266. So as soon as you fire up wifi, you brownout the chip and cause it to reset.

Use a battery, a dedicated ESP8266 flasher, a 3.3v LDO, or something besides the on-board 3.3v connection the USB-Serial adapter provides.


message:
for() loop doesn't seem to break?

So I'm quite new to the whole Arduino coding but constructed a sketch that does work, but I think it doesn't work properly. So I'd love to get some advice on how to improve it.

This script is currently running on a Wemos ESP8266 chip attached to a 1 meter WS2812 144 LED strip.

My questions:

1. The loop is set to break when fadein is higher then 254.
When I try to break it at `fadein == 255` the loop doesn't work anymore as it the fadein value directly jumps to 255. Why?

2. When I set the delay to zero the led flicker due to too fast updating. however, this flickering continues even after the for loop is broken, which makes me conclude that the for loop is still running even when the break is applied.

    Of course this is no longer an issue when the delay is set higher (as it is supposed to be) but it still seems a waste of processing power to keep the for loop active while it's not doing anything new anymore
how can i completely stop the loop from being executed?

3. How can this be done differently / more effective?

The code

    #define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
    #include <FastLED.h>                                                  //add fastled lib
    #define NUM_LEDS 144                                                  //set number of leds
    #define DATA_PIN D4                                                   //set data pin leds

    CRGB ledStrip[NUM_LEDS];                                              //init led strip
    int fadeIn = 8;                                                       //init fade in counter
    int led = 0;                                                          //init led counter

    void setup() {
      Serial.begin(115200);                                               //setup comm channel
      FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
    }

    void loop()
    {
    for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
        ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
        FastLED.show();                                                   //show led color
        ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
        delay(3);
        if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
          break;                                                          //stop led animation
        }
    }

        if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
          fadeIn+=16;                                                      //increase fadeIn value with 16
        }
        if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
          Serial.println(led);                                             //print led counter value
          Serial.println(fadeIn);                                          //print fadein value
        }
        if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
          fadeIn = 255;                                                     //clamp fadeIn value to 255

        }

    }

body:
1. Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16.  So: 8, 24, ... 248, 264, ... .  It is never exactly 255.  So you never break out of your "for" loop.

2. There is only 1 delay in your example code.  It is difficult to associate the described behavior in your question and the location of the delay.

3. Arduino programming is actually C and C++ programming.  Developed at Bell Labs, this language has been around for decades and there are countless books on the subject.  Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.


body:
You close your `for()` loop right after the if statement that contains the break. No where in that `for()` loop do you change `fadeIn`, so there is nothing to break out of.

If you move the `}` that closes the for loop to below the code that changes `fadeIn`, then the `break` has an opportunity to be executed:

    void loop() {
      for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
        ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
        FastLED.show();                                                   //show led color
        ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
        delay(3);
        if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
          break;                                                          //stop led animation
        }

        if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
          fadeIn+=16;                                                      //increase fadeIn value with 16
        }
        if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
          Serial.println(led);                                             //print led counter value
          Serial.println(fadeIn);                                          //print fadein value
        }
        if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
          fadeIn = 255;                                                     //clamp fadeIn value to 255
        }
      }
    }


body:
This is doing an assignment, not the comparison  you are expecting

    if (led = 144

Need == for the comparison


body:
Ok, thanks for all your help, found the solution to make it stable.
I think I got thrown off by the fact the led = 144 did (magically) seem to work outside the loop but led == 144 didn't work at all.

turns out i was counting the leds wrong (it's from 0-143 instead of 1-144) and that made all the other pieces fall into place.

tnx

    #define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
    #include <FastLED.h>                                                  //add fastled lib
    #define NUM_LEDS 144                                                  //set number of leds
    #define DATA_PIN D4                                                   //set data pin leds

    CRGB ledStrip[NUM_LEDS];                                              //init led strip
    int fadeIn = 8;                                                       //init fadein value
    int fadeIncr = 16;                                                    //init fadein increments

    void setup() {
      Serial.begin(115200);                                               //setup comm channel
      FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
    }

    void loop()
    {
    for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
        ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
        FastLED.show();                                                   //show led color
        ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
        delay(1);
        if (led == 143) {                                                  //when the 144th led is reached and the fadein value is less then 255
          fadeIn+=(fadeIncr);                                              //increase fadeIn value with 16
          fadeIn=constrain(fadeIn, 0, 255);                                // clip value range
            Serial.println(led);                                           //print led counter value
            Serial.println(fadeIn);                                        //print fadein
        }
        if (fadeIn == 255) {                                               //if the fadeIn value exceed 255
          break;                                                           //stop led animation
        }
      }
    }


message:
Atmega328p - Going low power 1.8V using 4Mhz oscillator - Bootloader flash

I would like to use an **Atmega328p** micro-controller with a 4 Mhz oscillator in order get some **low power consumptions**. I am using an Arduino board to **flash the bootloader** into the Atmega.

**EDIT**

In order to compile the optiboot bootloader I had to install the avr-libc package and clone the repo

    sudo apt-get install avr-libc
    git clone https://github.com/Optiboot/optiboot.git

and edited the Makefile in `/optiboot/bootloaders/optiboot/Makefile` by adding a new entry called atmega328_4

    HELPTEXT += "target atmega328     - ATmega328p 4Mhz\n"
    atmega328_4: TARGET = atmega328
    atmega328_4: MCU_TARGET = atmega328p
    atmega328_4: CFLAGS += $(COMMON_OPTIONS)
    atmega328_4: AVR_FREQ ?= 4000000L
    ifndef BIGBOOT
    atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7e00 -Wl,--section-start=.version=0x7ffe
    else
    # bigboot version is 1k long; starts earlier
    atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7c00 -Wl,--section-start=.version=0x7ffe
    endif
    atmega328_4: $(PROGRAM)_atmega328_4.hex
    atmega328_4: $(PROGRAM)_atmega328_4.lst

    atmega328_4_isp: atmega328
    atmega328_4_isp: TARGET = atmega328
    atmega328_4_isp: MCU_TARGET = atmega328p
    ifndef BIGBOOT
    # 512 byte boot, SPIEN
    atmega328_4_isp: HFUSE ?= D9
    else
    # 1k byte boot, SPIEN
    atmega328_4_isp: HFUSE ?= D9
    endif
    # Low power xtal 46MHz) 16KCK/14CK+65ms
    atmega328_4_isp: LFUSE ?= 7D
    # 2.7V brownout
    atmega328_4_isp: EFUSE ?= FE
    atmega328_4_isp: isp

I saved the file, run the make command and got the following error:

    userk@norepinephrine:~/development/git/optiboot/optiboot/bootloaders/optiboot$ make atmega328_4
    avr-gcc (GCC) 4.9.2
    Copyright (C) 2014 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    BAUD RATE CHECK: Desired: 115200, Real: 125000, UBRRL = 3, Difference=8.5%
    avr-gcc -g -Wall -Os -fno-split-wide-types -mrelax -mmcu=atmega328p -DF_CPU=4000000L  -DBAUD_RATE=115200 -DLED_START_FLASHES=3           -c -o optiboot.o optiboot.c
    optiboot.c:348:6: error: #error BAUD_RATE off by greater than 5%
         #error BAUD_RATE off by greater than 5%
          ^
    optiboot.c:359:2: error: #error Unachievable baud rate (too fast) BAUD_RATE
     #error Unachievable baud rate (too fast) BAUD_RATE
      ^
    <builtin>: recipe for target 'optiboot.o' failed
    make: *** [optiboot.o] Error 1

So I changed the -DBAUD_RATE parameter to 19200 and rerun the make command

    BAUD_RATE_CMD = -DBAUD_RATE=19200

Then 2 new files were created: optiboot_atmega328_4.elf and optiboot_atmega328_4.hex

Then I copied these files into the arduino configuration folder located
 at: `/home/userk/.arduino15/packages/arduino/hardware/avr/1.6.21/bootloaders/optiboot`

**TIDE**

I am using a **custom** board configuration file board.txt

    ##############################################################

    nz.name=Arduino Noize

    nz.vid.0=0x2341
    nz.pid.0=0x0043
    nz.vid.1=0x2341
    nz.pid.1=0x0001
    nz.vid.2=0x2A03
    nz.pid.2=0x0043
    nz.vid.3=0x2341
    nz.pid.3=0x0243

    nz.upload.tool=avrdude
    nz.upload.protocol=arduino
    nz.upload.maximum_size=32256
    nz.upload.maximum_data_size=2048
    nz.upload.speed=19200

    nz.bootloader.tool=avrdude
    nz.bootloader.low_fuses=0x7D
    nz.bootloader.high_fuses=0xD9
    nz.bootloader.extended_fuses=0xFE
    nz.bootloader.unlock_bits=0x3F
    nz.bootloader.lock_bits=0x0F
    nz.bootloader.file=optiboot/optiboot_atmega328_4.hex

    nz.build.mcu=atmega328p
    nz.build.f_cpu=4000000L
    nz.build.board=AVR_UNO
    nz.build.core=arduino
    nz.build.variant=standard

**Flashing the Bootloader**
I have followed these steps:

 -  Uploaded the ArduinoISP sketch onto the Arduino UNO board.

 -  Wired up the Arduino board and microcontroller as shown in the diagram below

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

 - Select "Arduino Noize" from the Tools > Board menu.

 - Select "Arduino as ISP" from Tools > Programmer
    Run Tools > Burn Bootloader

At this point I got a success message from IDE. So the bootloader has been correctly flashed into the Atmega328p

**The Problem**

When I try to upload a sample sketch (blink) using the wiring below I get a **timeout** from the IDE.

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

I have double checked the connections but the sketch doesn't upload.
Do you have any advice?

  [1]: https://i.stack.imgur.com/5zCLC.png
  [2]: https://i.stack.imgur.com/krPb7.png

body:
As Gerben notes in the comments, the bootloader has to know how fast the board is running. It uses this to work out the baud rate settings for the serial communication.

If you haven't compiled the bootloader yourself with the right clock settings you will probably find that it is operating at a quarter of the speed you expect it to. Dividing your upload baud rate by four in your board settings may make it work, but you really should compile the bootloader to match the board properly.


body:
As mentioned before, you need to compile the Optiboot bootloader with the correct clock frequency. Here's a guide that shows you how to do that, as well as adding an option to the Arduino IDE menu to select the right clock speed without having to add your own board definition.

[Optiboot - ATmega328P at custom frequency](https://tttapa.github.io/Pages/Arduino/Bootloaders/ATmega328P-custom-frequency.html)


body:
    nz.bootloader.low_fuses=0x7D
    nz.bootloader.high_fuses=0xD9
    nz.bootloader.extended_fuses=0xFE

Extended fuse byte. bits 2,1,0 determine the brown out level (bits 7-3 not used)
110 = 1.7 to 2.0V, 1.8 typical

Low fuse byte bits 3,2,1 determine the clock source
110 = low power crystal oscillator in 3-8 MHz range.

So those settings look okay.


message:
Checking a jumper between two pins on Arduino

I'm in the process of making a tag scanner (which transfers the tag ID to the computer), and I figured I'd use an Arduino Micro for that and just use the keyboard function on it to save myself a whole lot of hassle. From what I've read, however, having the keyboard open all the time can make it tricky to program it.

I figured my solution would be to use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard. That way I should be able to put the jumper on if I need to program it, and leave it off if I just want it to run.

Unfortunately, I've never really done anything like this before, and I don't really want to just start plugging things around and run the risk of damaging my board. I've read around a bit, but I figured I wanted to bounce my ideas off of someone before I try it.

First, would you recommend a different approach? I did see a question that used the internal pullup resistor to check if a jumper connected it to ground, but since I only want to make this check once, is that a good route to go?

Secondly, if I connect it between two pins, am I correct in thinking I'd need a resistor between them (the Arduino website suggested 470ohm to 1kohm when connecting to other devices, so I'm guessing this would be a good number)? How would I set the pins up to make this work; should I put one pin as output and the other as input, and just read the input pin (after which I'd simply turn the output pin off), or would I need to add additional connections?

Thirdly, since this will use the USB port on the Arduino that is used to program it, is there a way to wipe the code from the Arduino in case of Serious Bugs, or is it possible to "brick" the board by tying up the USB permanently? I mean, I'll definitely make use of the Serial connection to test the output (and also to test the above jumper), so I think the odds are small enough to try it anyway, but... better safe than sorry?

body:
First off, the premise:

> having the keyboard open all the time can make it tricky to program

is completely false.

The problems that people experience with programming are when the Arduino is *sending keystrokes all the time without external stimulus*.  This makes it tricky to do *anything* - not just program. Just like it's hard to write a letter when you have a cat walking all over your keyboard.

So as long as you aren't just sending keypresses all the time, and only send them when you actually read a card, there is no problem for you to try and fix.

Secondly, the idea:

> use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard.

is overly complex and meaningless.  If all you want to do is check a state of "set" or "not set" using some external "device", what you're talking about is a *button*, or a *switch*.  You don't need two pins for that - only one. And there's a myriad of tutorials available on the internet showing you in detail how to read the state of a button (or switch). (Hint: use a pin set to INPUT_PULLUP and connect that pin to GND to "activate" it. Include a small [100Ω] resistor for safety if you like).

So in summary:

1. Unless you're being really daft in your program, there is no problem to solve.
2. You are over-thinking your solution.


body:
First of all, welcome here. Usually questions should contain, well, only one question ;)

In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

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

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

<!-- End schematic -->

In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".

In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.

The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.

The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

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

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

<!-- End schematic -->

You will need, in your setup, to set the pin as INPUT_PULLUP, and then check the value you read:

    const byte jumperPin = 2;

    void setup() {
      pinMode(jumperPin, INPUT_PULLUP);
    }

    void loop() {
      if (digitalRead(jumperPin) == LOW)
      {
     // Jumper is inserted
      }
      else
      {
     // Jumper is not inserted
      }
    }

This is what the `DigitalInputPullup` example is for...

Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.

Luckily any arduino board can be used for this task; you will just need to download on another board the sketch `ArduinoISP` (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board


message:
1-10 volt analog signal

I have an Arduino project where I am using an ESP8266 (Wemos D1 mini) powered via USB. I want/need to output an analog voltage from 0 to 10V.

**Goal:**
A solution that is pre-made (eg a shield or sparkfun type module) or easy to build circuit that does not require a new power supply (besides the ones I have which is 3.3V and 5V, thanks to Wemos USB power).

Many devices allow you to control them using a 1-10V signal. I have two LED drivers at home that I would like to interface with: [specs1][1], [specs2][2].

What would be the easiest solution to generate a 1-10 Volt signal? Is there a module I can use?

I read about Op-amps but I don't yet have the knowledge to build one myself.
Another method is a DAC, but that seems to require a separate 10 Volt power supply.

  [1]: http://www.hidealite.se/Archive/FilesArchive/IM00259_JollyRound350_700mA_several_201706.pdf
  [2]: http://www.hidealite.uk/Archive/FilesArchive/IM00128_MDR_45_60_sv_en_fi_201601.pdf

body:
You do not need a DAC. In this 'regulation cases' PWM on digitalPin is used. See [analogWrite][1] Arduino function.

I use Grove MOSFET module to have PWM of desired voltage. The MCU generates a 3.3 V PWM. MOSFET module gets in my case 5 V as input voltage. You would use 10 V as Vin. MOSFET switches the 10 V line on and off at 'PWM speed' resulting in 10 V PWM.

As 10 V source you could use [a 'boost' converter][2], to convert 5 V to 10 V.

This is the schema of the Grove MOSFET module:

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

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
  [2]: https://www.elecrow.com/boost-and-buck-voltage-converter-lm2577-lm2596-p-1254.html
  [3]: https://i.stack.imgur.com/Fu9kQ.png


body:
The ADM660, link below,
>is a charge-pump voltage converter that can be used to either invert the input supply voltage giving VOUT = -VIN or double it (ADM660 only) giving VOUT = 2 x VIN.

It accepts an input range between 1.5V-7V so if you use the 5V from the Wemos USB power you'll be able to reach the desired 10V for your application, and it's cheap :)

http://www.analog.com/media/en/technical-documentation/data-sheets/ADM660_8660.pdf


message:
Looking for a waterproof SPI temperature sensor

In my current project I'm using a DS18B20, which seems to be the only temperature sensor to show up when googling for waterproof temperature sensor for an arduino.

The sensor itself is fine, however, I'm outputting the sensor's data to a SPI screen, and whenever the sensor is called to read data I believe the SPI communication is interrupted because of 1-Wire, and you can see a white flicker on the screen. The background LED is flashing more brightly for one frame. It's almost unnoticeable, but it bothers me.

I'm not using delays, and I'm not redrawing unnecessary elements on the screen again. Only dynamic elements are refreshed when they need to, static elements are only drawn once on the screen. The sensor is called every 5 seconds with a comparison:

    if(currentTime - lastTimeQueried >= delay){
        lastTimeQueried = currentTime;
        temperature = new temperature;
        return temperature;
    } else {
        return temperature;
    }

I also tried a function where I'm constantly calling the sensor and only drawing on the screen if there's a change in temperature, but then the screen is flickering all the time. Thus I conclude that the flickering is caused by the actual calling of the sensor, and not from redrawing anything on the screen.

So I'm wondering if there's an alternative to the DS18B20 that communicates via SPI, and that I can use in an aquarium, so I don't have to use both protocols in my project.

Edit:

As requested some more of my code and wiring:

The screen is wired to the ICSP headers on my Arduino Mega 2560 and power is supplied via 5V on a powersupply that is connected to my breadboard.

The DS18B20 is wired to pin 29 on the Arduino and is also supplied with power via 5V on the same powersupply.

    //TFT SPI
    #define TFT_DC 9
    #define TFT_CS 10
    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

    //SD Card Reader SPI
    //#define SD_CS 4

    //Touchscreen I2C
    UTouch  myTouch(5, 8, 6, 7, 2);  //(T_CLK, T_CS, T_DIN, T_DOUT, T_IRQ)

    #define ONE_WIRE_BUS 29
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

Here are some more variables that I have defined to help with using the sensor:

    //Temperature measurement
    unsigned long lastTempMeasure;  //Holds last unix timestamp temperature was measured at
    char tempMeasureDelay = 5;      //Call temperature every 5 seconds
    float sensorTemp;               //Holds measured temperature

In my loop I then use this function:

    tft.print(temperatureCall());

and then:

    float temperatureCall(){
      //get unix time for right now
      unsigned long currentUnix = now();

      //if 5 seconds passed since last poll, ask for new temperature, else return old measurement
      if(currentUnix - lastTempMeasure >= tempMeasureDelay){
        lastTempMeasure = currentUnix; //save last polling time

        sensors.requestTemperatures();
        sensorTemp = sensors.getTempCByIndex(0);

        return sensorTemp;
      } else {
        return sensorTemp;
      }
    }

As I said, the flicker only occurs when these two are used every 5 seconds:

    sensors.requestTemperatures();
    sensorTemp = sensors.getTempCByIndex(0);

Edit 2:

Pic of wiring:

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

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

body: There is a delay in the DallasTemperature `requestTemperatures()` function - it blocks until the temperature conversion is complete unless you have previously called `setWaitForConversion(FALSE)`. If you did that, you would still have to wait for the conversion but you can do it an a non-blocking manner, and I don't see that happening in your code.


message:
problem with reading PS3 controller buttons

I'm working on a camera slider mount with an X stepper (to move along slider), Y stepper (pan left right) and Z stepper (tilt up down). All of this is being controlled by a PS3 controller (PS3BT library).

I've implemented a feature in which all three steppers move from one saved position to other and then back again.. this keeps repeating infinitely. It works fine - except I can't stop it - it's more of a programming issue I think. Here's the code in question

    // MultiStepper instance - at the top somewhere
    MultiStepper StepperControl;

    void loop(){
        if(PS3.getButtonClick(START)){ // START to start movement between two POS's.
            Serial.print("\n Starting Movement between POS1 and POS2");
            while(!PS3.getButtonClick(CROSS)){
              StepperControl.moveTo(POS1); // go to POS1
              StepperControl.runSpeedToPosition();
              delay(200);
              StepperControl.moveTo(POS2); // go to POS2
              StepperControl.runSpeedToPosition();
              delay(200);
            }
          }
    }

My issue is that pressed X (cross) on the keypad, doesn't quit out of the loop. What I feel is happening is that the loop is running too fast and all the moveTo() commands are stacking on top of each other. And so, even if I do press X, too many moveTo() commands have already happened and it just keeps running those "queued" commands.

I've also tried putting an if statement inside the while loop that breaks out of the loop when CROSS is pressed - no luck.

// This isn't the entire code, just the parts I think are relevant.

body:
The `while(!PS3.getButtonClick(CROSS))` is only checked once per loop, so your system will complete a move to POS1, wait 200ms, complete a move to POS2, and wait another 200ms before it can check the controller for another button press.

`runSpeedToPosition()` is "blocking", which means NOTHING else can happen while it is doing it's task.

Instead, you probably want to avoid blocking functions and set up a [finite state machine][1] and use the `run()` function of `AccelStepper`, which you should call as often as you can and it will move the stepper one step toward the target position, if it's not yet at the target position.

The following rewrite is not tested, but the general structure should show you how you can change the way the program is written. You should think of the `loop()` function running and completing a million times a second, and each time through, you check the **state** (that is, on what step is the system currently on) and act accordingly. Change to a new state when appropriate.

In the example, there are 5 states, corresponding to all possible combinations of what your program could be doing:

 - STOPPED: the initial state, the stepper has no target
 - RUNTO1: the stepper is moving toward POS1, but hasn't reached it yet
 - WAIT1: the stepper has reached POS1 and is now waiting for a specified delay before moving to the next state. This state uses the process shown in the [BlinkWithoutDelay][2] standard Arduino example sketch for delaying without blocking.
 - RUNTO2: the stepper is moving toward POS2, but hasn't reached it yet
 - WAIT2: the stepper has reached POS2 and is now waiting for the next state

You can also see the situations where a state is changed:

 - When **START** is pressed, set a new target position and enter the
    `RUNTO1` state

 - When **CROSS** is pressed, stop all stepper action and enter the `STOPPED` state

 - When in `RUNTO1` or `RUNTO2`, and the distanceToGo() is zero, enter to the corresponding `WAITn` state

 - When in the `WAITn` state and the specified time has elapsed, enter the corresponding next `RUNTOn` state.

Example:

    #define POS1 80
    #define POS2 0

    const uint16_t DELAY = 200;
    enum stepperstates {STOPPED, RUNTO1, WAIT1, RUNTO2, WAIT2};

    [...]

    void loop() {
      static uint16_t last_millis;
      static stepperstates xStepState;
      if (PS3.getButtonClick(START)){
        xStepState = RUNTO1;
        StepperControl.moveTo(POS1); // go to POS1
        Serial.print("\n Starting Movement between POS1 and POS2");
      }
      if (PS3.getButtonClick(CROSS)) {
        xStepState = STOPPED;
      }

      StepperControl.run();

      switch (xStepState) {
        case STOPPED:
          StepperControl.stop();
          break;
        case RUNTO1:
          if (StepperControl.distanceToGo()==0) {
            xStepState = WAIT1;
            last_millis = millis();
          }
          break;
        case WAIT1:
          if (millis() - last_millis >= DELAY) {
            xStepState = RUNTO2;
            StepperControl.moveTo(POS2);
          }
          break;
        case RUNTO2:
          if (StepperControl.distanceToGo()==0) {
            xStepState = WAIT2;
            last_millis = millis();
          }
          break;
        case WAIT2:
          if (millis() - last_millis >= DELAY) {
            xStepState = RUNTO1;
            StepperControl.moveTo(POS1);
          }
          break;
      }
    }

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
How do I select Sensor using chip 74HC138 on Wemos D1 Mini?

I have a project for my graduate degree.

It's about Monitoring Temperature and Humidity using Message Queuing Telemetry Transport on Serial NodeJS. To get sensor data to Wemos D1 Mini and NodeJS had done, also on my MQTT had done. My lecturer wants to get data from two sensors at the edges of the room, he suggests using a 74HC138. I'm using this [74HC138 Datasheet][1] and I'm using this [BME280 Library][2].

This is my schematic:

[![Schematic][3]][3]

This is my code:

    #include <BME280.h>

    const uint32_t SERIAL_SPEED = 115200;
    const uint8_t SCK_PIN = D5;
    const uint8_t MISO_PIN = D6;
    const uint8_t MOSI_PIN = D7;
    const uint8_t SPI_CS1_PIN = 15;
    const uint8_t SPI_CS2_PIN = 14;
    const uint8_t GPIO[3] = {D1, D2, D3};

    static int32_t temperature, humidity, pressure;
    int i;

    BME280_Class   BME280;

    void setup() {
      Serial.begin(SERIAL_SPEED);
      pinMode(SCK_PIN, OUTPUT);
      pinMode(MOSI_PIN, OUTPUT);
      pinMode(MISO_PIN, INPUT);

      SPI.begin();
      SPI.setBitOrder(LSBFIRST);

      Serial.println(F("condition before loop = "));
      //status_pin();
      for (i = 0; i < 3; i++) {
        pinMode(GPIO[i], INPUT);
        digitalWrite(GPIO[i], HIGH);
      }
      pinMode(SPI_CS1_PIN, OUTPUT);
      pinMode(SPI_CS2_PIN, OUTPUT);

      Serial.println(F("Starting Hardware SPIDemo example program for BME280"));
      Serial.print(F("- Initializing BME280 sensor\n"));

      if ( (!BME280.begin(SPI_CS1_PIN) && (!BME280.begin(SPI_CS2_PIN) ) {
        Serial.println(F("-  Unable to find BME280. Waiting 3 seconds."));
        delay(3000);
      }

      BME280.mode(SleepMode);
      Serial.print(F("- Sensor detected in operating mode \""));
      Serial.print(BME280.mode());
      Serial.println(F("\"."));
      if (BME280.mode() == 0) {
        Serial.print(F("- Turning sensor to normal mode, mode is now \""));
        Serial.print(BME280.mode(NormalMode));
        Serial.println("\"");
      }
      Serial.println(F("- Setting 16x oversampling for all sensors"));
      BME280.setOversampling(TemperatureSensor, Oversample16);
      BME280.setOversampling(HumiditySensor,   Oversample16);
      BME280.setOversampling(PressureSensor,   Oversample16);
      Serial.println(F("- Setting IIR filter to maximum value of 16 samples"));
      BME280.iirFilter(IIR16);
      Serial.println(F("- Setting time between measurements to 1 second"));
      BME280.inactiveTime(inactive1000ms);
      Serial.print(F("- Each measurement cycle will take "));
      Serial.print(BME280.measurementTime(MaximumMeasure) / 1000);
      Serial.println(F("ms.\n\n"));
    }

    void loop() {
      static uint8_t loopCounter = 0;
      byte pin1 = 0x74;
      byte pin2 = 0x71;

      if ( BME280.begin(SPI_CS1_PIN) == 1 ) {
        selpin(pin1);
        Serial.println(F(" Data Bme = "));
      } else if ( BME280.begin(SPI_CS2_PIN) == 1 ) {
        selpin(pin2);
        Serial.println(F(" Data Bme = "));
        printdata();
      }

      if (++loopCounter % 10 == 0) {
        Serial.print(F("\n- Turning "));
        if (BME280.getOversampling(HumiditySensor) == 0) {
          BME280.setOversampling(HumiditySensor, Oversample16);
          Serial.print(F("ON"));
        } else  {
          BME280.setOversampling(HumiditySensor, SensorOff);
          Serial.print(F("OFF"));
        }
        Serial.println(F(" humidity sensing"));
        Serial.print(F("- Each measurement cycle will now take "));
        Serial.print(BME280.measurementTime(MaximumMeasure) / 1000.0);
        Serial.println(F("ms.\n"));
      }

      Serial.println(F("condition after loop = "));
      //status_pin();
      Serial.println();

    }

    float altitude(const float seaLevel = 1013.25) {
      int32_t temp, hum, press;
      BME280.getSensorData(temp, hum, press);
      float Altitude = 44330.0 * (1.0 - pow(((float)press / 100.0) / seaLevel, 0.1903));
      return (Altitude);
    }

    void printdata () {
      BME280.getSensorData(temperature, humidity, pressure);
      Serial.print(F("Temperature : "));
      Serial.print(temperature / 100.0);
      Serial.println(F(" *C"));
      if (BME280.getOversampling(HumiditySensor) != 0) {
        Serial.print(F("Humidity : "));
        Serial.print(humidity / 100.0);
        Serial.println(F(" %"));
      }
      Serial.print(F("Pressure : "));
      Serial.print(pressure / 100.0);
      Serial.println(F(" hPa"));
      Serial.print(F("Altitude : "));
      Serial.print(altitude());
      Serial.println(F(" m"));
      Serial.println();
      delay(5000);
    }

Serial output always says `Unable to find BME280. Waiting 3 seconds.` I know it's because `CS` pin cannot detect. I think something is missing my code.

**SOLVED**

Thanks to my pal @Majenko, I'm out of the 74HC138 stock but i have 74HC139, i think that's same to me, i tried advice from @Majenko early morning after i make assembly of my board own for define Chip Select Wemos to my enable pin and get back my missing code whom not understand me.

**See below** for verbose log of uploading my sketch.

[![enter image description here][4]][4]

**See below** for serial monitor.

[![enter image description here][5]][5]

Thanks.

  [1]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT138.pdf
  [2]: https://github.com/SV-Zanshin/BME280
  [3]: https://i.stack.imgur.com/0BhNC.png
  [4]: https://i.stack.imgur.com/3LsdK.gif
  [5]: https://i.stack.imgur.com/9mgXL.gif

body:
Using a 74HC138 in this situation is both pointless and wasteful. You're using 3 pins (or 4 - see below) to drive a chip to select between 2 pins. That's wasting one more pin than you would by directly driving the CS pins.

The only time it would make sense would be if you were wanting to connect with 5 or more devices, in which case you would get a saving in the number of pins used.

Anyway - what you are missing from your code is absolutely everything to do with the 74HC138. First off, you're using a library which assumes the CS pins are directly connected to the MCU. Second, there is no code to set the A/B/C pins to the right state to select an output.

If you really *must* use the 74HC138 I would suggest:

* Use the same CS pin in your code for every BMS280 instance.
* Connect that CS pin to G2A on the 74HC138
* Use the following procedure to access a sensor:
  1. Select the correct output on the 74HC138 by setting the A/B/C pins to the binary representation of the output you want
  2. Perform the BME280 operations you want on the relevant instance

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

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

<!-- End schematic -->

The CS pin you passed to the BME280 instances will control the state of the currently selected output on the 74HC138, turning it into a demultiplexer controlled by the A/B/C pins.  Using multiple instances of the BME280 class associated with each selected output will allow proper tracking of any internal state and data associated with the device connected to that output.

Or, and this is just throwing ideas out there, don't use the 74HC138 and tell your "lecturer" that it's a stupid idea to use 3 pins (4 including the chip select pin) to control a pair of devices that need a total of 2 pins.


message:
How do I create a state machine for my purpose?

I am new to Arduino.

I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open the door fully. When the switch is deactivated, the motor reverses for the same duration as opening.

I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops when my switch is activated/deactivated whereas I want it to run once per switch activation. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:

    const int Switch = 2;
    const int hbridge1 = 13;
    const int hbridge2 = 12;
    const int threshold = 400;

    int buttonState = 0;

    void setup() {

      pinMode(hbridge1, OUTPUT);
      pinMode(hbridge2, OUTPUT);
      pinMode(Switch, INPUT_PULLUP);

      Serial.begin(9600);
    }

    void loop() {
      int buttonState = digitalRead(Switch);
      Serial.println(buttonState);

      if (buttonState == HIGH) {
        digitalWrite(hbridge1, HIGH);
        digitalWrite(hbridge2, LOW);
        delay(4000);
        digitalWrite(hbridge1, LOW);
        digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
      } else {
        digitalWrite(hbridge1, LOW);
        digitalWrite(hbridge2, HIGH);
        delay(4000);
        digitalWrite(hbridge1, LOW);
        digitalWrite(hbridge2, LOW); //Same issue  here
      }

    ;
      delay(1);
    }

body:
A schematic will help to create a solution. Are you using a resistor, like 10K, to pull the switch pin low? If the button is not pressed and the code keeps looping through like it is pressed, I recommend adding the resistor. You may need to add another component though. Like a micro-switch on the frame of the door that gets tripped while it is closed. Or a button to close the door. Without that every loop through the code will think the switch is held low and activate the motor. Which might burn out the motor or trip a fuse.

    if(buttonstate == high){
    //open door
    }
    else{
    if(microswitch == high){
    //H-bridge pins low, low
    {
    else{
    //close door
    {

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

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

<!-- End schematic -->


body:
Creating a few boolian variables could help with this.

    bool opening = 0
    bool closing = 0

    const int Switch = 2;
    const int hbridge1 = 13;
    const int hbridge2 = 12;
    const int threshold = 400;

    int buttonState = 0;

    void setup() {

      pinMode(hbridge1, OUTPUT);
      pinMode(hbridge2, OUTPUT);
      pinMode(Switch, INPUT_PULLUP);

      Serial.begin(9600);
    }

    void loop() {
      int buttonState = digitalRead(Switch);
      Serial.println(buttonState);

      if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
        opening == 1  //variable "opening" is set to on
        closing == 0  //variable "closing" is set to off
        digitalWrite(hbridge1, HIGH);
        digitalWrite(hbridge2, LOW);
        delay(4000);
        digitalWrite(hbridge1, LOW);
        digitalWrite(hbridge2, LOW);
      }
        else if (buttonState == Low && closing == 0){ //variable "closing" is tested
          opening == 0    //variable "opening" is set to off
          closing == 1    //variable "closing" is set to on
          digitalWrite(hbridge1, LOW);
          digitalWrite(hbridge2, HIGH);
          delay(4000);
          digitalWrite(hbridge1, LOW);
          digitalWrite(hbridge2, LOW); //Same issue  here
      }
      delay(1000) // delay is in milliseconds. So 1000 = 1 second
    }

These new variables are set when the code is ran the first time. Therefore, no looping.


message:
INPUT_PULLUP not work for D8 in my NodeMCU v3

I changed my arduino NodeMCU application pin mode to use INPUT_PULLUP mode instead of INPUT. D8 input pin is not working as expected, I is always in LOW even the button is pressed or not.

I have 3 input pins (D2, D7, D8), when I changed to internal pull up resistor, I removed each external resistors from input and changed the circuit accourding to this: https://www.arduino.cc/en/Tutorial/InputPullupSerial

D2 and D7 works well, but D8 is not. I checked with a volage between GND and pins:

 - when button on D2, D7 is not pressed: 2.95 - 3 V
 - when button on D8 is not pressed: 0.8 V
 - when button on D2, D7, D8 is pressed: 0V (as expected)

You can see my code in github:
[https://github.com/kisdaniel/HomeDashboardGarageDoorOpener][1]

  [1]: https://github.com/kisdaniel/HomeDashboardGarageDoorOpener/tree/4cb86ffa2fbca5346bb1bd11c512f242a2a73cfc

body:
Pin D8 is esp8266 pin 15. This pin is one of the [boot configuration pins][1] and for use on a dev board, it must be pulled down at boot. So the NodeMcu has a pull down circuit on this pin and internal pullup is weaker then this external pulldown.

  [1]: https://github.com/espressif/esptool/wiki/ESP8266-Boot-Mode-Selection#required-pins


message:
Serial communication between python and arduino

I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:

    #include <Servo.h>
    int data;
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards
    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin(9600); //initialize serial COM at 9600 baudrate
      pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
      digitalWrite (LED_BUILTIN, LOW);
      myservo.attach(9);
      Serial.println("Hi!, I am Arduino");
    }

    void loop() {
    while (Serial.available()){
     //to receive more than one character
     char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
     while (!Serial.available()); // Wait for characters
     Serial.readBytesUntil('n', buffer, 7);
     data = atoi(buffer);

    }
    myservo.write(data);
    }

And here is the python code:

    import serial
    import time  # Required to use delay functions

    arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
    object called arduinoSerialData
    time.sleep(2)  # wait for 2 secounds for the communication to get
    established

    print arduinoSerialData.readline()  # read the serial data and print it as
    line
    print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

    while 1:  # Do this forever

        var = raw_input()  # get input from user
        print "you entered", var  # print the intput for confirmation

        arduinoSerialData.write(var)

body:
If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().

    void loop() {
      if (Serial.available()){
        byte data = Serial.read();
        myservo.write(data);
      }
    }

If python sends the number as text, then you can read it with `parseInt()`.

    void loop() {
      if (Serial.available()){
        int data = Serial.parseInt();
        myservo.write(data);
      }
    }

The `parseInt` is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in `setup()` `Serial.setTimeout(10);`


message:
How to detect when intercom is ringing?

For my apartment, I need to check when intercom is ringing and call an API in that case. I was thinking about using an AC input / DC output relay, since the buzzer signal is an AC signal. Is there an equivalent pre-built component similar to [this][1]?

  [1]: https://www.aliexpress.com/item/1pcs-ESP8266-ESP-01S-Relay-module-relay-WIFI-intelligent-socket-Add-ESP-01S/32861788818.html

body:
As it sounds like you do not own the buzzer (it is part of the appartment), someone may not like you directly connecting to it.

If this is a classic buzzer with an electromagnet, consider using a [Hall Effect Sensor][1].  The magnetic field generated by the buzzer may be able to activate the Hall Effect Sensor and inform the Arduino the buzzer has been activated.  [This article][2] talks about Hall Effect sensors and an Arduino.

Image of Arduino and Hall Effect Sensor from linked to article:
[![Image of Arduino and Hall Effect Sensor from linked to article.][3]][3]

Further, this is a much safer way connect to a buzzer.  As a classic buzzer can generate very high voltages that can damage processors and other sensitive electronic devices when directly connected.

  [1]: https://en.wikipedia.org/wiki/Hall_effect_sensor
  [2]: https://maker.pro/arduino/tutorial/how-to-use-a-hall-effect-sensor-with-arduino
  [3]: https://i.stack.imgur.com/ko95Z.jpg