message:
[Solved]How to make my stepper motor run clockwise and counterclockwise?

I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

I am using AccelStepper Library

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

    #include <AccelStepper.h>
    //Define stepper motor connections
    #define dirPin 4
    #define stepPin 14
    //Create stepper object
    AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
    void setup()
    {
      stepper.setMaxSpeed(1200); //maximum steps per second
    }
    void loop()
    {
      stepper.setSpeed(1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
    }

I have tried to add delay and counterclockwise code but its not working.

    #include <AccelStepper.h>
    //Define stepper motor connections
    #define dirPin 4
    #define stepPin 14
    //Create stepper object
    AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
    void setup()
    {
      stepper.setMaxSpeed(1200); //maximum steps per second
    }
    void loop()
    {
      Serial.println("clockwise");
      stepper.setSpeed(1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
      delay(1000);
      Serial.println("counterclockwise");
      stepper.setSpeed(-1200); //steps per second
      stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
      delay(1000);
    }

body:
From the AccelStepper website: [link][1]

> Speeds of more than 1000 steps per second are unreliable

Try to change the speed to lower value, and let us know what is the outcome.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#ae79c49ad69d5ccc9da0ee691fa4ca235


sender: user

sender: assistant

body:
Hi here it the reference to the library functions that are available in [accelstepper library](https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html).

Go through the link, it will provide you the issues with your code and example for your application like @smajli said **steps more than 1000 is unreliabe**, here you can see `setSpeed(float)` function where setting negative or positive sign selects the direction and value set the speed of rotation.


message:
Change data-type String

I'm currently working with an ESP8266 NodeMCU V3 and an IR transmitter breakout board. The module receives NEC IR commands trough a HTTP request and then sends them trough the IR transmitter. Getting the command from the HTTP request and sending static (pre-programmed) IR NEC commands works perfectly. The problem however is that the NEC IR command I receive trough HTTP is in a `String` variable/data type (after processing). `irsend.sendNEC();` however requires `uint64_t` as the input type, according to the error message I get in the Arduino IDE.

I don't really know my way around C data types to be honest. Searches like "Arduino String to uint64_t" have came up empty or reversed. One [post][1] came close to what I'm trying to accomplish, but `irsend.sendNEC(strtoul(irrequest));` didn't do the trick either.

Arduino code;

 - Check for `// Send IR NEC command` almost at the bottom
 - The second and third `irsend.sendNEC();` are an example and not in the final code
 - HTTP request is formatted like http://192.168.1.xxx/rest/ir/nec/0xFB0042BD

`Sketch.ino`

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_PORT      = 80;
    const int   CONFIG_TIMEOUT   = 5000;
    const int   CONFIG_IRTPIN    = 2;

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    // Include libraries
    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <IRremoteESP8266.h>
    #include <IRsend.h>
    #include <IRrecv.h>
    #include <IRutils.h>

    // Create webserver object
    WiFiServer server(CONFIG_PORT);

    // Create IR Send object
    IRsend irsend(CONFIG_IRTPIN);

    // Setup instructions
    void setup() {

      // Start serial and LED
      Serial.begin(CONFIG_SERIAL);
      Serial.println();
      Serial.println("Starting setup");
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, 1);

      // Start WiFi connection
      Serial.print("Connecting to: ");
      Serial.println(CONFIG_SSID);
      WiFi.mode(WIFI_STA);
      WiFi.begin(CONFIG_SSID, CONFIG_PSK);

      // Wait for WiFi connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println();
      Serial.println("WiFi connected!");

      // Print WiFi connection information
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  Local IP: ");
      Serial.println(WiFi.localIP());

      // Start webserver
      Serial.println("Starting webserver...");
      server.begin();
      delay(1000);
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Host: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Port: ");
      Serial.println(CONFIG_PORT);

      // Start IR Send
      Serial.println("Starting IR Send...");
      irsend.begin();
      delay(1000);
      Serial.println("IR Send started!");

      // Setup complete
      Serial.println("Setup completed");
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();

    }

    // Loop instructions
    void loop() {

      // Wait for new client
      WiFiClient client = server.available();
      if (client) {

        // New client
        digitalWrite(LED_BUILTIN, 1);
        Serial.println("New client connected");

        // Wait nicely for the client to complete its full request
        unsigned long timeout = millis() + CONFIG_TIMEOUT;
        Serial.println("Waiting for client request to finish...");
        while (!client.available() && millis() < timeout) {
          delay(1);
        }

        // End client connection when timeout is reached to not hold up availability
        if (millis() < timeout) {
          Serial.println("Client request finished!");
        } else {
          Serial.println("Client request timeout!");
          client.flush();
          client.stop();
          digitalWrite(LED_BUILTIN, 0);
          Serial.println();
          return;
        }

        // Catch client request
        String req = client.readStringUntil('\r');
        Serial.print("Request header: ");
        Serial.println(req);
        if (req.indexOf(F("/rest/ir/nec/")) != -1) {

          // Get IR Send NEC request
          String irrequest = req;
          irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
          irrequest.remove((irrequest.indexOf(" ")));
          Serial.print("IR Send NEC code: ");
          Serial.println(irrequest);

          // Send IR NEC command
          Serial.println("Sending IR NEC command");
          irsend.sendNEC(irrequest);    // <<< here lays the problem
          irsend.sendNEC(0xFB0042BD);   // This works
          irsend.sendNEC("0xFB0042BD"); // This doesn't

          // Send HTTP response
          Serial.println("Sending HTTP/1.1 200 OK");
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");
          client.println();
          client.println("OK");

        } else {

          // Invalid request
          Serial.println("Invalid client request");
          Serial.println("Sending HTTP/1.1 404 response");
          client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

        }

        // Flush output buffer
        Serial.println("Flushing output buffer");
        client.flush();
        digitalWrite(LED_BUILTIN, 0);
        Serial.println();
        return;

      }

    }

  [1]: https://forum.arduino.cc/index.php?topic=123486.0

body:
`irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 10));` did the trick with the help of [Juraj][1]. Much thanks! I only had the set `10` to `16` to get it to work.

Working code:

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_PORT      = 80;
    const int   CONFIG_TIMEOUT   = 5000;
    const int   CONFIG_IRTPIN    = 2;

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    // Include libraries
    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <IRremoteESP8266.h>
    #include <IRsend.h>
    #include <IRrecv.h>
    #include <IRutils.h>

    // Create webserver object
    WiFiServer server(CONFIG_PORT);

    // Create IR Send object
    IRsend irsend(CONFIG_IRTPIN);

    // Setup instructions
    void setup() {

      // Start serial and LED
      Serial.begin(CONFIG_SERIAL);
      Serial.println();
      Serial.println("Starting setup");
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, 1);

      // Start WiFi connection
      Serial.print("Connecting to: ");
      Serial.println(CONFIG_SSID);
      WiFi.mode(WIFI_STA);
      WiFi.begin(CONFIG_SSID, CONFIG_PSK);

      // Wait for WiFi connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println();
      Serial.println("WiFi connected!");

      // Print WiFi connection information
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  Local IP: ");
      Serial.println(WiFi.localIP());

      // Start webserver
      Serial.println("Starting webserver...");
      server.begin();
      delay(1000);
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Host: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Port: ");
      Serial.println(CONFIG_PORT);

      // Start IR Send
      Serial.println("Starting IR Send...");
      irsend.begin();
      delay(1000);
      Serial.println("IR Send started!");

      // Setup complete
      Serial.println("Setup completed");
      digitalWrite(LED_BUILTIN, 0);
      Serial.println();

    }

    // Loop instructions
    void loop() {

      // Wait for new client
      WiFiClient client = server.available();
      if (client) {

        // New client
        digitalWrite(LED_BUILTIN, 1);
        Serial.println("New client connected");

        // Wait nicely for the client to complete its full request
        unsigned long timeout = millis() + CONFIG_TIMEOUT;
        Serial.println("Waiting for client request to finish...");
        while (!client.available() && millis() < timeout) {
          delay(1);
        }

        // End client connection when timeout is reached to not hold up availability
        if (millis() < timeout) {
          Serial.println("Client request finished!");
        } else {
          Serial.println("Client request timeout!");
          client.flush();
          client.stop();
          digitalWrite(LED_BUILTIN, 0);
          Serial.println();
          return;
        }

        // Catch client request
        String req = client.readStringUntil('\r');
        Serial.print("Request header: ");
        Serial.println(req);
        if (req.indexOf(F("/rest/ir/nec/")) != -1) {

          // Get IR Send NEC request
          String irrequest = req;
          irrequest.remove(0, ((irrequest.lastIndexOf("/rest/ir/nec/")) + 13));
          irrequest.remove((irrequest.indexOf(" ")));
          Serial.print("IR Send NEC code: ");
          Serial.println(irrequest);

          // Send IR NEC command
          Serial.println("Sending IR NEC command");
          irsend.sendNEC(strtoul(irrequest.c_str(), NULL, 16));

          // Send HTTP response
          Serial.println("Sending HTTP/1.1 200 OK");
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println("Connection: close");
          client.println();
          client.println("OK");

        } else {

          // Invalid request
          Serial.println("Invalid client request");
          Serial.println("Sending HTTP/1.1 404 response");
          client.println("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nNot found");

        }

        // Flush output buffer
        Serial.println("Flushing output buffer");
        client.flush();
        digitalWrite(LED_BUILTIN, 0);
        Serial.println();
        return;

      }

    }

  [1]: https://arduino.stackexchange.com/users/37622/juraj


message:
Should L, TX, RX led light on while connected with laptop

Dear Sir,
               I need to know that should led light named as L, TX, RX should be on when we connect it with laptop?
Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question.
                 Hoping for a favourable answer.
Your's faithful,
Nir Patel.

body:
On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).

If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.

If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and *it* will control the LEDs.

If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.


message:
Problem with reading data from HMC5883L in GY-86

I am trying to read the data from GY-86 with my arduino UNO.
While reading MPU6050 and MS5611, it works quite well. But somehow I can't read anything from HMC5883L. Here is the code I used:
```
#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;

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

  // Initialize HMC5883L
  Serial.println("Initialize HMC5883L");
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

  // Set measurement range
  // +/- 0.88 Ga: HMC5883L_RANGE_0_88GA
  // +/- 1.30 Ga: HMC5883L_RANGE_1_3GA (default)
  // +/- 1.90 Ga: HMC5883L_RANGE_1_9GA
  // +/- 2.50 Ga: HMC5883L_RANGE_2_5GA
  // +/- 4.00 Ga: HMC5883L_RANGE_4GA
  // +/- 4.70 Ga: HMC5883L_RANGE_4_7GA
  // +/- 5.60 Ga: HMC5883L_RANGE_5_6GA
  // +/- 8.10 Ga: HMC5883L_RANGE_8_1GA
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  // Idle mode:              HMC5883L_IDLE
  // Single-Measurement:     HMC5883L_SINGLE
  // Continuous-Measurement: HMC5883L_CONTINOUS (default)
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  //  0.75Hz: HMC5883L_DATARATE_0_75HZ
  //  1.50Hz: HMC5883L_DATARATE_1_5HZ
  //  3.00Hz: HMC5883L_DATARATE_3HZ
  //  7.50Hz: HMC5883L_DATARATE_7_50HZ
  // 15.00Hz: HMC5883L_DATARATE_15HZ (default)
  // 30.00Hz: HMC5883L_DATARATE_30HZ
  // 75.00Hz: HMC5883L_DATARATE_75HZ
  compass.setDataRate(HMC5883L_DATARATE_15HZ);

  // Set number of samples averaged
  // 1 sample:  HMC5883L_SAMPLES_1 (default)
  // 2 samples: HMC5883L_SAMPLES_2
  // 4 samples: HMC5883L_SAMPLES_4
  // 8 samples: HMC5883L_SAMPLES_8
  compass.setSamples(HMC5883L_SAMPLES_1);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.print("Selected range: ");

  switch (compass.getRange())
  {
    case HMC5883L_RANGE_0_88GA: Serial.println("0.88 Ga"); break;
    case HMC5883L_RANGE_1_3GA:  Serial.println("1.3 Ga"); break;
    case HMC5883L_RANGE_1_9GA:  Serial.println("1.9 Ga"); break;
    case HMC5883L_RANGE_2_5GA:  Serial.println("2.5 Ga"); break;
    case HMC5883L_RANGE_4GA:    Serial.println("4 Ga"); break;
    case HMC5883L_RANGE_4_7GA:  Serial.println("4.7 Ga"); break;
    case HMC5883L_RANGE_5_6GA:  Serial.println("5.6 Ga"); break;
    case HMC5883L_RANGE_8_1GA:  Serial.println("8.1 Ga"); break;
    default: Serial.println("Bad range!");
  }

  Serial.print("Selected Measurement Mode: ");
  switch (compass.getMeasurementMode())
  {
    case HMC5883L_IDLE: Serial.println("Idle mode"); break;
    case HMC5883L_SINGLE:  Serial.println("Single-Measurement"); break;
    case HMC5883L_CONTINOUS:  Serial.println("Continuous-Measurement"); break;
    default: Serial.println("Bad mode!");
  }

  Serial.print("Selected Data Rate: ");
  switch (compass.getDataRate())
  {
    case HMC5883L_DATARATE_0_75_HZ: Serial.println("0.75 Hz"); break;
    case HMC5883L_DATARATE_1_5HZ:  Serial.println("1.5 Hz"); break;
    case HMC5883L_DATARATE_3HZ:  Serial.println("3 Hz"); break;
    case HMC5883L_DATARATE_7_5HZ: Serial.println("7.5 Hz"); break;
    case HMC5883L_DATARATE_15HZ:  Serial.println("15 Hz"); break;
    case HMC5883L_DATARATE_30HZ: Serial.println("30 Hz"); break;
    case HMC5883L_DATARATE_75HZ:  Serial.println("75 Hz"); break;
    default: Serial.println("Bad data rate!");
  }

  Serial.print("Selected number of samples: ");
  switch (compass.getSamples())
  {
    case HMC5883L_SAMPLES_1: Serial.println("1"); break;
    case HMC5883L_SAMPLES_2: Serial.println("2"); break;
    case HMC5883L_SAMPLES_4: Serial.println("4"); break;
    case HMC5883L_SAMPLES_8: Serial.println("8"); break;
    default: Serial.println("Bad number of samples!");
  }

}

void loop()
{
  Vector raw = compass.readRaw();
  Vector norm = compass.readNormalize();

  Serial.print(" Xraw = ");
  Serial.print(raw.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(raw.YAxis);
  Serial.print(" Zraw = ");
  Serial.print(raw.ZAxis);
  Serial.print(" Xnorm = ");
  Serial.print(norm.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(norm.YAxis);
  Serial.print(" ZNorm = ");
  Serial.print(norm.ZAxis);
  Serial.println();

  delay(100);
}
```
I download it from https://github.com/jarzebski/Arduino-HMC5883L.

The program always stuck at
```
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }
```
Here is the begin function in HMC5883L.cpp
```
bool HMC5883L::begin()
{
    Wire.begin();

    if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
    || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
    || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
    {
 return false;
    }

    setRange(HMC5883L_RANGE_1_3GA);
    setMeasurementMode(HMC5883L_CONTINOUS);
    setDataRate(HMC5883L_DATARATE_15HZ);
    setSamples(HMC5883L_SAMPLES_1);

    mgPerDigit = 0.92f;

    return true;
}
```
So, it seems that the begin function always returns False. What should i do to solve this problem?

This is how I connect GY-86 to UNO:

VCC-IN  -> 5V

GND     -> GND

SDA     -> 4A

SLC     -> 5A

body:
Did you run a i2c scanner? Is it found with i2c address 0x1E?

Looking at the schematic, the magnetometer HMC5883L is connected to XDA and XCL. That is not the normal I2C bus, but a second I2C bus from the MPU-6050.

The reason for that is that the 'dmp' firmware in the MPU-6050 can read the magnetometer and do calculations with it, in the MPU-6050.

If you want to communicate with the magnetormeter via the normal I2C bus, then you have to turn on the bypass-mode.

The libraries from Jeff Rowberg and Jarzębski are large. I suggest to enable the bypass-mode and run a i2c scanner.

Do you have a logic analyzer?
Perhaps you can use a simple multimeter. Keep the SDA low (shortcut it to GND) and try to measure if XDA is low as well in the bypass mode.

There is a chance that something is broken.


body:
Thank to Jot, your answer actually helps me.
Now I am using this code and it is working very well.

```
#include <Wire.h>
#include <HMC5883L.h>
#include <MPU6050.h>

HMC5883L compass;
MPU6050 mpu;

int previousDegree;

void setup()
{
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
  Serial.begin(38400);

  // Initialize MPU6050
  mpu.initialize();

  // Enable bypass mode
  mpu.setI2CMasterModeEnabled(false);
  mpu.setI2CBypassEnabled(true);
  mpu.setSleepEnabled(false);

  // Initialize HMC5883L
  while (!compass.begin())
  {
    delay(500);
  }

  // Set measurement range
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  compass.setDataRate(HMC5883L_DATARATE_30HZ);

  // Set number of samples averaged
  compass.setSamples(HMC5883L_SAMPLES_8);

  // Set calibration offset. See HMC5883L_calibration.ino
  compass.setOffset(0, 0);
}

void loop()
{
  long x = micros();
  Vector norm = compass.readNormalize();

  // Calculate heading
  float heading = atan2(norm.YAxis, norm.XAxis);

  // Set declination angle on your location and fix heading
  // You can find your declination on: http://magnetic-declination.com/
  // (+) Positive or (-) for negative
  // For Bytom / Poland declination angle is 4'26E (positive)
  // Formula: (deg + (min / 60.0)) / (180 / M_PI);
  float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI);
  heading += declinationAngle;

  // Correct for heading < 0deg and heading > 360deg
  if (heading < 0)
  {
    heading += 2 * PI;
  }

  if (heading > 2 * PI)
  {
    heading -= 2 * PI;
  }

  // Convert to degrees
  float headingDegrees = heading * 180/M_PI;

  // Fix HMC5883L issue with angles
  float fixedHeadingDegrees;

  if (headingDegrees >= 1 && headingDegrees < 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 0, 239, 0, 179);
  } else
  if (headingDegrees >= 240)
  {
    fixedHeadingDegrees = map(headingDegrees, 240, 360, 180, 360);
  }

  // Smooth angles rotation for +/- 3deg
  int smoothHeadingDegrees = round(fixedHeadingDegrees);

  if (smoothHeadingDegrees < (previousDegree + 3) && smoothHeadingDegrees > (previousDegree - 3))
  {
    smoothHeadingDegrees = previousDegree;
  }

  previousDegree = smoothHeadingDegrees;

  // Output
  Serial.print(norm.XAxis);
  Serial.print(":");
  Serial.print(norm.YAxis);
  Serial.print(":");
  Serial.print(norm.ZAxis);
  Serial.print(":");
  Serial.print(headingDegrees);
  Serial.print(":");
  Serial.print(fixedHeadingDegrees);
  Serial.print(":");
  Serial.print(smoothHeadingDegrees);
  Serial.println();

  // One loop: ~5ms @ 115200 serial.
  // We need delay ~28ms for allow data rate 30Hz (~33ms)
  delay(30);
}
```

By the way, the code on https://github.com/jarzebski/Arduino-HMC5883L should add
```
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
```
in the begin of setup.


message:
Serial input values only working for very short seconds

I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?

    int light=9;

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

    void loop() {
      Serial.println("How long do you want the light on for (in seconds)?");
      while(Serial.available()==0){}
      int on_time = (Serial.parseInt() * 1000);
      digitalWrite(light, HIGH);
      delay(on_time);
      digitalWrite(light, LOW);
      Serial.print("The light was just on for ");
      Serial.print(on_time/1000);
      Serial.print(" seconds. ");
    }

body:
If you add `Serial.println(on_time);` right after `int on_time = (Serial.parseInt() * 1000);` you will see the problem. Once you enter the number 33 for example, the `integer` value printed is **-32536**. The Allowed data type for `delay()` is `unsigned long`, so the negative number is causing a problem.

Using `Serial.println()` judiciously can be very helpful when you are trying to debug a sketch.


message:
NTP rollover-safe design with ESP8266 (Curiosity)

The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).

If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.

The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):
<!-- language-all: lang-cpp -->

    unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
    unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

body:
This implementation is perfectly fine. The calculations are done with
unsigned numbers, so they are naturally rollover safe. The day NTP time
rolls over, `secsSince1900` will become a very small number, and
subtracting `SEVENZYYEARS` from it will cause an extra roll over. Owing
to the rules of modular arithmetics, these two rollovers compensate and
you are guaranteed to get the correct result modulo
232 s.

In the end, you get a Unix time as an unsigned 32-bit integer. Unix time
is traditionally signed, which makes the 32-bit representation roll over
in January 2038. The authors of this library have instead chosen to
represent it as an _unsigned_ number, which means it will roll over in
February 2106.


message:
Bit Number to Byte Value conversion (AVR Docs)

I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_use_bv.html

I has a macro called `_BV` that

>  convert a bit number (usually within a byte register) into a byte value

And the example tells this

>_BV(3) => 1 << 3 => 0x08

I am kinda used to bits and bytes etc. But I don't understand what the **3** in this example is? It says it converts a bit number but **3** is not binary it is an integer. And the macro resolves it to **0x08** which is the value of 8 in decimal.

I am very confused. I hope someone can explain to me what is happening here!

body:
The bits within a byte are numbered 0 through 7 from right to left. The
rightmost (least significant) is bit 0, next is bit 1... and the
leftmost (most significant) is bit 7.

The expression `_BV(3)` builds a byte where bit 3 is set (is 1) and all
other bits are clear (are 0). In binary it looks like this:

    position:   7  6  5  4  3  2  1  0
    bit value:  0  0  0  0  1  0  0  0

The macro expands to `1<<3`, which takes the integer 1 (0b00000001 in
binary) and shifts all its bits by three positions to the left. The
result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8
in decimal.


message:
Arduino SD Card open file modes append / overwrite

Running Arduine IDE `SD DataLogger Example`, my data gets appended to a txt file.

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
    }

Is there an explicit option to open the file in overwrite / append modes?

body:
If you look in [this library][1], you see:

    File SDClass::open(const char *filepath, uint8_t mode) {

        ...

        if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) {

So you can use all these mode combinations (e.g. O_CREATE, O_APPEND, O_WRITE).

  [1]: https://github.com/arduino-libraries/SD/blob/master/src/SD.cpp


body:
The Arduino SD library is an Arduino wrapper of old version of SdFat library (put into utility subfolder of the SD library). This SdFat library [has constants][1] like O_READ, O_WRITE, O_APPEND.

Arduino wrapper has constants

    #define FILE_READ O_READ
    #define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

You can use the SdFa library constants in the wrapper calls.

    File dataFile = SD.open("datalog.txt", O_READ | O_WRITE | O_CREAT);

**Warning**: not all versions of SD library bundled in different board packages have O_APPEND in `#define FILE_WRITE`. Even in the Arduino SD library the O_APPEND was removed some time ago and then the change was reverted, because all dataloger examples used FILE_WRITE.

  [1]: https://github.com/arduino-libraries/SD/blob/b8a78d4b3bf970c776522b79f95c7cc4691ced3c/src/utility/SdFat.h#L52


body:
You only need to open the file with `FILE_WRITE` and use `file.seek(EOF)` to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.

```
File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");
```


message:
LED dimmer not fading out

I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?

    int blue_led=10;

    void setup() {
      pinMode(blue_led,OUTPUT);
    }

    void loop() {

      int voltage=0;

      for(int i=0;i<=255;i+1){

        analogWrite(blue_led,voltage);
        voltage=voltage+1;
        delay(8);
      }
       int volts=255;

       for(int i=0;i<=255;i+1){

        analogWrite(blue_led,volts);
        volts=volts-1;
        delay(8);
       }

    }

body: your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)


message:
Arduino IDE upload error

I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

> Sketch uses 7514 bytes (23%) of program storage space. Maximum is
> 32256 bytes. Global variables use 415 bytes (20%) of dynamic memory,
> leaving 1633 bytes for local variables. Maximum is 2048 bytes.
>
> avrdude: verification error, first mismatch at byte 0x0002
>
>    0x5d != 0x62 avrdude: verification error; content mismatch
>
> avrdude: verification error; content mismatch

I'm using **Arduino UNO R3**

This is the code I'm trying to run

        #include <IRremote.h>
    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop()
    {
      if (irrecv.decode(&results))
        {
         Serial.println(results.value, HEX);
         irrecv.resume(); // Receive the next value
        }
    }

Also, every other code(not using the IRremote library) uploads just fine without any errors.

body:
There can be power/connection problem or somehow the bootloader has been damaged.
So

 - Check power
 - Check Connection
<br>

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.


message:
GPS Module don't provide full data

I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.

### My pin configuration:
GPS ------- ESP32

VCC ------- 3v3

GND ------- GND

TX -------- RX2 (pin 16)

RX -------- TX2 (pin 17)

### Baud Rate: 9600

My code:
```c++
#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}
```
### OUTPUT
[![my output][1]][1]

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

body:
GPS seems to be working and informing you that you have no signal.  Usually happens inside buildings, when far from a window or when antenna isnt properly connected.

Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky.  Wait for a couple of minutes until you get a fix on 4 or 5 satellites.


message:
Check if Arduino Uno connected with PC

I'm using Arduino Uno controller

How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.

I've tried `Serial.available()`, but I'm not sure, if I can do it this way:

    if (Serial.available())
    {
       val = true;
    }
    else
    {
       val = false;
    }

I want use this condition to avoid `setup()` commands by some unexpected reason in case if controller powered only with adapter

body:
You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

 1. If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.

 2. If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC

 3. If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)


message:
Running Python on Arduino

I've been using **Python** for quite long, and I was wondering if it can be used as a programming language for **Arduino**, rather than **C/C++**.

When I'm using the Arduino IDE, the sketch is compiled into a **hex** file that contains the program **binary**.

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

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

Knowing that micro controllers execute only binary, I would like to know if there is a tool to **convert** Python code into binary, so that I can **upload** it directly to Arduino using AVR or other programmers.

  [1]: https://i.stack.imgur.com/8RDCw.png
  [2]: https://i.stack.imgur.com/C5QiE.png

I read about **Micro Python**, a lightweight adaptation of Python that can fit in boards, but can only work with **PyBoard**, which I have never used yet.

I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in **IOT**.

body:
To my knowledge, there is not a "python to ATMega architecture" compiler out there.

However, it's not true that MicroPython only runs on PyBoard. There are versions for installation also on the ESP8266 and ESP32 chips, and so the popular NodeMCU and Wemos D1 development boards, or any of the other similar products with those processors, can easily run Python code. Many of these are available at a very low cost from the usual retailers/sources.

Be aware that MicroPython is somewhat limited compared to the full version due to the limited RAM available on these boards.


message:
ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)

What is the minimum `debug level` (`TOOLS` tab) which will display the stack trace on crash?

I would like to reduce information clutter in the serial monitor.

I understand that `debug port` must point to my serial monitor.

In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

body:
The crash report is printed to 'standard output' by `__wrap_system_restart_local` in `core_esp8266_postmortem.c` in esp8266 Arduino core.

The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by `Serial.setDebugOutput(true);`.

At compile time the initial debug output is controled by `-DDEBUG_ESP_PORT=`, for example `-DDEBUG_ESP_PORT=Serial1`. The Tools menu "Debug port" sets the `DEBUG_ESP_PORT` define. The crash report is not controlled by "Debug level" setting.


message:
Servo motor (HSR-1425R) not running continuously

I'm trying to programme a servo motor to reach certain positions. I have a 360 degrees servo motor, so I can not use the Servo library and I can only control the speed. Therefore I want to regulate the time for the pulse. The setup is simple, 5 V, GND and pin 9 from the Arduino to the motor.

    int servo1 = 9;

    void setup{
        Serial.begin(9600);
        pinMode(servo1, OUTPUT);
    }
    void loop{
        digitalWrite(servo1, HIGH);
        delay(5000);
        Serial.println(digitalRead(servo1));
        digitalWrite(servo1, LOW);
        delay(5000);
        Serial.println(digitalRead(servo1));
    }
Expected:
I expect the code to run the servo motor at full speed for 5 seconds.

Actual:
The motor runs at the first impulse and pauses for 10 seconds.

How can I improve the code to do what I expect?

body:
Look at how servo motors are typically controlled. As far as I know there are no servos that can just be "enabled to rotate" like you seem to expect.
Usually a servo's position is set by applying a pulse of a specific length. This means you can apply a PWM signal with proper frequency. Then the duty cycle should be proportional to the servos position. From my experience timing is quite critical when controlling a servo, so going the way you do (timing a gpio's output state with `delay()`s) will not work well. You have to use the atmega's hardware modules (which already is the case when using the arduinos digital write) to achieve adequate timing.


body: Apply some impulse which you need your servo to work on


message:
C++ trim char array

I have a char array of length 10.  It gets filled with an unpredictable number of chars, usually up to 6.

    char charDummy[10] = "";

When i concatenate the char array with another, I get spaces, which are unwanted in later parsing.

    char postStr[300] = "";
    strcat(postStr, "&field1=");
    strcat(postStr,dtostrf(rain05m,6,2,charDummy));

How do I trim a char array directly?

Workaround: loop thru the array and copy valid characters to a new char array with perfect number of rows.  Due to memory constraints, I need to be parcimonious with the amount of variables created.

body:
Your problem is that `dtostrf()` right-aligns the value in the space allotted to it.  The simple answer is to tell it to left-align instead:

> Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. **width is signed value, negative for left adjustment.**
>
> [AVR LIBC Manual](https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html)

So, just make your width negative and it will left align.


message:
Best way of storing extra data for Arduino project

I am an arduino beginner and I am trying to make a speed camera alert system, it would start beeping if I am above the speed limit and getting close to the speed camera. There is this website where I can get all the data I need, coordinates, direction and speed limit of every 36000 speed cams in my country.

I would need some extra memory space to be able to store all this data, would an eeprom chip do the job? and would it be able to keep up with a for loop going through all those 36000 speed cam locations to check if i am close to it and above the speed limit?

Edit: since going through all those locations on a loop would be a lot for the processor to handle, someone recommended the creation of a temp file that would narrow that list down by direction, and when that direction changed it would recalculate that temp file. This is what I came up with:

```c++
void setup() {
  int tempDirection = gpsDirection;
  writeTempFile();
}

void loop() {
  //this will recalculate the temp file when the gpsDirection changes
  if(gpsDirection > tempDirection +5 || gpsDirection < tempDirection -5){
    tempDirection = gpsDirection;
    writeTempFile();
  }

  for(temp file){
    if(distance <= 100 && speed > speedlimit){
      //start beeping
    }
  }
}

void writeTempFile(){
  //this will write a temp file with every cam with a direction that's similar the gps direction
  for(each line of the file){
    if(gpsDirection + 10 > camDirection || gpsDirection - 10 < camDirection ){
      add cam to temp file;
    }
  }
}

```

body:
EEPROM writes are limited to about 100k cycles.  They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).

You should not store your speed camera base here.

Get a MicroSD adapter and save your data there.  Looping thru 36000 speed trap locations is going to put a toll on your processor and memory.  I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box.  recheck every time your position changes a full degree (N/S or E/W).

Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).


message:
Accelstepper - how to switch from fullstep to halfstep in loop?

I am using `Accelstepper` library to control a unipolar stepper motor. In my project, I would like to run the stepper in full-step mode when I need speed and in half-step mode when I need precision. As you know, the full-step/half-step selection is done in the very beginning of the sketch...

I found a workaround by creating two instances of `Accelstepper` for the same stepper. That is:

    Accelstepper fast(FULL4WIRE, 2,3,4,5);

    Accelstepper slow(HALF4WIRE, 2,3,4,5);

With this, when I call (skipping other details of the code) `fast.run()` the motor moves fast (full-step) and when I call `slow.run()` it moves slowly as it is in half step mode.

But;

When it comes to determine to current motor position, this workaround fails, since there are two different values returned by the two functions: `fast.currentPosition()` and `slow.currentPosition()`. So this workaroud becomes useless.

My first question is: is there a way in `Accelstepper` to switch from full-step to half-step and vice versa in the execution(let say in the loop)? If so, the second question can be skipped.

The second: `XX.currentPosition()` function returns the value of a variable, namely "_currentPos" which is calculated in `Accelstepper.cpp` file. As I understand, there become, as many `_currentPos` values as `Accelstepper` instances. In my case, one for fast and another for slow, and somehow they are kept and calculated individually without any confusion. Is there a way to access (extern?) and set this variable from the sketch, by referencing the specific `Accelstepper` instence? Briefly, is there a way to copy one motor position to another?

Many thanks.

body:
[The documentation][1] notes a `setCurrentPosition()` function.

>     void AccelStepper::setCurrentPosition ( long position )
> Resets the current position of the motor, so that wherever the motor happens
> to be right now is considered to be the new 0 position. Useful for
> setting a zero position on a stepper after an initial hardware
> positioning move. Has the side effect of setting the current motor
> speed to 0.
>
> Parameters
>
> **position** The position in steps of wherever the motor happens to be right now.

----------

Use the `currentPosition()` function to get the current position from either mode. You will have to decide whether you want "fast" steps or "slow" steps to be the actual count, and when you switch from one context to the other, grab the current position of the last used mode, and set a new position in the mode you will use next, possibly multiplying or dividing by 2 as needed.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a9d917f014317fb9d3b5dc14e66f6c689


message:
Segmentation fault and huge SRAM need for Serial.println

I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).

AssertUtils.h:

    #pragma once

    #define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

    class AssertUtils
    {
    public:
     static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
    };

AssertUtils.cpp:

    #include "AssertUtils.h"
    #include "Arduino.h"

    /* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
    {
     if (!expression)
     {
      Serial.println(funcName);
      Serial.println(fileName);
      Serial.println(line, DEC);
      Serial.flush();

      // Abort program execution.
      abort();
     }
    }

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).

When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).

  //Serial.println(funcName);

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).

  //Serial.println(funcName);
     //Serial.println(fileName);

Questions:

1. How can I get rid of the segmentation fault?
2. How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char* buffering (?)

body:
Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.

What I did was:

- (Juraj) Changed the compiler version to 6.21
- (juraj) Added an F in `F(__FILE__)`
- (KIIV) Removed __func__; this did not work with the `F` flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
- (Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.

The resulting code is below:

    #define assert(expression) \
      if (!(expression)) \
      { \
        Serial.println(F(__FILE__)); \
        Serial.println(__LINE__, DEC); \
        Serial.flush(); \
       abort(); \
      }


message:
Can I power Arduino with 12V 1.2A adapter

I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?.
Thanks in advance.
As i said i want to run it long time.

body:
If it is an Arduino Uno Rev3 SMD, the [documentation](https://store.arduino.cc/arduino-uno-smd-rev3) (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

> Operating Voltage     5V
>
> Input Voltage (recommended)   7-12V
>
> Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.

Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.


body:
Yes, you can power an Arduino with 12V into the barrel connector. It will then use it's internal voltage regulator to drop that to the 5V it needs internally. However, that is on the high side of it's recommended range, and will make the Arduino's voltage regulator run hot. A 7.5V supply would be better, and you could probably get more total current out of the 5V regulator without overheating if you fed it 6V or 7.5V instead of 12V. (6V is the lower limit. >= 7V is better.)

(A linear voltage regulator like the one in most Arduino boards essentially uses a transistor as a variable resistor to lower the voltage from the input voltage to 5V, which converts the excess voltage to heat. The higher the input voltage, and the more current you draw from the regulator, the more heat it generates.)


message:
Float division returns "inf" and 0

I'm new to Arduino and I'm doing an ultrasonic project where I test for the speed of sound. My code is below and for some reason, this is what the serial port returns:

This is the measured speed of sound: inf m/s
This is the measured speed of sound: 0m/s
This is the measured speed of sound: 0m/s
etc...

Here's my code. Any help's massively appreciated:)

    int trig = 13;
    int echo = 11;
    float target_distance = 0.3;
    float recieved;
    float speed_of_sound;

    void setup() {
        Serial.begin(9600);
        pinMode(trig, OUTPUT);
        pinMode(echo, INPUT);
    }

    void loop() {
        digitalWrite(trig, LOW);
        delayMicroseconds(2000);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(trig, LOW);

        recieved=pulseIn(echo, HIGH);
        recieved = recieved*1000000.0;
        speed_of_sound = (2*target_distance)/recieved;
        Serial.print("This is the measured speed of sound: ");
        Serial.print (speed_of_sound);

        Serial.println("m/s");
        delay(3000);
    }

body:
Assuming the speed of sound is of the order of 330 m/s, you expect
the round-trip to the target and back to last about 1.8 ms. Then

    recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and

    recieved = recieved * 1000000.0;

should make `received` something like 1.8 × 109.
Then

    speed_of_sound = (2*target_distance)/recieved;

gives a speed of sound of 3.3 × 10−10. It is the
correct value if you want that speed in meters per picosecond, but this
is inconsistent with your program printing “m/s” after the value.

The Arduino's `Serial.print()` is quite dumb with floating point
numbers. It defaults to printing two digits after the decimal point,
irrespective of the order of magnitude of the number. Thus, anything
smaller than 0.005 gets printed as “0”.

I don't quite understand why you got ∞ on the first loop. Looks like
`pulseIn()` missed the pulse and returned zero, in which case the speed
is computed as 0.6 ÷ 0 = ∞.

The solution is to compute `received` as

    recieved = pulseIn(echo, HIGH) * 1e-6;

This can be remembered by thinking that a quantity (round-trip time) is
a numeric value (`pulseIn(echo, HIGH)`) multiplied by a unit (`1e-6`,
which stands for “microseconds”).


message:
ESP8266 official library post request returns 400

Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h

    if (http.begin(client, host)) {  // HTTP

      http.addHeader("Content-Type", "application/json");
      // Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      // int httpCode = http.GET();
      String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
      Serial.print("[HTTP] POST...\n");
      int httpCode = http.POST(request);

body:
400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.

In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable `host`. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol [and used the secure port 443][1]. But the underlying networking Client object was not SSL so it didn't encrypt the request.

  [1]: https://github.com/esp8266/Arduino/blob/8859b818d8557ebada8d60e76891ac7e23f5aa96/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp#L177


message:
Whats the maximum external voltage/current i can apply through an Arduino Uno ? + a couple mini questions

i'm just starting out with electronics and Arduino's and was wondering about the extent of an Arduino's ability. Will i eventually be able to program and power very high voltage/current requiring devices such as a full sized fan motor? Also at what point would i not be able to use normal wires, components and breadboards due to a high current/voltage (not sure which one would break them).

I know these are total noob questions but thanks in advance!

body:
**Arduino Uno**

First, never use too high voltages on GPIO pins of an Arduino. if you want to know, search for 'absolute maximum current' or 'absolute maximum voltage'. Probably any pin of an Arduino is about 5 V (plus some headroom).

**External power**

So since your fan will use more voltage high likely, you are not lost, in contrary, you should use a separate power source (giving the voltage you need for the fan), and use either a relay, or a transistor or MosFet. Than you can program it with a 5 volts pin and control a much higher voltage device (your fan).

**Wires**

Do not send high voltages/currents through breadboards and jumper wires neither. Use separate wiring, and you can check tables using AWG (thickness of wires) to see how much current they can support. Note that I say current, not voltage. The voltage will drop depending on the length of the wire and the size, so calculate that you have enough voltage at the end of the wire.

**Safety**

Also for safety, do not forget a fuse, and remember that the external power source and all wires have the same voltage as the fan, which may kill you if you touch them.


body:
arduinos, and microcontrollers in general, handle only very small ammounts of current, and they work at what is called 'logic level' voltage, usually much lower than 'line' voltage or 'mains,' which is your wall outlet. in general an arduino will put out 30-50 mAh per pin, and max of about 200mAh combined. again, the total ouput for the entire board is a max of about 0.2 amps. the idea is that the pins are pulled high or low (+5 or ground) depending on the logic of the programming. these signals trigger logic level components to act, usually mosfets/transistors and relays turn higher loads on/off

basically, you dont want to power even a single led without a current limiting resistor. its just a micro*controller* after all


message:
OTA push sketch to NodeMCU

Similar questions regarding Arduinos mention the existence of tools that would enable the pushing of sketch updates to NodeMCU via WiFi / OTA (Over The Air).

Does this proceed?  If so, please indicate the proper tools.

body:
Arduino IDE supports upload to a network port. Network ports are detected with mDns and made available in Tools>Port menu.

The ArduinoOTA library bundled with the esp8266 Arduino boards package supports upload from IDE with 'network port' over WiFi. See the example of the ArduinoOTA library available in Examples menu in IDE.


body: Yes, there exist methods to update codes through OTA in Wifi-modules/NodeMCU. You will first need to allot an IP address to your device which will later be used as a port to carry out OTA transmission. Look out to this tutorial-https://circuitdigest.com/microcontroller-projects/esp8266-ota-update-programming-using-arduino-ide


message:
How to write code to make the LED’s ﬂash in the following sequence?

How to write code like this sequence? What is the meaning of 4 decimal?
For this, we had to add a delay in the code

    led_Pin_1 1 0 0 0
    led_Pin_2 0 1 0 0
    led_Pin_3 0 0 1 0
    led_Pin_4 0 0 0 1

my code, It is working. But I need to convert this code to above sequence?

    int led_Pin_1 = 11;
    int led_Pin_2 = 10;
    int led_Pin_3 = 9;
    int led_Pin_4 = 8;

    void setup() {
      pinMode(led_Pin_1, OUTPUT);
      pinMode(led_Pin_2, OUTPUT);
      pinMode(led_Pin_3, OUTPUT);
      pinMode(led_Pin_4, OUTPUT);
    }

    void loop() {
      digitalWrite(led_Pin_1, HIGH);
      delay(200);
      digitalWrite(led_Pin_2, HIGH);
      delay(200);
       digitalWrite(led_Pin_3, HIGH);
      delay(200);
       digitalWrite(led_Pin_4, HIGH);
      delay(200);
      digitalWrite(led_Pin_1, LOW);
      delay(300);
       digitalWrite(led_Pin_2, LOW);
      delay(300);
       digitalWrite(led_Pin_3, LOW);
      delay(300);
       digitalWrite(led_Pin_4, LOW);
      delay(300);
    }

body:
    int led_Pin_1 = 11;
    int led_Pin_2 = 10;
    int led_Pin_3 = 9;
    int led_Pin_4 = 8;

    int led_on = 0; // Start with first (led_Pin_1)

    void setup() {
      pinMode(led_Pin_1, OUTPUT);
      pinMode(led_Pin_2, OUTPUT);
      pinMode(led_Pin_3, OUTPUT);
      pinMode(led_Pin_4, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
      digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
      digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
      digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
      delay(250);

      led_on = (led_on + 1) % 4;
    }

led_on will start with 0 (pin 1), switching only that pin on. Some explanation:

    (led_on == 0) ? HIGH : LOW

This means: if (led_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led_on is 0, and in the next loop, only pin 2 oing on, because led_on is 1 etc.

    led_on = (led_on + 1) % 4;

This increases the value of led_on, but when it reaches 4, it reverts back to 0.

I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.

You can make the 4 almost identical digitalWrite lines into a function as small improvement.

If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.


message:
Help understanding how avrdude works with ArduinoISP and why its not working for me

I am trying to use avrdude with a Mega2560 running ArduinoISP

Note: I have the 10uF cap on the Mega2560 RESET line as described by Ardunio.

Also, I am using avrdude/6.3 on Windows 10.  The Mega2560(ArduinoISP) is connected to the PC using an a USB cable - connection is COM8.

I have a couple of tasks I want to do

 1. Update the firmware on my USBASP
 2. Load Arduino boot on ATTINY85 dev board.

I started with Arduino IDE but moved to avrdude to better understand the problem

For #1:
Wired it per https://www.arduino.cc/en/Tutorial/ArduinoISP

    AVR-ISP pin  MEGA-ISP pin
    6/10 (name)

    1/9 (MISO)  50
    2/2 (VCC)  VCC
    3/7 (SCK)  52
    4/1 (MOSI)  51
    5/5 (RESET)  53
    6/10 (GND)  GND

I tried using the command:

    avrdude -c arduino -p m8 -P COM8

I get the error

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xed
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

    avrdude done.  Thank you.

--UPDATE-- The error above was caused by not setting the BAUD rate. Now I get:

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.

What I really want to know is more of how this process works so I can better understand it and be able to debug the issues.

 1. Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?
 2. What does "stk500" mean?  Is that the programming protocol, the ISP protocol, or something all together different?
 3. Is this all documented somewhere?

body:
The target board was not reset.

The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.
[![enter image description here][1]][1]

>Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

>What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

>Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc

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


message:
Please help me combine the two codes for DHT11 and SW-420 Vibration sensor for arduino in one program

The following is the code used for DHT11 Temperature and Humidity sensor:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(4, 5, 0, 1, 2, 3);
    byte degree_symbol[8] =
                  {
                    0b00111,
                    0b00101,
                    0b00111,
                    0b00000,
                    0b00000,
                    0b00000,
                    0b00000,
                    0b00000
                  };
    int gate=11;
    volatile unsigned long duration=0;
    unsigned char i[5];
    unsigned int j[40];
    unsigned char value=0;
    unsigned answer=0;
    int z=0;
    int b=1;
    void setup()
    {

    lcd.begin(16, 2);
     lcd.print("Temp = ");
     lcd.setCursor(0,1);
     lcd.print("Humidity = ");
     lcd.createChar(1, degree_symbol);
     lcd.setCursor(9,0);
     lcd.write(1);
     lcd.print("C");
     lcd.setCursor(13,1);
     lcd.print("%");
    }

    void loop()
    {

     delay(1000);
     while(1)
     {
      delay(1000);
      pinMode(gate,OUTPUT);
      digitalWrite(gate,LOW);
      delay(20);
      digitalWrite(gate,HIGH);
      pinMode(gate,INPUT_PULLUP);//by default it will become high due to internal pull up
     // delayMicroseconds(40);

      duration=pulseIn(gate, LOW);
      if(duration <= 84 && duration >= 72)
      {
          while(1)
          {
            duration=pulseIn(gate, HIGH);

            if(duration <= 26 && duration >= 20){
            value=0;}

            else if(duration <= 74 && duration >= 65){
            value=1;}

            else if(z==40){
            break;}

            i[z/8]|=value<<(7- (z%8));
            j[z]=value;
            z++;
          }
        }
    answer=i[0]+i[1]+i[2]+i[3];

    if(answer==i[4] && answer!=0)
    {
    lcd.setCursor(7,0);
    lcd.print(i[2]);
    lcd.setCursor(11,1);
    lcd.print(i[0]);
    }

    z=0;
    i[0]=i[1]=i[2]=i[3]=i[4]=0;
     }
    }

The following is the code for SW-420 Sensor:

    int LED_Pin = 13;
    int vibr_Pin =3;

    void setup(){
      pinMode(LED_Pin, OUTPUT);
      pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurment
      Serial.begin(9600); //init serial 9600
     // Serial.println("----------------------Vibration demo------------------------");
    }
    void loop(){
      long measurement =TP_init();
      delay(50);
     // Serial.print("measurment = ");
      Serial.println(measurement);
      if (measurement > 1000){
        digitalWrite(LED_Pin, HIGH);
      }
      else{
        digitalWrite(LED_Pin, LOW);
      }
    }

    long TP_init(){
      delay(10);
      long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
      return measurement;
    }

Assuming the DHT11 Pin configuration remains unchanged and you can change the pin configurations for SW-420 vibration sensor, please give me a combined code for the two sensors to display results in one program. Thanks a lot.

body:
There are multiple threads on how to combine two different sketches. One of the main things you have to do is refactor your code to get rid of calls to `delay()`. Do a Google search on `Arduino blink without delay` and read one of the tutorials you find. The idea is to make a call to the `millis()` function for each thing you want to do on a time intervl, save the current millis count, and then wait until the new value of millis() is greater than the saved value by your desired time interval. By doing that, your code does a very fast series of checks:

"is it time to do `<thing 1>` again?"

"Is it time to to `<thing 2>` again?"

"What about `<thing 3>`"

And repeats.

Then it doesn't freeze the rest of your sketch waiting for time to pass. (That is what `delay()` does. Everything stops until the delay time has passed, which is bad.)


message:
NodeMCU Modbus interfacing with Pressure Multi-Switch

I've been trying to interface between a **NodeMCU** and a **Dotech DPX200** Pressure Multi-Switch over **Modbus** RS485 using a MAX485 Module for the past few weeks, going through nearly every Modbus post on this site  with no luck.
As my access to the multi-switch can be limited at times, I've also tried using several simulators like ModScan64, Simply Modbus Master/Slave, Modbus Poll etc. but could get none to work.

I'd like to know if the Modbus device's Slave ID has to be set on the device itself or the NodeMCU? Also to get the "Display of low pressure value" the address given in the manual is 40023. How would I write the NodeMCU code to read that value using either the ModbusRtu, ModbusMaster or any other appropriate library?

----------

I've added the [DPX200's Manual][2] link with my NodeMCU script and wiring diagram, and would appreciate any help from you.

 [![Wiring Diagram][1]][1]
<!-- language-all: lang-cpp -->

    #include <ModbusMaster.h>
    #define MAX485_TX_ENABLE  12

    int myInts[6];
    ModbusMaster node;

    void preTransmission(){
      digitalWrite(MAX485_TX_ENABLE, 1);
    }

    void postTransmission(){
      digitalWrite(MAX485_TX_ENABLE, 0);
    }

    void setup(){
      Serial.begin(9600);
      Serial1.begin(9600, SERIAL_8N1);
      pinMode(MAX485_TX_ENABLE, OUTPUT);
      digitalWrite(MAX485_TX_ENABLE, 0);
    }

    void loop(){
      uint16_t k = 0,Status;
      node.begin(1, Serial1); //Slave ID = 1?
      node.preTransmission(preTransmission);
      node.postTransmission(postTransmission);
      Serial.println(i);
      Status = node.readHoldingRegisters(0x0023, 5); //Since address is 40023 to 40027
      if ( (Status == node.ku8MBSuccess) ){
         Serial.print("\nIDK: ");
         //Serial.println(node.getResponseBuffer(0));
         for (k = 0; k <= 5; k++ ){
            Status = node.readHoldingRegisters(k, 1);
            Serial.println(node.getResponseBuffer(0));
            delay(0);
         }
      }
    }

  [1]: https://i.stack.imgur.com/k76tD.png
  [2]: http://dotech21.com/winko/include/etc_down_hit.php?code=e_data&v=&category=&page=1&number=122&keyfield=&key=&file=DPX200_MANUAL_EN_R20140806.pdf

body:
Now you have `node.begin(1, Serial1)`, but you can't use Serial1 for RS485 because Serial1 doesn't have RX pin

According to the picture you wired the adapter to RX/TX pin of Serial, but this pins are wired on board to USB for communication with the computer (upload and Serial Monitor). You can't use Serial for RS485 adapter while you are using it for debug prints.

You can use SoftwareSerial fo example on D1/D2 for RS485.

Or if you have an USB-to-TTL-Serial adapter then you can use Serial1 for debug prints and Serial for RS485


message:
LED blinking issue

i made a distance measuring circuit with different led for different distance ranges

    #define trigPin 13
    #define echoPin 12
    #define BPin 7
    #define piezoPin 9
    #define RPin 4
    #define GPin 8

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(BPin, OUTPUT);
      pinMode(piezoPin, OUTPUT);
      pinMode(RPin, OUTPUT);
      pinMode(GPin, OUTPUT);
    }

    void loop() {
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;

      if (distance >= 200 || distance <= 0) {
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
      delay(1000);
      {
        if (distance <= 25 || distance <= 0) {
          digitalWrite(RPin, HIGH);
        }
        else {
          digitalWrite(RPin, LOW);
        }
      }

      {
        if (distance >= 25 && distance <= 50) {
          digitalWrite(GPin, HIGH);
        }
        else {
          digitalWrite(GPin, LOW);
        }

        {
          if (distance >= 50 && distance <= 75) {
            digitalWrite(GPin, HIGH);
          }
          else {
            digitalWrite(BPin, LOW);
          }

          {
            if (distance >= 75 && distance <= 100) {
              digitalWrite(BPin, HIGH);
            }
            else {
              digitalWrite(GPin, LOW);
              {
                {
                  if (distance >= 100 && distance <= 200) {
                    digitalWrite(piezoPin, HIGH);
                  }
                  else {
                    digitalWrite(piezoPin, LOW);
                  }
                }
              }
            }
          }
        }
      }
    }

everything is working fine except Gpin it is blinking please  help me
i am also uploading link to download my .ino file
link; https://www.datafilehost.com/d/e19b35d5

body:
This is your code without unnecessary brackets:

    #define trigPin 13
    #define echoPin 12
    #define BPin 7
    #define piezoPin 9
    #define RPin 4
    #define GPin 8

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(BPin, OUTPUT);
      pinMode(piezoPin, OUTPUT);
      pinMode(RPin, OUTPUT);
      pinMode(GPin, OUTPUT);
    }

    void loop() {
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;

      if (distance >= 200 || distance <= 0) {
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
      delay(1000);

      if (distance <= 25 || distance <= 0) {
        digitalWrite(RPin, HIGH);
      }
      else {
        digitalWrite(RPin, LOW);
      }

      if (distance >= 25 && distance <= 50) {
        digitalWrite(GPin, HIGH);
      }
      else {
        digitalWrite(GPin, LOW);
      }

      if (distance >= 50 && distance <= 75) {
        digitalWrite(GPin, HIGH);
      }
      else {
        digitalWrite(BPin, LOW);
      }

      if (distance >= 75 && distance <= 100) {
        digitalWrite(BPin, HIGH);
      }
      else {
        digitalWrite(GPin, LOW);
        if (distance >= 100 && distance <= 200) {
          digitalWrite(piezoPin, HIGH);
        }
        else {
          digitalWrite(piezoPin, LOW);
        }
      }
    }

Using the ternary operator you can write some if statements easier:

    #define trigPin 13
    #define echoPin 12
    #define BPin 7
    #define piezoPin 9
    #define RPin 4
    #define GPin 8

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(BPin, OUTPUT);
      pinMode(piezoPin, OUTPUT);
      pinMode(RPin, OUTPUT);
      pinMode(GPin, OUTPUT);
    }

    void loop() {
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;

      if (distance >= 200 || distance <= 0) {
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
      delay(1000);

      digitalWrite(RPin, (distance <= 25 || distance <= 0) ? HIGH : LOW);
      digitalWrite(GPin, (distance >= 25 && distance <= 50) ? HIGH : LOW);

      if (distance >= 50 && distance <= 75) {
        digitalWrite(GPin, HIGH);
      }
      else {
        digitalWrite(BPin, LOW);
      }

      if (distance >= 75 && distance <= 100) {
        digitalWrite(BPin, HIGH);
      }
      else {
        digitalWrite(GPin, LOW);
        digitalWrite(piezoPin, (distance >= 100 && distance <= 200) ? HIGH : LOW);
      }
    }

Some remarks to think about that helps you solve your sketch (and is the reason why your GPin may blink):

1. The line part `(distance <= 25 || distance <= 0)` can be rewritten to `(distance <= 25)` since if a value is less/equal than 0, it automatically is less/equal than 25.

2. You set based one a condition a pin to HIGH or another pin to LOW, I would expect both pins to change, or the same pin. But I don't know your requirements.

3. The 'edge' values (e.g. 25, 50, 75) fall in multiple conditions, you probably want to exclude the end edge. It is a sort of guideline to include the start and exclude the end, e.g. `if (distance >= 50) && (distance < 75)`.

In your case you probably are best of checking the distance like this:

    if (distance < 0)
    {
       ...
    }
    else if (distance < 25)
    {
       // 0 <= distance < 25)
       ...
    }
    else if (distance < 50)
    {
       // 25 <= distance < 50)
    }
    ...

or do it the other way around:

    digitalWrite(GPin, 'condition in which GPin should be on' ? HIGH : LOW);
    digitalWrite(BPin, 'condition in which BPin should be on' ? HIGH : LOW);

e.g. when you want the GPin to be on when between 0 and 25:

    digitalWrite(GPin, ((distance >=0) && (distance < 25) ? HIGH : LOW);


message:
Getting maximum value from HX711 and use it in the code further

i am using HX711 module to get value from load cell.my projects is a tensile strength testing machine,which will increase the load gradually and break at its maximum capacity.therefore i need the maximum value at which the specimen breaks.and use that value in the code to calcuate the tensile strengh of the specimen using the formula(tensile strength=load/cross section area of specimen).
Please help me with this and if possible ,i will be very gratefull if anyone can help me with the code too.
Thank you

body:
We won't write the code for you, since we are not a free coding service, but I will try to give you some hints, how you can do it.

1. **Timing of measurements:** The measurements themselves can be done with one of the HX711 libraries, that are available on the web, but you may want to time them to get more regular measurements. This can be done in a non-blocking coding style like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It involves the `millis()` function to measure the time since the last measurement and act accordingly. This is explained many times troughout the web and on this site.

2. **Saving the data and finding the maximum:** This depends on what else you want to do with the data.
    - **Saving all data for later processing**: You might want to save all data (the load curve) for later use. In this case you have to define an array of appropriate length (the length depends on the duration and frequency of the measurement). Also define a position variable or pointer, that marks the current position in this array. Everytime when you do a measurement, you save the result to the array element at the saved position and increment the position variable after that. After the end of the measurement, you declare a value variable with the value of the first array element. Then you loop through all the following elements (`for(int i=1;i<array_length;i++)`). Inside the loop you calculate and save the maximum of 2 numbers: The value of the current array element and the saved variable. This can be done with `saved_value = max(saved_value, array[i]);`. When the loop is finished, you will have the maximum value in the `saved_value` variable.

    - **No saving of data:** You can also calculate a flying maximum without saving all data. Declare a variable (`max_value`), that will hold the maximum value, and set it to zero. Then, everytime when you do a measurement, you execute `max_value = max(current_value, max_value);` which calculates the maximum of the two numbers (current measurement and the previously calculated maximum). At the end of the measurement you will have the absolute maximum in the `max_value` variable.

3. **Sensing the end of measurement:** You need to sense the end of the measurement (when the specimen breaks) (though this can be done manually if you like). For this I would suggest to calculate the speed in which the load changes. During the measurement the load will increase slowly. In the moment of breaking the load will decrease very fast. The speed between two load measurments is calculated by `(value(x) - value(x-1))/measurement_interval`. You can define a threshold of negative speed, so that every speed below it (faster negative decrease of load) will be sensed as breaking of specimen. You can check this on every measurement with a simple `if` statement, or you can calculate the speed over more than 2 consecutive measurements. That depends on the actual speed of load change and the frequency of load measurements.

4. **Calculating the tensile strength:** This is just writing your formula into the code using the variable names, that you used in the previous code. Be sure to use the correct variable type for your needs. Most likely you would want to use `float`.

5. **Getting input from user:** This depends largely on your planned means of interaction with the user. Is the Arduino connected to a PC and you use a serial terminal program? Then you can use this for user input (You might want to look at the `SerialEvent` example of the Arduino IDE, which shows how to work with messages and delimiter characters). Do you want to add a keypad and a LCD display? There are library available for these too, so it should not be very difficult to learn how to use then to get user input.


message:
Writing Data through Pin at certain frequency

I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:

    loop{
    digitalWrite(1);
    digitalWrite(0);
    }

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.

I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.

Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?

body:
If I understand correctly, you want to output a synchronous serial bit
stream at 1 MHz. Something like this:

            ___     ___     ___
    clk  __/   \___/   \___/   \___⋅⋅⋅
         ______ _______ _______ ___
    dat  __D0__X___D1__X___D2__X___⋅⋅⋅

where the data bits come from the PC.

If you want this to be a continuous bit stream, it will not be easy to
generate on an Arduino Uno.

## Receiving the data

Since the data comes from the PC, it comes presumably through the serial
link. You have to account for the fact that this link adds a start bit
and a stop bit to every byte. Thus, you have 10 bits on the wire
for every 8 bits of actual data. Since you have to sustain
1 Mb/s average of actual data, this means that you must configure
the serial port for at least 1.25 Mb/s. However, the only baud rate
higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.

Does your PC support this baud rate? Is the communication reliable at
this speed?

If the speed is too high, I would suggest you try to have the PC send
the data as PCM at a lower speed, and have the Arduino handle the
PCM → PDM conversion.

## Transmitting the data

This data format is very similar to an SPI transmission. Then, the SPI
hardware port seems like the easiest way to generate it. However, the
SPI transmitter on the Uno is _not_ double-buffered. This means that you
have to wait for the current byte transmission to be finished before
providing the next byte to the SPI hardware. This in turn means that you
will inevitably have small delays between consecutive bytes, and one out
of every 8 clock cycles will be stretched beyond the expected
1 µs. If this unsteadiness is acceptable for your application, then
do use the SPI transmitter. If not, you will have to find another
solution.

The serial port on the Uno has a special mode of operation where it
behaves like a master SPI port. Unlike the actual SPI port, this port is
double-buffered, which makes it possible to send a continuous bit stream
with a steady clock. The problem is, you cannot use this mode for
transmission and at the same time use the serial port receiver in its
regular asynchronous mode. Thus you will not be able to receive the data
from the PC when using this mode. If you can manage to route the
PC → Arduino communication through SPI, this mode of operation
of the serial port may be a good choice.

If none of the options above works for you I suggest, as last resort, to
generate the bitstream entirely by software. The timings are tight, as
each level of the clock has to be held for only 8 CPU cycles. But
it is likely doable in hand-written assembly, provided that interrupts
are disabled. Here is roughly how I may try to do that:

<!-- language: lang-lisp -->

        in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

    loop:
        lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

        ; output bit 0
        andi output, ~_BV(1)                ; clear clock bit
        bst data, 0                         ; save data[0]
        bld output, 0                       ; load it into output[0]
        ; no delay needed here
        out _SFR_IO_ADDR(PORT_OUT), output  ; output
        ori output, _BV(1)                  ; set the clock bit
        delay 6                             ; assumed to be a macro
        out _SFR_IO_ADDR(PORT_OUT), output  ; output

        ; output bit 1
        andi output, ~_BV(1)                ; clear clock bit
        bst data, 1                         ; save data[1]
        bld output, 0                       ; load it into output[0]
        delay 4
        out _SFR_IO_ADDR(PORT_OUT), output  ; output
        ori output, _BV(1)                  ; set the clock bit
        delay 6
        out _SFR_IO_ADDR(PORT_OUT), output  ; output

        ; etc...

        rjmp loop

The code above assumes the UART is synchronized with the output stream,
which will likely not be the case in reality. Your real application may
then be more complex, and you will have to make that extra complexity
fit within the delay slots above.

Note that if you handle the PCM → PDM conversion on the
Arduino the resulting code may end up being simpler, as you will be able
to read the UART at every loop iteration without worrying about
synchronization. I have written a program that does something very
similar a while ago, and I just pushed it to GitHub for you to take a
look: [avr-dac: Turn an AVR into a 1-bit D/A converter][avr-dac]. Note
that this program is meant to be usable on AVRs without a hardware UART.
It expects the PCM data to be fed in the fashion of a shift register.
Using the UART would make the program simpler.

[avr-dac]: https://github.com/edgar-bonet/avr-dac


message:
Python Arduino Serial Communication Speed

Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.

I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.

Here my arduino code,

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

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
    int x,temp;

    int sudutT0(long int p)
    {
      int u = 3600+((405*p)/180);
      return u;
    }

    void setup() {
      Serial.begin(250000);
      Serial.println("Joint 2 Test!");
      pwm.begin();
      pwm.setPWMFreq(50);

      Wire.setClock(1000);
      for (uint8_t pin=0; pin<16; pin++)
      {
      pwm.setPWM(pin, sudutT0(90),4095);
      }
      pwm.setPWM(3, sudutT0(150), 4095);
    }

    void loop() {
        if(Serial.available() == 8){
          if(Serial.read() == 0xF5)
          {
            //Joint 1
          temp = Serial.read();
          x = sudutT0(temp);
          pwm.setPWM(0,x,4095);
          // Joint 2 Servo
          temp = Serial.read();
          x = sudutT0(temp);
          pwm.setPWM(1,x,4095);
          x = sudutT0(180-temp); //810 - theta
          pwm.setPWM(2,x,4095);
          //Joint 3 - 6, Gripper
          for(uint8_t u = 3; u<8; u++)
          {
            temp = Serial.read();
            x = sudutT0(temp);
            pwm.setPWM(u,x,4095);
          }
          //delay(100);
          }
        }
    }

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?

body: All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data. I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms


message:
Is there an Arduino motor shield library?

I have an old motor shield but can see the revision 3 is still being sold: https://store.arduino.cc/arduino-motor-shield-rev3

When I follow the link for "Getting Started section" [the page][1] lists a lot of shields but not the motor shield.  I must be missing something really obviously but I can't find a library for the motor board.

I'm trying to drive 2 DC motors.

  [1]: https://www.arduino.cc/en/Guide/HomePage

body:
From [Chrisl's comment][1]: https://github.com/gallingern/arduino-motor-shield-r3

You don't really need a library though as the code is simple enough:

    void setup() {

      //Setup Channel A
      pinMode(12, OUTPUT); //Initiates Motor Channel A pin
      pinMode(9, OUTPUT); //Initiates Brake Channel A pin

    }

    void loop(){

      //forward @ full speed
      digitalWrite(12, HIGH); //Establishes forward direction of Channel A
      digitalWrite(9, LOW);   //Disengage the Brake for Channel A
      analogWrite(3, 255);   //Spins the motor on Channel A at full speed

      delay(3000);

      digitalWrite(9, HIGH); //Engage the Brake for Channel A
    }

[From here][2].

  [1]: https://arduino.stackexchange.com/questions/65977/is-there-an-arduino-motor-shield-library/65979#comment140786_65977
  [2]: https://www.instructables.com/id/Arduino-Motor-Shield-Tutorial/


message:
Trouble with i2c on ESP8266

I have used with partial success I2C with the ESP8266.  When it works, it works well, with many devices on the bus.  I've examined the signals on a 'scope to assure Vlo, Vhi, Tr, and Tf.

However, often it works not at all.  No I2C devices (even if there is only one connected) are detected.  This condition is determined by some unknown factor, and it stays in this condition for some time (days?) before it starts working again.  Power cycle, reset-by-button, and reset-by-reflashing do not restore operation until it works again.

This has occurred with at least three ESP8266 modules from two different manufacturers with different pinouts.  It affects all connected I2C devices.  They are all slaves to the ESP8266.

What should I try next?

body: The signals had looked good, but I did not examine them closely enough.  When I removed extra pullup resistors I had added on SCL and SDA, I2C worked.