body:
Here is my code. My issue is is that the keys are getting "pressed" even though there is nothing jumping any of the pins on the Arduino.

    // UNO-HIDKeyboard-Library - Version: Latest
    // This program has been created by pcs3rd.
    // Please do not change this line.
    #include <HIDKeyboard.h>
    HIDKeyboard keyboard;   // Initiate keyboard
    // Pin deffanitions and variables...
    int key0 = 2;   // Button 0 (Unused but optional)
    int key1 = 3;   // Button 1
    int key2 = 4;   // Button 2
    int key3 = 5;   // Button 3
    int key4 = 6;   // Button 4
    int key5 = 7;   // Button 5
    int key6 = 8;   // Button 6
    int key7 = 9;   // Button 7
    int key8 = 10;  // Button 8
    int led0 = 13;  // Indicator light.
    int state0 = 0; // Button 0
    int state1 = 0; // Button 1
    int state2 = 0; // Button 2
    int state3 = 0; // Button 3
    int state4 = 0; // Button 4
    int state5 = 0; // Button 5
    int state6 = 0; // Button 6
    int state7 = 0; // Button 7
    int state8 = 0; // Button 8

    void setup() {
       keyboard.begin();    // Start keyboard emulation
       Serial.begin(9600);  // Start Serial Output
       delay(300);          // Wait to be recognized be PC.
       pinMode(key1, INPUT_PULLUP); // set pin mode
       pinMode(key2, INPUT_PULLUP); // set pin mode
       pinMode(key3, INPUT_PULLUP); // set pin mode
       pinMode(key4, INPUT_PULLUP); // set pin mode
       pinMode(key5, INPUT_PULLUP); // set pin mode
       pinMode(key6, INPUT_PULLUP); // set pin mode
       pinMode(key7, INPUT_PULLUP); // set pin mode
       pinMode(key8, INPUT_PULLUP); // set pin mode
       pinMode(led0, OUTPUT);       // set pin mode
       Serial.println("Startup Completed!");
    }

    void loop() {
       // write state info to vars
       state0 = digitalRead(key0); // Button 0
       state1 = digitalRead(key1); // Button 1
       state2 = digitalRead(key2); // Button 2
       state3 = digitalRead(key3); // Button 3
       state4 = digitalRead(key4); // Button 4
       state5 = digitalRead(key5); // Button 5
       state6 = digitalRead(key6); // Button 6
       state7 = digitalRead(key7); // Button 7
       state8 = digitalRead(key8); // Button 8
       if (state0 == HIGH) {       // Button 0
         digitalWrite(led0, HIGH);
         // keyboard.pressSpecialKey(0x68); (You can enter a scancode instead of 0x68,)
         Serial.println("state0");
         delay(30);
       }
       if (state1 == HIGH) { // Button 1
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x68);
         Serial.println("state1");
         delay(30);
       }
       if (state2 == HIGH) { // Button 2
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x69);
         Serial.println("state2");
         delay(30);
       }
       if (state3 == HIGH) { // Button 3
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x6A);
         Serial.println("state3");
         delay(30);
       }
       if (state4 == HIGH) { // Button 4
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x6B);
         Serial.println("state4");
         delay(30);
       }
       if (state5 == HIGH) { // Button 5
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x6C);
         Serial.println("state5");
         delay(30);
       }
       if (state6 == HIGH) { // Button 6
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x6D);
         Serial.println("state6");
         delay(30);
       }
       if (state7 == HIGH) { // Button 7
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x6E);
         Serial.println("state7");
         delay(30);
       }
       if (state8 == HIGH) { // Button 8
         digitalWrite(led0, HIGH);
         keyboard.pressSpecialKey(0x0F);
         Serial.println("state8");
         delay(30);
       }
       digitalWrite(led0, LOW);
       Serial.println("scan");
       delay(30);
    }

Yet, even though I have 'if' statements, the code still gets executed, as shown in my monitor:

Startup Completed!

    state0
    hstate1
    istate2
    jstate3
    kstate4
    lstate5
    mstate6
    nstate7
    state8
    scan
    state0
    hstate1
    istate2
    jstate3
    kstate4
    lstate5
    mstate6
    nstate7
    state8
    scan

Are there any hints to what could be going on? I reformatted the code for readability, but it is pretty much the same as before. Also, I am not using pin 0 or one. I am using 13 for onboard LED.

title: Why are my if statements acting like the condition is always true?

Answers: 1

body:
Microcontroller pins tend to read LOW when left floating (but not always!). However, pin 1 is used to communicate with the USB-UART converter, and I believe it is set HIGH in the idle state. So assuming you are not pressing any buttons, keys 2-8 will be in the LOW state by default, but key 1 will be HIGH. Hence when `defaultCase = HIGH;`, the first `if` is triggered. When `defaultCase = LOW;` all `if`'s but the first one fire up. Solution — don't use digital pin 1 (edit: avoid pin 0 and maybe 13 as well).

Edit: The answer above refers to the original code without the pull-up resistors enabled.


body:
I want to be able to track the curvature of a human arm as it straightens out and retracts (ex: like live tracking a bicep curl). I don't want to use resistive flex sensors.

I've been trying to find suppliers for this technology demoed here: https://www.youtube.com/watch?v=iAeXp-TpFLU&t=38s

But I cant seem to find anyone who sells directly to consumers. I was thinking about creating a hobbyist level version my own using fiber optic wire, a led, and a light wavelength sensor, using a more powerful Arduino such as the Intel Edison. I have a basic understanding of how this technology works, but I want to learn by attempting to create it.

Is this practical or possible with an Arduino?

if so:

 - Are these the correct materials I would need?

if not:

 - Why not?
 - What kind of equipment would I need to achieve this?
 - Is there anywhere to buy this sensor directly?
 - Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

title: Reproducing a Fiber Optic Shape Sensor with Arduino?

Answers: 2

body:
I think nobody here can really give you an answer, if this is possible with an Arduino, since we don't know enough about the technology and the nitty gritty things, that make this a difficult task. So making a hobbyist version won't be easy and maybe really expensive.

In the fiber each bragg grating reflects a bit of the light back. The wave length of this reflected light is dependend on the angle between light and grating. So you get a specific wave length back from each grating, that corresponds to the bending at that particular part of the cable. The task is to measure the many wave lengths, that are being reflected in the fiber, and match them to a particular part of the cable. Since they don't say, how they are solving this, I will mention some ideas here:

 1. **Spectral Measurement (Wave length):**
   - From the video I guess, that they use white light to shine into the cable. The gratings will only reflect the wave lengths from this spectrum, that satisfy Bragg's law due to bending angle. You have to measure the wave length directly with a spectrometer. Mostly this is another grating, that will seperate the wave lengths spatially, so that you can measure the spectral structure by using a spatial sensor, for example a camera or a line sensor. You would have to correct for different wave length sensitivities of the camera.
   - Maybe they are only using a laser with 1 wave length. Then the bending would result in a change in intensity reflected from that grating. If you can seperate the signals from the different gratings good enough, you would be able to measure just the change in intensity, which would be easier, since you basically need just a photo transistor or similar for that wave length. (In this case you would need to calibrate the sensor each time as a straight cable and ensure, that the measurement is fast enough for the expected movement).
 2. **Matching of signals to each part of the cable:** Here I guess, that they use a time-of-flight sensor, because I cannot think of anything else without further information. This is a really difficult problem, because most available sensors are not sensible enough for measuring quarter inches without being cheap in the first place. You will likely spend a lot of money for a sensor like this. And you building an own time-of-flight sensor with the wanted sensitivity may be as difficult as building the whole device in the first place.
 3. **Needed Parts:** Also you will need the fiber itself, which is - as stated - not a normal glas fiber, which you can by everywhere. It is most likely a custom build and you will pay a lot of money, to get one of these. The light source is dependend on the spectral measurement above. For a white light it is important, that all wavelength should have as equal intensity as possible. You would also have to account for the spectral absorption and the overall absorption in the fiber, which restricts the sensitivity and possible lengths.

> Is there anywhere to buy this sensor directly?

Most likely not. In the videos it seems like a device, that was developed by the NASA for a specific application. The video is a proposal for other companies to learn from the NASAs development, so the device is not consumer ready. But you might be able to get a paper about this device by searching the internet for it or by asking the NASA directly. This paper would contain way more information about the device as the videos.

All in all this would be an extremely difficult task. Since you came here (a simple Q&A site) with this difficult question, I think, that you are not really ready for this big of a task. Most likely even the developers at the NASA needed long and much money for this.

---

> Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I would propose to build a string of bending strips, which change their resistance according to the bending angle. You can use multiple strips for getting multiple readings for different parts of the human arm. With each strip you build a voltage divider and do an analog measurement. With a bit of calibration you should be able to measure the curls.

body:
Well. is not impossible and the accepted answer is quite dark.

To use a FBG with an Arduino (I advise a ESP32) one needs to have a light* emitter and also a light receiver for the same end of the fiber. To achieve this, is used an unidirectional optical circulator coupled with both emitter, receiver and the FBG.

The difficulty is in finding those components suitable or sensing and at the same time inexpensive. That said, here https://europepmc.org/article/pmc/6651577 is an article depicting a portable FBG interrogator using a raspberry pi. The Pi uses a 120Mhz MCU , so a ESP32 MCU is also a suitable option.

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

in sum, it can be done quite easily.

  [1]: https://i.stack.imgur.com/ucq4G.png
  [2]: https://i.stack.imgur.com/QR4K0.png


body:
I have a few arduinos with ESPs, one of which is set up to measure temperature, and I'd like to have it send commands to other connected arduinos to perform various functions (open/close valves etc.)

In other words, the only communication I need is for one server to hopefully broadcast to a few clients. I don't really need to discern which client is which.

I am struggling to make sense of some of the documentation, and this is new to me.

For starters, I'm just trying to get any communication at all functional before I do the next parts.

My server device is set up as a soft access point and a WiFiServer.

My server ESP code looks a little something like this.

    #include <ESP8266WiFi.h>

    const byte ON = 2;
    const byte OFF = 1;
    int message;

    WiFiServer server(80);

    void setup()
    {
      Serial.begin(9600);
      WiFi.softAP("access", "point");
      server.begin();
    }

    void loop()
    {
        server.write(ON);
        delay(1000);
        server.write(OFF);
        delay(1000);
      }
    }

My client code looks a little something like this:

    #include <ESP8266WiFi.h>

    const byte ON = 2;
    const byte OFF = 1;

    byte ip[] = {192, 168, 4, 1};
    WiFiClient client;

    int message;

    void setup() {
      Serial.begin(9600);
      // connect to wifi.
      WiFi.mode(WIFI_STA);
      WiFi.begin("access", "point");

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

      //Now connect to server object
      if (client.connect(ip, 80) == 1) {
        Serial.println("Connected");
      } else {
        Serial.println("Not Connected");
      }
      delay(10000);

    }

    void loop() {
      if (client.connected()) {
        Serial.println("Waiting for Data");
        while(!client.available()){}
        String message = client.read();
        Serial.println(message);
      }
    }

The client code does connect to the server, and get stuck at the "Waiting for Data" line, never getting out of the while (!client.available) loop, so it clearly isn't receiving anything.

I'm sure I must look super dumb here, can someone help me understand the proper way to do what I want to do? Stuff I have seen online is primarily client -> server communication, do I HAVE to ping the server with something in order to receive something back?

Any help is appreciated. This is for a big project and I hope that I can make it all work. Thank you all very much!

title: ESP8266 - One server sending data to multiple clients

Answers: 1

body:
Your server doesn't handle clients. It is only a listening TCP socket. You must handle incoming TCP connections by checking if the server has a client available.

This is from [ChatServer example][1]. A telnet server to connect to with telnet terminal.

    void loop() {
      // wait for a new client:
      WiFiClient client = server.available();

      // when the client sends the first byte, say hello:
      if (client) {
        if (client.connected()) {
          if (!alreadyConnected) {
            Serial.println("We have a new client");
            client.println("Hello, client!");
            alreadyConnected = true;
          }

          if (client.available() > 0) {
            // read the byte incoming from the client:
            char c = client.read();
            // echo the byte back to the client:
            client.write(c);
            // echo the byte to the server as well:
            Serial.write(c);
          }
        } else {
          alreadyConnected = false;
          client.disconnect();
        }
      }
    }

----------

**UPDATE 2022**: The esp8266 Arduino core now has ArduinoWiFiServer which implements proper `server.available()` and has the write-to-all-clients functionality of Ethernet and WiFi libraries by Arduino. See the PagerServer example. (I am the author of esp8266 ArduinoWiFiServer class and PagerServer example)

from the PagerServer example:
```
void loop() {

  WiFiClient client = server.available();     // returns first client which has data to read or a 'false' client
  if (client) {                               // client is true only if it is connected and has data to read
    String s = client.readStringUntil('\n');  // read the message incoming from one of the clients
    s.trim();                                 // trim eventual \r
    Serial.println(s);                        // print the message to Serial Monitor
    client.print("echo: ");                   // this is only for the sending client
    server.println(s);                        // send the message to all connected clients
    server.flush();                           // flush the buffers
  }
}
```

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


body:
Board: __ESP32__

Script: [restore_offsets.ino from Adafruit's BNO055 library](https://github.com/adafruit/Adafruit_BNO055)

The only difference is I am storing the information in ESP's __NVS__ using the `Preferences` Library

### Code

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BNO055.h>
    #include <utility/imumaths.h>
    #include <Preferences.h>

    /* Set the delay between fresh samples */
    #define BNO055_SAMPLERATE_DELAY_MS (1000)

    Adafruit_BNO055 bno = Adafruit_BNO055(1390);

    Preferences Calibration;

    /**************************************************************************/
    /*
        Display some basic info about the sensor status
        */
    /**************************************************************************/
    void displaySensorStatus(void)
    {
        /* Get the system status values (mostly for debugging purposes) */
        uint8_t system_status, self_test_results, system_error;
        system_status = self_test_results = system_error = 0;
        bno.getSystemStatus(&system_status, &self_test_results, &system_error);

        /* Display the results in the Serial Monitor */
        Serial.println("");
        Serial.print("System Status: 0x");
        Serial.println(system_status, HEX);
        Serial.print("Self Test:     0x");
        Serial.println(self_test_results, HEX);
        Serial.print("System Error:  0x");
        Serial.println(system_error, HEX);
        Serial.println("");
        delay(500);
    }

    /**************************************************************************/
    /*
        Display sensor calibration status
        */
    /**************************************************************************/
    void displayCalStatus(void)
    {
        /* Get the four calibration values (0..3) */
        /* Any sensor data reporting 0 should be ignored, */
        /* 3 means 'fully calibrated" */
        uint8_t system, gyro, accel, mag;
        system = gyro = accel = mag = 0;
        bno.getCalibration(&system, &gyro, &accel, &mag);

        /* The data should be ignored until the system calibration is > 0 */
        Serial.print("\t");
        if (!system)
        {
            Serial.print("! ");
        }

        /* Display the individual values */
        Serial.print("Sys:");
        Serial.print(system, DEC);
        Serial.print(" G:");
        Serial.print(gyro, DEC);
        Serial.print(" A:");
        Serial.print(accel, DEC);
        Serial.print(" M:");
        Serial.print(mag, DEC);
    }

    /**************************************************************************/
    /*
        Display the raw calibration offset and radius data
        */
    /**************************************************************************/
    void displaySensorOffsets(const adafruit_bno055_offsets_t &calibData)
    {
        Serial.print("Accelerometer: ");
        Serial.print(calibData.accel_offset_x); Serial.print(" ");
        Serial.print(calibData.accel_offset_y); Serial.print(" ");
        Serial.print(calibData.accel_offset_z); Serial.print(" ");

        Serial.print("\nGyro: ");
        Serial.print(calibData.gyro_offset_x); Serial.print(" ");
        Serial.print(calibData.gyro_offset_y); Serial.print(" ");
        Serial.print(calibData.gyro_offset_z); Serial.print(" ");

        Serial.print("\nMag: ");
        Serial.print(calibData.mag_offset_x); Serial.print(" ");
        Serial.print(calibData.mag_offset_y); Serial.print(" ");
        Serial.print(calibData.mag_offset_z); Serial.print(" ");

        Serial.print("\nAccel Radius: ");
        Serial.print(calibData.accel_radius);

        Serial.print("\nMag Radius: ");
        Serial.print(calibData.mag_radius);
    }

    /**************************************************************************/
    /*
        Arduino setup function (automatically called at startup)
        */
    /**************************************************************************/
    void setup(void)
    {
        Wire.begin(13, 16, 400000);
        Serial.begin(115200);
        delay(1000);
        Serial.println("Orientation Sensor Test"); Serial.println("");

        /* Initialise the sensor */
        if (!bno.begin())
        {
            /* There was a problem detecting the BNO055 ... check your connections */
            Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
            while (1);
        }

        Calibration.begin("offsets", false);
        adafruit_bno055_offsets_t calibrationData;
        sensor_t sensor;

        int32_t bnoID = Calibration.getInt("bnoID");
         bool foundCalib = false;
        /*
        *  Look for the sensor's unique ID at the beginning oF EEPROM.
        *  This isn't foolproof, but it's better than nothing.
        */
        bno.getSensor(&sensor);
        if (bnoID != sensor.sensor_id)
        {
            Serial.println("\nNo Calibration Data for this sensor exists in NVS");
            delay(500);
        }
        else
        {
            Serial.println("\nFound Calibration for this sensor in NVS.");

            // Accelerometer offsets
            calibrationData.accel_offset_x = Calibration.getInt("acc_off_x");
            calibrationData.accel_offset_y = Calibration.getInt("acc_off_y");
            calibrationData.accel_offset_z = Calibration.getInt("acc_off_z");

            // Gyroscrope offsets
            calibrationData.gyro_offset_x = Calibration.getInt("gyr_off_x");
            calibrationData.gyro_offset_y = Calibration.getInt("gyr_off_y");
            calibrationData.gyro_offset_z = Calibration.getInt("gyr_off_z");

            // Magnetometer offsets
            calibrationData.mag_offset_x = Calibration.getInt("mag_off_x");
            calibrationData.mag_offset_y = Calibration.getInt("mag_off_y");
            calibrationData.mag_offset_z = Calibration.getInt("mag_off_z");

            displaySensorOffsets(calibrationData);

            Serial.println("\n\nRestoring Calibration data to the BNO055...");
            bno.setSensorOffsets(calibrationData);

            Serial.println("\n\nCalibration data loaded into BNO055");
            foundCalib = true;
        }

        delay(1000);

        /* Display some basic information on this sensor */
    //    displaySensorDetails();

        /* Optional: Display current status */
        displaySensorStatus();

       //Crystal must be configured AFTER loading calibration data into BNO055.
        bno.setExtCrystalUse(true);

        sensors_event_t event;
        bno.getEvent(&event);
        if (foundCalib){
            Serial.println("Move sensor slightly to calibrate magnetometers");
            while (!bno.isFullyCalibrated())
            {
                bno.getEvent(&event);
                displayCalStatus();
                Serial.println("");
                delay(BNO055_SAMPLERATE_DELAY_MS);
            }
        }
        else
        {
            Serial.println("Please Calibrate Sensor: ");
            while (!bno.isFullyCalibrated())
            {
                bno.getEvent(&event);

                Serial.print("X: ");
                Serial.print(event.orientation.x, 4);
                Serial.print("\tY: ");
                Serial.print(event.orientation.y, 4);
                Serial.print("\tZ: ");
                Serial.print(event.orientation.z, 4);

                /* Optional: Display calibration status */
                displayCalStatus();

                /* New line for the next sample */
                Serial.println("");

                /* Wait the specified delay before requesting new data */
                delay(BNO055_SAMPLERATE_DELAY_MS);
            }
        }

        Serial.println("\nFully calibrated!");
        Serial.println("--------------------------------");
        Serial.println("Calibration Results: ");
        adafruit_bno055_offsets_t newCalib;
        bno.getSensorOffsets(newCalib);
        displaySensorOffsets(newCalib);

        Serial.println("\n\nStoring calibration data to NVS...");

        bno.getSensor(&sensor);
        bnoID = sensor.sensor_id;
        // enter the Sensor ID
        Calibration.putInt("bnoID", bnoID);

        // store new Accelerometer offsets
        Calibration.putInt("acc_off_x", newCalib.accel_offset_x);
        Calibration.putInt("acc_off_y", newCalib.accel_offset_y);
        Calibration.putInt("acc_off_z", newCalib.accel_offset_z);

        // store new Gyroscope offsets
        Calibration.putInt("gyr_off_x", newCalib.gyro_offset_x);
        Calibration.putInt("gyr_off_y", newCalib.gyro_offset_y);
        Calibration.putInt("gyr_off_z", newCalib.gyro_offset_z);

        // store new Magnetometer offsets
        Calibration.putInt("mag_off_x", newCalib.mag_offset_x);
        Calibration.putInt("mag_off_y", newCalib.mag_offset_y);
        Calibration.putInt("mag_off_z", newCalib.mag_offset_z);
        Serial.println("Data stored to NVS..");

        Serial.println("\n--------------------------------\n");
        delay(500);
    }

    void loop() {
        /* Get a new sensor event */
        sensors_event_t event;
        bno.getEvent(&event);

        /* Display the floating point data */
        Serial.print("X: ");
        Serial.print(event.orientation.x, 4);
        Serial.print("\tY: ");
        Serial.print(event.orientation.y, 4);
        Serial.print("\tZ: ");
        Serial.print(event.orientation.z, 4);

        /* Optional: Display calibration status */
        displayCalStatus();

        /* Optional: Display sensor status (debug only) */
        displaySensorStatus();

        /* New line for the next sample */
        Serial.println("");

        /* Wait the specified delay before requesting new data */
        delay(BNO055_SAMPLERATE_DELAY_MS);
    }

The only difference in the code is instead of passing the offset struct I save information individually using `putInt` method

### steps

1. I calibrate the sensor connected via I2C
2. Once the calibration is done store it into NVS
3. Observe values for a bit
4. Restart the node and retreive the offsets from NVS

## Problem

The calibration offsets are stored into the BNO and it takes _hella time_ in the following block:

       if (foundCalib){
            Serial.println("Move sensor slightly to calibrate magnetometers");
            while (!bno.isFullyCalibrated())
            {
                bno.getEvent(&event);
                displayCalStatus();
                Serial.println("");
                delay(BNO055_SAMPLERATE_DELAY_MS);
            }
        }

I added the `displayCalStatus` to see the values of the accelerometer, gyroscope and magnetometer and all values within the block are Zero.

Doesn't this defy the whole idea of storing offsets in the first place if the values are all zero?

### Output from board

    Found Calibration for this sensor in NVS.
    Accelerometer: 19 -10 4
    Gyro: -3 -4 9
    Mag: 589 986 1473
    Accel Radius: 0
    Mag Radius: 0

    Restoring Calibration data to the BNO055...

    Calibration data loaded into BNO055

    System Status: 0x0
    Self Test:     0xF
    System Error:  0x0

    Move sensor slightly to calibrate magnetometers
     ! Sys:0 G:0 A:0 M:0
     ! Sys:0 G:0 A:0 M:0
     ! Sys:0 G:0 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0
     ! Sys:0 G:3 A:0 M:0

As you can observe the calibration are all set to 0 and I have to do the whole thing again. why ?

title: After restoring the BNO055 offsets to the sensor the calibration values are all 0

Answers: 1

body:
The displayCalStatus() function shows the status of the calibration, not the offsets or current sensor values. With calibration in progress the status is zero. Once the calibration of a sensor is complete, the status is 3. The sensor starts the calibration itself with first movements after power up.

The set offsets are used after power-up only until the initial automatic calibration finished.

from datasheet:
> Once  the  device  is  calibrated,  the  calibration  profile  can  be  reused  to  get  the
> correct  orientation  data  **immediately  after  ‘Power  of  Reset’**.  However,  once  the  sensor  enters  the  internal
> calibration  routine,  the  calibration  profile  **is  overwritten**
> with  the  newly  obtained  sensor  offsets  and  sensor radius.


body:
I'm using now() and millis() to trigger events after a certain time has passed.
I am aware, and it's also easily found on the web, that millis() rolls over after a certain time has passed and for code that has to run indefinitely you have to handle this.

However I am not aware of if now() can do the same at some point. I mean it does count the seconds from the 1.1.1970 so just regarding this fact, it should not roll over. However, just like millis() this has to be counted somewhere no? How does it work?

title: Can now() roll over just like millis()?

Answers: 3

body:
If `now()` is from the [`TimeLib.h` library][1], then [this definition][2]:

    typedef unsigned long time_t;

indicates time_t is 32-bit unsigned value. Since it represents seconds since 1970-Jan-01 00:00:00, it will experience a rollover when representing dates past approximately 2106 (1970-Jan-01 + 2^32 seconds). Being unsigned, it also cannot represent dates earlier than 1970-Jan-01.

This is slightly different than the [2038 Rollover Problem][3], which occurs when a system defines a `time_t` as a **signed** 32-bit integer, and thus experiences this rollover earlier, in year 2038.

All of this depends on how/where the type `time_t` is defined for your CPU architecture, and this answer assumes an 8-bit AVR like Arduino Uno. If you use a different architecture, for which TimeLib.h has a different type definition, read the source code to find out exactly what you're dealing with.

  [1]: https://github.com/PaulStoffregen/Time/blob/master/TimeLib.h
  [2]: https://github.com/PaulStoffregen/Time/blob/master/TimeLib.h#L21
  [3]: https://en.wikipedia.org/wiki/Year_2038_problem

body:
`now()` is a function that is specific to *Intel Curie* based boards.

It returns an `unsigned long` (which on a 32-bit system is the same as an `unsigned int`) and so can provide the number of seconds since 1/1/1970 up until the year 2106, at which point it will roll over.

If you plan on having your system run continuously for more than the next 88 years you will have to deal with that rollover correctly, including:

* Using subtraction to "wrap around" your calculations
* Not trying to calculate any periods longer than 136 years

body:
Time represented in seconds from 1970-01-01 is called Epoch or Unix time. Function now() and similar functions in Arduino libraries returning 'epoch' use 32-bit representation. Some use the time_t type defined in basic includes distributed with the compiler (types.h). On some compilers or in many time and RTC libraries the 32-bit type is signed allowing to represent time before 1970, on some system the type is unsigned.

The signed 32 bit type for epoch time overflows in 2038 ([Year 2038 problem][1]). The unsigned 32-bit overflows in 2106.

I use the TimeLib library and it uses the time_t type defined on SAMD and ESP in type.h distributed with the compiler. ARM GCC has time_t as long, which is signed 32 bit type. The same for ESP boards with xtensa compiler. time_t for AVR is defined in the TimeLib library as unsigned 32bit type and overflows in 2016.

  [1]: https://en.wikipedia.org/wiki/Year_2038_problem


body:
I buy a stm32 board as picture below, I connect the Boot0 to 3.3 and use the serial port  download the program.

I use the library https://github.com/rogerclarkmelbourne/Arduino_STM32

The second and third picture is my program. After I download the program, the led on board shine and the serial is normal, but after I press RESET on board, it is not shine. Seemly, the program vanish.

Why it is so ? And how to let the program in board after press reset ?

>[![enter image description here][1]][1]
>
>[![enter image description here][2]][2]
>
>[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/fs6nq.jpg
  [2]: https://i.stack.imgur.com/Yu6F3.jpg
  [3]: https://i.stack.imgur.com/t2LBJ.jpg

title: Why after the reset the program vanish?

Answers: 2

body:
By connecting `BOOT0` to 3.3V you are telling the chip *When I reset for whatever reason you must go into the bootloader*.

So you reset, and it goes into the bootloader. You then upload your sketch.

At that point the programming software tells the bootloader "Ok, you are done now. Run the program". And it does.

Until you reset. And because *you are telling it to go into the bootloader with BOOT0* it dutifully does so, waiting for you to load a new program.

The old program is still there, but you just aren't letting run, since you are insisting that the chip go into the bootloader when you reset.

In order to get your program to run and not the bootloader you must disconnect BOOT0 so it doesn't enter the bootloader.

You *only* need to connect the BOOT0 *when you want to put a new program on there*.

body:
From http://wiki.stm32duino.com/index.php?title=Bootloader

> Activating the bootloader is done through forcing two boot pins (and
> then resetting the MCU). Many boards have one or more boot pins
> exposed as jumpers or push buttons.
>
> Normal boot (to user firmware, which may be a secondary bootloader):
>
>  - Boot0 LOW
>  - Boot1 LOW
>
> Allow firmware upload through USART1:
>
>  - Boot0 HIGH
>  - Boot1 LOW

After uploading new software through the serial, move `Boot0` back to `GND` so that the MCU loads the firmware you uploaded, rather than it's internal serial bootloader.


body:
We created a website hosted by 000webhost and we're trying to post data from our nodeMCU to the database using the sketch below, but the database doesn't seem to show any received data. How do you fix this?
[![Sketch for the nodemcu][1]][1]

and below is the php code to rtecieve the data:
[![PHP codes][2]][2]

  [1]: https://i.stack.imgur.com/x7iFM.png
  [2]: https://i.stack.imgur.com/h9inZ.png

    #include <ESP8266WiFi.h>

    const char* ssid = "Jino";
    const char* pass = "myinternet";
    char server[] = "cdgresearch.000webhostapp.com";

    WiFiClient client;

    int led = 2;

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid,pass);
      pinMode(led,OUTPUT);
      digitalWrite(led, HIGH);

      Serial.println("Connecting to: ");
      Serial.println(ssid);
      Serial.print("Connecting");

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

      delay(300);
      digitalWrite(led, LOW);
      Serial.println();
      Serial.println("Successfully connected to the network");
      Serial.print("NodeMCU IP Address: ");
      Serial.println(WiFi.localIP());

      if (client.connect(server, 80)){
        String data = "incoming=fromDuino&incoming2=FROMDUINO2";
        client.println("POST /tag.php? HTTP/1.1");
        client.println("Host: cdgresearch.000webhostapp.com");
        client.println("User-Agent: 8266/1.0");
        client.println("Connection: close");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.print("Content-Length: ");
        client.print("\n\n");
        client.println(data);
        client.stop();

        Serial.println("Connected to server");
        }
        else{
        Serial.println("Failed to Connect to server...");
        }

      client.stop();
      Serial.println("Disconnected from Server");
    }

    void loop() {
     // put your main code here, to run repeatedly:
    }

title: How to post data to database using nodeMCU?

Answers: 3

body: HTTP requires \r\n as line ending. println adds \r\n. So to print the host name to client use println and remove \n from the string. And replace `client.print("\n\n")` with `client.println(); client.println();` (or println the length and then use one println)

body:
You are using POST method in the php script ($_POST['var']) and trying to pass parameters to the script by adding them in the URL. This addition of the parameters would work only if it were a GET method in place of a POST method.

Change wherever you have written POST to GET (Both in the php script and the node mcu code) and your data will be inserted into the database.

1) Change both the $_POST['var'] to $_GET['var'] in the php file.

2) Change client.println("POST /tag.php HTTP/1.1") to client.println("GET /tag.php?incoming=fromDuino&incoming2=fromDuino2 HTTP/1.1")

Also, you can go through this [link][1] to learn more about how to make a
POST request. And can you show me the whole code or the classes that you have instantiated?

  [1]: https://techtutorialsx.com/2016/07/21/esp8266-post-requests/

body:
1st I would check each part i.e.
First check your PHP script can insert by setting some values in the script i.e. incomming = "somejunk";

I assume the PHP include file connects to your DB and changes into the corresponding DB?
I assume you have setup a user for the DB in say cPanel and set privileges

Your method of sending data is different to my working format...
You are sending the data at the end rather than the beginning...

Also if you look at your server log you can see if the values get sent

    if (client.connect(server, httpPort)) {
      // connected to resource
      // send data
      client.print("POST /dir/file.php?field1=");
      client.print(data1&field2=data2); // must be url encoded
      client.println(" HTTP/1.1");
      client.println("Host: www.domainname.com");
      // client.println("Content-Length: " + String(data.length())); // you dont need
      client.println("User-Agent: ESP8266");
      client.println("Connection: close");
      client.println();


body:
I want to use stm32duino to control 5110, I use the library http://www.rinkydinkelectronics.com/download.php?f=LCD5110_Basic.zip

Before, I use arduino pro mini to control 5110 by this library, it works well. But when I use stm32, it fails. Whether this library is not suitable for stm32duino ? If so, which library is suitable for me ?

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

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

title: How to use stm32duino control 5110?

Answers: 1

body:
The library you linked to does not indicate it works for STM32 architecture. The display uses SPI, and each architecture has it's own way of implementing such peripherals.

There is this library: https://github.com/KenjutsuGH/Adafruit-PCD8544-Nokia-5110-LCD-library which is a port of the Adafruit 5110 driver to STMduino.


body:
I have a nodemcu connected to a shift register(https://www.amazon.de/gp/product/B07CHBYR7Z) to control an 8 channel relay board (https://www.amazon.de/Elegoo-Relaismodul-Optokoppler-Arduino-Raspberry/dp/B01M61VVGV). The realy board is connected to various pumps. The setup itself works quite well normally. However after some switching cycles or when I manually bridge the relay to activate a pump the shift register suddenly either doesnt react at all. Switches on everything or is off by one. I read that it might be possible that I have flow back from the relay coil so I added the diode over the gnd and vcc pin of the relay board. However that didnt help either. Can anybody tell me what I am doing wrong? I hope the schematic is legible.

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

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

title: Shift register with relay board behaving erratically

Answers: 1

body:
If this is a noise issue, there are a number of mitigating actions to consider.  Also, consider that most if not all noise mitigating approaches are generic and may not apply to all situations.

 1. It is almost always easier to mitigate noise at the source.  Filtering the power & shielding are two approaches.
 2. When laying out digital integrated circuits, it is common to include [bypass or decoupling capacitors][1] as near as possible to each integrated circuit.  If unfamiliar with these, these capacitors go across the power pins of the integrated circuit.
 3. If an electrically noisy environment is anticipated, making all communication leads and cables as short as possible prevents the likely hood of unexpected results.
 4. If cables need to be long different communications methods such as [balanced line][2] or [differential signalling][3] should be considered.
 5. Bring all power grounds to a single point.  This mitigates [current loops][4] which can cause unexpected power voltage fluctuations.
 6. Consider the power requirements and generally use a power supply that is rated for double to have a margin of safety.
 7. Avoid running cables containing high power or switched power near or in parallel to cables containing low voltage logic.

For this particular application / design:

 1. Likely the reversed bias diode on the relay power supply lines is not needed.  There appears to be optical isolators on the relay board which should prevent the inductance of the relays from feeding back.
 2. Verify you are creating the correct signal to the 74HC595 chip.  Use the [timing diagrams on page 8 of this ti.com 74HC595 specification sheet][5] as a guide.
 3. Consider the gauge of the power cables.  Thinner wires over longer runs will drop the voltage proportional to the current demand.  If all 8 relays are active, the current demand may be as much as an Amp.

  [1]: https://en.wikipedia.org/wiki/Decoupling_capacitor
  [2]: https://en.wikipedia.org/wiki/Balanced_line
  [3]: https://en.wikipedia.org/wiki/Differential_signaling
  [4]: https://en.wikipedia.org/wiki/Current_loop
  [5]: http://www.ti.com/lit/ds/symlink/sn74hc595.pdf


body:
My esp is consuming 180mA with a led blink. The same consumption happens when I put it in WIFI_STA mode with the `WiFi.mode(WIFI_STA);` function. <BR>
**What should I do to reduce consumption?** Used AMS1117 CI as tension regulator.

**My code:**

    void setup() {
      pinMode(2, OUTPUT); // pin number 2 is on board blue led
    }

    void loop() {
      digitalWrite(2, LOW); // blue led highlight with LOW level
      delay(100);
      digitalWrite(2, HIGH);
      delay(100);
    }

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

  [1]: https://i.stack.imgur.com/4Y8IS.jpg
**Why all this consumption?**

title: ESP8266 - 12F High consumption in led blink (with pictures)

Answers: 1

body:
The SDK library of the ESP8266 remembers on flash memory the mode, SSID and password of the last WiFi network it connected. At start or by enabling STA mode it tries to connect to that network. The SDK library is always part of the compiled sketch for the esp8266.

The esp8266 WiFi library has some functions to control this:

 - WiFi.[setAutoConnect][1](false)
 - WiFi.[disconnect][2](true);
 - WiFi.persistent(false)

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#setautoconnect
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#disconnect


body:
I am making a simple calculator with Arduino Uno R3. It only has +, -, x and /.

I use 3 libraries:

1. This use for LCD with I2C module. [Arduino-LiquidCrystal-I2C-library][1]
2. This use for keypad 4x4. [Chris--A/Keypad][2]
3. And this: [jamesgregson/expression_parser][3]

  [1]: https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library
  [2]: https://github.com/Chris--A/Keypad
  [3]: https://github.com/jamesgregson/expression_parser
My code:

    #include "expression_parser.h"
    #include <Keypad.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x3F, 16, 2);

    const byte ROWS = 4;
    const byte COLS = 4;

    char keys[ROWS][COLS] = {
      {'1', '2', '3', '+'},
      {'4', '5', '6', '-'},
      {'7', '8', '9', '*'},
      {'.', '0', '=', '/'}
    };

    byte rowPins[ROWS] = {10, 9, 8, 7};
    byte colPins[COLS] = {6, 5, 4, 3};

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    String s = "";
    char ex[16];

    void setup() {
      Serial.begin(9600);
      lcd.init();
      lcd.backlight();
      lcd.setCursor(0, 0);
    }

    int cur = 0;
    bool enter = false;

    void loop()
    {
      char key = keypad.getKey();

      if ((key != '=') && (key != NO_KEY) ) {
        if (!enter) {
          Serial.println(F("key"));
          if(key=='/')
            lcd.print(F("':'"));
          else
          if (key=='*')
            lcd.print(F("'x'"));
          else
            lcd.print(F("key"));
          s = s + key;
          cur++;
          lcd.setCursor(cur, 0);
        } else {

          lcd.setCursor(0, 0);
          lcd.print("");
          enter = false;
          lcd.setCursor(0, 0);
          cur = 0;
          lcd.print(F("key"));
          s = "";
          s = s + key;
          cur++;
          lcd.setCursor(cur, 0);
        }
      } else if (key == '=') {
        enter = true;

        if ((s[0] == '=') || (s[0] == '/') || (s[0] == '*') || (s[0] == '.')) {
          lcd.setCursor(0, 1);
          lcd.print("Error");
        } else {
          lcd.setCursor(0, 1);
          lcd.print("");
          s.toCharArray(ex, 16);
          Serial.println(F("s"));
          int re = parse_expression(ex);
          String check = String(re);
          if (check.length() > 15) {
            lcd.setCursor(0, 1);
            lcd.print("Overflow");
          } else {
            Serial.println(re);
            lcd.setCursor(0, 1);
            lcd.print("=");
            lcd.print(F("re"));
          }
        }
      }
    }
I ran it and got error:

Global variables use 3302 bytes (161%) of dynamic memory, leaving -1254 bytes for local variables. Maximum is 2048 bytes.
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
Error compiling for board Arduino/Genuino Uno.

So what should I do?

title: Not enough memory

Answers: 2

body:
Your own declared global variables do not use up much space.

Watch out for using string, this can be extended during the flow of the program thus using more.

The problem is in the libraries.

What you can do:

- Leave out the include and related code per library to see which is using up a lot of global space.
- When you find out which causes problems, try to follow the internals of the library to see if there is some buffered memory that you can decrease.

If not, I'm afraid the only solution is to move to an Arduino with more memory (like the Arduino Mega which has 8 KB).

With the use of PROGMEM you can save some space on

    char keys[ROWS][COLS] = {
      {'1', '2', '3', '+'},
      {'4', '5', '6', '-'},
      {'7', '8', '9', '*'},
      {'.', '0', '=', '/'}
    };

    byte rowPins[ROWS] = {10, 9, 8, 7};
    byte colPins[COLS] = {6, 5, 4, 3};

Because it will be placed in Flash instead of SRAM, but it will save you just 24 bytes.

body:
Move up to a '1284P based board. They have 16K of SRAM and 12 more IO pins, will give you plenty of room to add and expand into more functions later.

I offer '1284P boards in several form factors at www.crossroadsfencing.com/BobuinoRev17/

It is easy to add to the IDE with MCUdude's MegaCore
https://github.com/MCUdude/MegaCore


body:
So we were asked to do something with a force sensitive resistor so naturally i thought of a project which takes the name of the main component which is force and applies it ,mine works by as  you apply more and more pressure to the sensor it takes this value and displays it on an lcd but the display should be a bar graph which increases as the pressure increases. the problem is i dont really know how to do a bar graph on a 16x2 lcd. Please help. (my lcd has an I2c)

here is my code for the pressure sensor so far

    int fsrAnalogPin = 0; // FSR is connected to analog 0
    int fsrReading;      // the analog reading from the FSR resistor divider

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

    void loop(void) {
      fsrReading = analogRead(fsrAnalogPin);
      Serial.print("Analog reading = ");
      Serial.println(fsrReading);
      delay(100);
    }

ok so i improved my code and i finally got it this code displays the force detected by the fsr into a bar graph

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <LcdBarGraphX.h>
    #include<LcdBarGraph.h>

    byte lcdNumCols = 20; // -- number of columns in the LCD

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);   // -- creating LCD instance

    int fsrAnalogPin = 0; // FSR is connected to A0

    // -- creating a 4 chars wide bars
    LcdBarGraphX lbg0(&lcd, 16, 0, 0); // -- First line at column 0 and row 0 with 16 columns

    void setup(void) {
      Serial.begin(9600);   // We'll send debugging information via the Serial monitor
      lcd.begin(4, lcdNumCols); // start lcd with 2 rows and 16 columns
      lcd.clear();
      delay(100);
    }

    void loop(void) {
      lbg0.drawValue( analogRead(fsrAnalogPin), 9); // the 9  is the maximum range you want for pressure
      Serial.print("Analog reading = ");
      Serial.println(fsrReading);
      delay(100);
    }

title: Arduino Force sensitive Resistor with an lcd

Answers: 2

body:
From the Library Manager, install the [LcdBarGraphX][1] library by Balazs Kelemen.

There are several examples there as well.

  [1]: https://platformio.org/lib/show/681/LcdBarGraphX

body:
There's two ways you can do it: the *easy* way, and the *fancy* way.

The easy way really is easy.  Since the display can only display characters you just display characters - enough to represent a bar graph.

If you have a display with "Rom Code A00"<sup>*</sup> then character 255 is a solid block (▇) so you just print between 0 and 16 of them in a row.  0 is 0% and 16 is 100%. (If you have ROM Code A02 then you could just use `#`, or custom design a character - see below).

    Force:▒▒▒▒▒▒▒▒▒▒
    ▇▇▇▇▇▇▇▇▇▒▒▒▒▒▒▒

Or with `#`:

    Force:▒▒▒▒▒▒▒▒▒▒
    #########▒▒▒▒▒▒▒

The fancy way is to use the programmable characters facility.  You would create 4 new characters that partially fill a block.  Each character is 5 pixels wide, so creating a character with 1 column of pixels set (▏), one with 2 set (▍), 3 set (▌) and 4 set (▋) (you already have all 5 set on in character 255 if you have ROM Code A00 - otherwise define a 5th with all 5 columns on).  Now you can be clever and work out:

1. How many full characters to print, and
2. Which of the extra characters to print on the end.

That gives you effectively 16*5 (80) pixels of horizontal resolution (albeit with a small gap between each set of 5 pixels).

Exactly how you do whichever of those methods you choose is now up to you.

----

*: ROM Code A00 is the character ROM with Japanese characters in the characters 128-255.  ROM Code A02 has European accented characters instead.


body:
I am a novice in Arduino programming and I'm setting up an Arduino controlled, underwater time-lapse camera to take a picture every 2 hours.  It's going in the ocean for a month and I want to be sure that the code will not fail because of the upper limit that normal integers can go.
The Arduino simply switches on a relay (connected to the LED_PIN 11) and the camera does the rest, using a script from the awesome [Canon Hackers Development Kit C.H.D.K.][1]

I've tried several variations of sketch, some using simple delay, some with millis and some with counters that print what increment the loop it up to.

One of my fast running test sketches, that used a counter, stopped prematurely, I suspect due to hitting the integer limit but I'm not sure if this only occurred due to the fact that it had a counter in the sketch.  So I've gone back to the simplest sketch I can find hoping it will not have this issue.

I think I read that once the integer limit is reached, the sketch will simply restart.  Or maybe it will become unpredictable.  I'd rather the  former than the latter.

Any suggestions would be welcome.

I am sure there are many ways to go about this but I'm looking for the simplest and most robust one I can find, so that I can adjust the async timing easily ie.
loop starts
CameraOn for 10 seconds
CameraOff for 2 hours
Loop repeats

thanks in advance for your consideration

Here's the sketch I'm testing right now.

    #define LED_PIN 11
    #define LED_OFF 7200000     // 2 hours in millis
    #define LED_ON  8000       // 6 seconds in millis

    unsigned long ms;        //time from millis()
    unsigned long msLast;    //last time the LED changed state
    boolean ledState;        //current LED state

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

    void loop(void)
    {
        ms = millis();
        blinkLED();
    }

    void blinkLED(void)
    {
        if (ms - msLast > (ledState ? LED_OFF : LED_ON)) {
            digitalWrite(LED_PIN, ledState = !ledState);
            msLast = ms;
        }
    }

  [1]: https://chdk.setepontos.com/index.php?action=forum

==================================================================

Okay, I've come up with a new, much simpler sketch based on delay.
Can someone please tell me if this is more robust in terms of continued looping for weeks on end?

    #define LED_PIN 11

    void setup()
    {
       Serial.begin(9600);
       pinMode(LED_PIN, OUTPUT);
       digitalWrite(LED_PIN, HIGH);
    }

    void loop()
       {
           delay(7200000);                 // 2 hours in millis
           digitalWrite(LED_PIN, LOW);
           delay(8000);                    // 8 seconds in millis
           digitalWrite(LED_PIN, HIGH);

       }

title: Will this sketch eventually fail because of integer limit issue?

Answers: 1

body: No, the sketches will not fail or work incorrectly. The Arduino "delay()" function calls the "micros()" function for timing. The "micros()" function uses the Atmel's TIMER0 clock and waits for 1000 microseconds (1 milliseconds) each iteration. The TIMER0 overflows about every 70 minutes, but the program code used in the "delay()" function handles that overflow correctly.


body:
By using boolean and flag, I can now control the green light but the program cannot repeat or loop the sequence for traffic light from red to yellow to green. If I don't use flag, the sequence red-yellow-green LED can be looped but I can't control and trigger green light on app.

My current project also serial communicate from NodeMCU to Arduino.

    #include <SoftwareSerial.h>

    SoftwareSerial nodemcu(2,3);
    long int data;

    boolean start = true;

    void setup() {
      pinMode(7,OUTPUT);//greenbulb
      pinMode(8,OUTPUT);//yellowbulb
      pinMode(9,OUTPUT);//redbulb

    Serial.begin(9600);
    nodemcu.begin(9600);

    }

    void changeLights()
    {
      digitalWrite(7,LOW);// greenbulb
      digitalWrite(8,LOW); // yellowbulb
      digitalWrite(9,HIGH);// redbulb
      delay(7000);

      digitalWrite(7,HIGH);// greenbulb
      digitalWrite(8,LOW);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(5000);

      digitalWrite(7,LOW);// greenbulb
      digitalWrite(8,LOW);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(1000);
      digitalWrite(7,HIGH);// greenbulb
      digitalWrite(8,LOW);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(1000);
      digitalWrite(7,LOW);// greenbulb
      digitalWrite(8,LOW);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(1000);
      digitalWrite(7,HIGH);// greenbulb
      digitalWrite(8,LOW);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(1000);

      digitalWrite(7,LOW);// greenbulb
      digitalWrite(8,HIGH);// yellowbulb
      digitalWrite(9,LOW);// redbulb
      delay(2000);
    }

    void loop() {

    if ( nodemcu.available() > 0 )
    {
      data = nodemcu.parseInt();
      delay(100);
      Serial.println(data);

          if (( data == 10) && (start == true)){
               changeLights();
                start = false;
          }

          if (( data == 11) && (start == false)){
          digitalWrite(7, HIGH);
          digitalWrite(9, LOW);
          digitalWrite(8, LOW);
                start = true;
          }
    }
    }

title: Stop and continue loop by using boolean flag for traffic light

Answers: 1

body:
This is not an answer (that is looking at the BlinkWithoutDelay as Juraj mentioned), but I want to provide a way how to greatly reduce your program and use this method in future.

You are repeating

    digitalWrite(7,LOW);// greenbulb
    digitalWrite(8,HIGH);// yellowbulb
    digitalWrite(9,LOW);// redbulb
    delay(2000);

A lot, with variations of LOW/HIGH and the delay time. Instead, use a function that has parameters:

    void changeLight(int green, int yellow, int red, int delayTime)
    {
        digitalWrite(7, green);
        digitalWrite(8, yellow);
        digitalWrite(9, red);
        delay(delayTime);
    }

And you can call it by

   changeLight(LOW, HIGH, LOW, 2000);

You can do this for all of the 4 line repeats.


body:
The idea is when a switch is pushed, the corresponding tone will be played as well as lighting up the corresponding LED. I have the circuit set up to where each array matches another, for example Switch one will play tone 1 and light LED 1. When the switch is released the LED turns off and the tone no longer plays.

However I have to use an Array for the sketch instead of declaring each individual switch, led, and tone.  My issue is when I compile the code, I get the error message "i" is not declared.  Not sure where my error is within the for loop in the setup portion of the sketch.

I tried following the example from the Exploring Arduino web page but it did not help.

    #define NOTE_C   262 //HZ
    #define NOTE_D   294 //HZ
    #define NOTE_E   330 //HZ
    #define NOTE_G   392 //HZ
    #define NOTE_A   440 //HZ

    const int SPEAKER = 9;   //speaker on pin 10
    int LED[5] = {13, 12, 11, 10, 8};   //led pins
    int ledcount = 5;
    int buttonState;
    int buttonState1;
    int buttonState2;
    int buttonState3;
    int buttonState4;

    //Button Array
    int Buttons[5]= {3, 4, 5, 6, 7};
    int ButtonCount = 5;
    const int numButtons = sizeof(Buttons) / sizeof (Buttons[0]);

    //Tone Note Array
    int Notes[5] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

    void setup()
    {
      for (int i = 0; i < sizeof (Buttons) / sizeof(Buttons[0]); i++){
      pinMode(Buttons[], INPUT);
    }
      for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
      pinMode(LED[], OUTPUT);
    }
      for (int i = 0; i < numButtons; i++){
      pinMode(Buttons[i], INPUT);
      debouncer[i].attach(Buttons[i]);
      debouncer[i].interval(100);
    }
      buttonState = digitalRead(Buttons[0]);
      buttonState1 = digitalRead(Buttons[1]);
      buttonState2 = digitalRead(Buttons[2]);
      buttonState3 = digitalRead(Buttons[3]);
      buttonState4 = digitalRead(Buttons[4]);
    }

    void loop()
    {

      if (buttonState == HIGH)
      { tone(SPEAKER, Notes[0]);
      digitalWrite(LED[0], HIGH);
      }
      else if (buttonState1 == HIGH)
      {tone(SPEAKER, Notes[1]);
      digitalWrite(LED[1], HIGH);
     }
      else if (buttonState2 == HIGH)
      {tone(SPEAKER, Notes[2]);
      digitalWrite(LED[2], HIGH);
     }
      else if (buttonState3 == HIGH)
      {tone(SPEAKER, Notes[3]);
      digitalWrite(LED[3], HIGH);
     }
      else if (buttonState4 == HIGH)
      {tone(SPEAKER, Notes[4]);
       digitalWrite(LED[4], HIGH);
     }

      else
     {
      digitalWrite(LED[5], LOW);
      noTone(SPEAKER);
     }
    }

title: 5 switches, 5 leds, 5 tones, in an Array

Answers: 1

body:
You have a rogue `;` here:

      for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
      pinMode(LED[], OUTPUT);                                 ^------HERE
    }

That is terminating the `for`, making it empty, and the following block is a completely different scope.

Another thing I spotted - you aren't putting `i` into your array index `LED[]` (should be `LED[i]`).  The same is true with Buttons[].

However, on a different subject, this:

    buttonState == digitalRead(Buttons[0]);
    buttonState == digitalRead(Buttons[1]);
    buttonState == digitalRead(Buttons[2]);
    buttonState == digitalRead(Buttons[3]);
    buttonState == digitalRead(Buttons[4]);

is pretty meaningless.  You are comparing values and throwing away the result.

In a similar vein:

    if (buttonState = Buttons[0])

stores the current value of Buttons[0] into buttonState and succeeds if `Buttons[0]` is anything other than 0.  The same goes for all the others.

You need to sort out your comparisons (`==`) and your assignments (`=`) and also sort out what you think you are doing with all those buttonStates at the top of loop.


body:
I have a LCD screen, and I wanted to use it with a Simon Says game that I am making. I tried the tutorial on the Arduino website, but it doesn't work. Then I tried another tutorial on [Adafruit][1]. On this one, the LCD screen seemed brighter which is good, but it also doesn't work.

**What it is supposed to look like:**
[![enter image description here][2]][2]

**My code:**

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    void setup() {
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.print("Test!");
      delay(500);
      lcd.clear();
      delay(500);
    }

I have verified that the wiring is correct on the official version and the Adafruit version, and my screen is brand new from the kit, so what is wrong?

**Edit 1:**

Let me define "doesn't work." I can turn the potentiometer, but nothing changes. I can't even see white rectangles or even a single pixel on the display. It is blank. Absolutely nothing to see other than the blacklight, which does work.

**Edit 2:**

Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!

  [1]: https://learn.adafruit.com/adafruit-arduino-lesson-11-lcd-displays-1/
  [2]: https://i.stack.imgur.com/nI573.jpg

title: My brand new LCD screen doesn't display anything, even though there is no code errors?

Answers: 1

body: Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!


body:
I am having an issue when I try to upload a program to the board. I am working on a Simon Says game, and when I first started uploading, my computer handled it fine. Everything worked properly.

However, now I have added 3 LEDs for the colors and 3 buttons. I wrote a program for them to start the game, and then went to test it. That's when my Arduino would beep 3 times and then 75% of the time my computer would give me this error:

> Problem uploading to board.
See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

25% of the other time I get this:

> An error occurred while uploading the sketch

It seems as though my project is getting too complicated for the Arduino to handle maybe? This is my code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    int s = 13; // Speaker
    int r = 6;  // Red LED
    int y = 5;  // Yellow LED
    int g = 4;  // Green LED
    int b1 = 3; // Red button
    int b2 = 2; // Yellow button
    int b3 = 1; // Green button - I don't know if pin 1 works.

    void setup() {
      lcd.begin(16, 2);
      pinMode(s, OUTPUT);
      pinMode(r, OUTPUT);
      pinMode(y, OUTPUT);
      pinMode(g, OUTPUT);
      pinMode(b1, INPUT);
      pinMode(b2, INPUT);
      // pinMode(b3, INPUT); Does pin 1 work?
    }

    void loop() {
      lcd.print("Press any button");
      lcd.setCursor(4, 1);
      lcd.print("to play!");
      while (true) {
        if (digitalRead(b1) == HIGH) {
          break;
        }
        delay(50);
      }
      lcd.clear();
      delay(1000);
      lcd.setCursor(1, 0);
      lcd.print("Simon's turn!");
      delay(1000);
      while (true) {
        // For now, I don't want to loop. I will finish the program when this     problem is resolved.
        delay(50);
      }
    }

Does anyone know the solution to this problem?

  [1]: http://www.arduino.cc/en/Guide/Troubleshooting#upload

title: Problem uploading to board error, but I've selected the port and the board type?

Answers: 2

body:
Arduino play around from time to time. Which one do you use.

Unplug it and plug it back in. If Pin D0 and D1 are occupied, you may have problems with uploading.

body:
Remove anything that is connected to the Tx and Rx pin(communication pins)

And try uploading the code and it might possibly work


body: I have a button with two isolated tracks. I want to be able to wake up esp from deepSleep with this button, and also detect that it was clicked. So i can't connect it to reset, because esp won't work if i don't release a button. And if it's not at deepSleep, it will reset, and i don't want it. How to do this?

title: Wake up ESP8266 from deepSleep with a button

Answers: 2

body:
Use some other pin to hold RESET HIGH or to disconnect the button from RESET while the esp8266 is not running.

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

<!-- End schematic -->

[I asked on EE SE][1] for the missing part of the circuit.

  [1]: https://electronics.stackexchange.com/questions/404458/button-which-wakes-up-the-esp8266-from-deep-sleep-but-can-be-used-as-common-but

body:
You can't stop deepSleep, all you can do is reset the board so connect the button to the reset pin and make the appropiate set-up:

 1. Connect a pullup resistor (10k) in RST
 2. Connect the button from RST
    to GND

When you push, RST has GND so the ESP gets reseted.

Remember that deepsleep only works for about an hour so you have to contemplate this situation, too, maybe with a static variable...

**EDIT** Thanks Juraj for the comment: "from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."


body:
I am doing a project right now that involves a Neo 6M GPS module, a micro sd card module and 6 BH1750 light sensors. All the modules work fine when testing them standalone, especially the GPS module works as it should with TinyGPS++ example sketches.
When i run the "DeviceExample" sketch, it takes around 6 seconds to revieve time and around 10 seconds to recieve the location. However in my own sketch it only updates time every 3 or more seconds as well as i think it also updates location very slow.

Sometimes it even works for a short time, sometimes it never works, no matter how long the sketch runs.
Here is an example log:
As you can see, the sketch did not retrieve full date 20 secs after starting, but time is updating every second. Yet you can see that the time isn't updated anymore 5 seconds before the module is retrieving location and then the update interval gets slowed down, even though the module itself still indicates the update interval of around .5-1 second.

The Neo 6M GPS module is connected directly to RX,TX,GND,VCC and works fine with the example sketches. Has anybody a solution to this?

    ms(), longitude, latitude,month,day,year,hour,min,sec,centisecs,alt,6 lux values
    17642, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
    17980, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
    18333, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
    18803, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,106,106,6,0,3,93,
    19131, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,33,33,6,0,3,0,
    19530, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,0,0,6,0,3,40,
    19956, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
    20311, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
    20787, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
    21114, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
    21504, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
    21942, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,
    22292, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,
...

    240540, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
    240869, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
    241249, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
    241697, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
    242035, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
    242531, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,109,109,6,0,3,106,
    242859, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
    243238, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
    243687, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    244016, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    244425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    244892, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    245260, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    245754, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    246083, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    246494, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
    246947, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,109,6,0,3,106,
    247320, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    247820, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,106,6,0,3,106,
    248160, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    248676, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    249027, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    249425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
    249889, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
    250253,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
    250768,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
    251097,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
    251608,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
    252021,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
    252412,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
    252883,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
    253248,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
    253765,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
    254094,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
    254608,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,109,6,0,3,106,
    255020,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
    255412,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
    255882,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,

Here is the sketch:

    ////
    //initialising constants
    static const  int out_min = 5;
    static const  int out_max = 10;
    static
    const uint8_t RXPin = 0,
                  TXPin = 1;
    static
    const uint16_t GPSBaud = 9600;
    static
    const uint16_t chipSelect = 4;
    //initialising Objects
    SoftwareSerial ss(RXPin, TXPin);
    TinyGPSPlus gps;

    BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
    BH1750 inactive_sensor(0x5C);
    SdFat sd;
    SdFile file;

    //initialising variables for collecting data
    float lng_;
    float lat_;

    String month_ = "";
    String day_ = "";
    String year_ = "";

    uint16_t lux_ = 0;
    uint8_t hour_ = 0;
    uint8_t min_ = 0;
    uint8_t second_ = 0;
    uint8_t centisecond_ = 0;
    float altitude_ = 0;

    unsigned long runtime_ = 0;

    uint16_t values[6];
    char buf[6];
    char data_buffer[12];
    char fileName[13] = FILE_BASE_NAME "00.csv";
    uint8_t lines = 0;

    void setup() {
      digitalWrite(2, HIGH);
      pinMode(2, INPUT);
      Serial.begin(115200);
      Wire.begin();

      pinMode(3, OUTPUT);
      digitalWrite(3, LOW);

      for (int i = out_min; i <= out_max; i++)
      {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
      }

      ss.begin(GPSBaud);

      if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
       Serial.println(F("BH1750 Advanced begin"));
      } else {
        Serial.println(F("Error initialising BH1750"));
      }
    }

    void(* resetFunc) (void) = 0;
    void loop() {

      while (ss.available() > 0)
        if (gps.encode(ss.read())) {
          digitalWrite(3, HIGH);
        }
      if (millis() > 5000 && gps.charsProcessed() < 10) {
        while (true);
      }
      if (gps.location.isValid()) {
        lat_ = gps.location.lat();
        lng_ = gps.location.lng();
      }

      if (gps.date.isValid()) {
        day_ = gps.date.day();
        month_ = gps.date.month();
        year_ = gps.date.year();
      }

      if (gps.time.isValid()) {
        hour_ = gps.time.hour();
        min_ = gps.time.minute();
        second_ = gps.time.second();
        centisecond_ = gps.time.centisecond();
        altitude_ = gps.altitude.meters();
      }

      int i;
      for (i = 5; i <= 10; i++) {
        digitalWrite(i, LOW);
        switch (i) {
          case 7:
            active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
          case 8:
            active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
          case 9:
            active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
          case 10:
            active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
          case 5:
            active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
          case 6:
            active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
        }
        delay(15);
        lux_ = active_sensor.readLightLevel();
        values[i - 5] = lux_;
        digitalWrite(i, HIGH);
      }
      delay(10);
      digitalWrite(3, LOW);
      delay(5);
      file.print(millis());
      file.write(',');
      dtostrf(lng_, 9, 6, data_buffer);
      file.print(data_buffer);
      file.write(',');
      dtostrf(lat_, 9, 6, data_buffer);
      file.print(data_buffer);
      file.write(',');

      file.print(month_);
      file.write(',');
      file.print(day_);
      file.write(',');
      file.print(year_);
      file.write(',');

      file.print(hour_);
      file.write(',');
      file.print(min_);
      file.write(',');
      file.print(second_);
      file.write(',');
      file.print(centisecond_);
      file.write(',');
      file.print(altitude_);
      file.write(',');

      for (int i = 0; i <= 5; i++) {
        file.print(values[i]);
        file.write(',');
      }
      file.println();
      lines++;

      int state = digitalRead(2);

    }

Example Output:

title: Neo 6M GPS Module does not work properly inside own sketch

Answers: 1

body:
You can't (and certainly *shouldn't* ever even try to) use SoftwareSerial on pins 0 and 1. Not when you're using `Serial`, since they are the same pins.

Pick a different pair of pins for your GPS connection.


body:
I am working on a web app to program some nodeMCU devices that were flashed with the arduinoOTA library.

http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html

I tried the example and the OTA upload of the binary file compiled from Arduino IDE works.

Let's say my web app will allow user to code in Sketch, is there any open source server side or client side compiler that can compile the Sketch code into the bin file?

title: Is there an open source compiler for Arduino Sketch codes?

Answers: 3

body:
Arduino IDE runs external tools to create the hex or bin file. First the ino files of a project are processed by [arduino builder][1] to cpp file. Then the arduino builder invokes the toolchain of the MCU architecture - compiler and linker. For example AVR tools for 328p or 2560; ARM toolchain from SAMD; xtensa tools for Espressif chips.

New is [Arduino CLI][2], which focuses on using Arduino with command line.

Tha Arduino builder, Arduino CLI and esp8266 Arduino core are Open Source. Extensa tools and Espressif SDK are not open source, but are free.

  [1]: https://github.com/arduino/arduino-builder
  [2]: https://github.com/arduino/arduino-cli

body:
Try PlatformIO: https://platformio.org

Opensource and cross platform.

body:
Just have a look here https://github.com/arduino/Arduino/wiki/Build-Process to understand the process.

In fact Arduino code is not "C or C++" at 100%. You can't compile directy as some informations are missing.
This is why when you "compile" with the IDE, it copies the files in a temp folder, add some lines at beginning of theses files and then call the basic and well known avr-gcc.
If you have a dedicated server you just have to search for the avr-gcc package according to the OS.
Eg, for Debian: https://packages.debian.org/stretch/gcc-avr

Then or you send directly the code avr-gcc is waitng for, or you apply on the code the same changes the IDE is doing before sending the code to GCC.

Hope this help


body:
I am creating a standalone Arduino using Atmega328P. The circuit is below.

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

However, I'm seeing

    avrdude: Device signature = 0x000000 error

whenever I try to burn the Arduino Uno bootloader. I'm assuming that the chip isn't responding to the SPI lines?

I know I'm doing something wrong but I can't see it.

My connections are

    SCLK --> Arduino Pin 13
    MISO --> Arduino Pin 12
    MOSI --> Arduino Pin 11
    Reset --> Arduino Pin 10

    VIN --> 5V
    GND --> GND

I'm using a true Arduino UNO as the ISP. I've uploaded the ArduinoISP code into it, choose Arduino as ISP as Programmer and Arduino Uno on boards. The programming connections are just wired from Arduino UNO pins to some vias I've purposely added on the layout.

As mentioned in the comments, I'm adding an image of the layout here.

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

I've tried this very circuit on an atmega328P soldered in a TQFP adapter and with the other components soldered on the adapter as well (looks like a jungle of wires) and somehow I was able to burn the bootloader.

Hoping someone can point out what's wrong.

  [1]: https://i.stack.imgur.com/2NQPO.png
  [2]: https://i.stack.imgur.com/7kEI2.png

title: Standalone 328P Arduino

Answers: 2

body:
From the schematic it appears you are using a LM317 voltage regulator from USB V_IN.  The voltage drop is too large and your issues may be due to brown out, i.e. insufficient voltage:  See [this SE post][1].  You can solve it by using a lower dropout regulator (5 V to 3.3 V) or just use the standard USB 5 V, bypass V_IN to V_CC.

  [1]: https://electronics.stackexchange.com/questions/214371/lm317-dropout-voltage

body:
It seems that you are using a lm317 voltage regulator to power your atmega328p MCU but I think you forgot the part that lm317 needs feedback of 1.25v with voltage divider network to set its variable output voltage in the schematic you have connected adj pin of  lm317 directly to GND.
S0 check your output vtg from your regulator and another issue voltage regulator only works great when difference between regulating voltage is lower then the supply voltage.


body:
I have to port a Project written for an Arduino Micro to an MKRZERO.

It communicates via UART with an IC and should also provide a clock signal.

The former code I have used is this:

    #define OUTPUTPIN 8
    #define CLOCKOUTPIN 5
    #define CONTRLEDPIN 13

    void Setup() {
    pinMode(OUTPUTPIN, OUTPUT);
    // Needed for initialization
    digitalWrite(OUTPUTPIN, HIGH);
    // set clock PIN
    pinMode(CLOCKOUTPIN, OUTPUT);
    // sets PIN for internal LED
    pinMode(CONTRLEDPIN, OUTPUT);

    TCCR3A = (1 << COM3A0);
    TCCR3B = ((1 << WGM32) | (1 << CS30));
    TIMSK3 = 0;
    OCR3A = 7;
    }

As the MKRZERO uses a different IC the registers are not the same. I've waded through the data sheet document but cannot find something similar.

Does somebody have any experience with the MKRZERO and can help me with this?

title: Output clock signal on MKRZERO

Answers: 1

body: The IC on the MKRZERO is an Atmel SAMD21.  Look up the [datasheet](http://ww1.microchip.com/downloads/en/devicedoc/40001882a.pdf) and read the section on timer counter.  Yes, it's a long document, but you will find all of the information there.


body:
I'm trying to upload this code and it works properly but I can't see anything on my serial plotter

    const int AnalogIn_Pin0=  A0;
    const int AnalogIn_Pin1=A1;
    const int Pwmout_PIN=11;
    float AnalogIn_Val0=0;
    float AnalogIn_Val1=0;
    int Pwmout_Val=0;
    float Error=0;
    float ErrorInteg=0;
    float Control=0;
    float ControlFilt=0;
    float kp=0.2;
    float Pole =-10;
    float Ki =0.01;
    int deltaT=0.01;
    int deltaT_ms=(int)deltaT*1000;

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

    void loop() {
      AnalogIn_Val0=(float)constrain (analogRead(AnalogIn_Pin0),0,600);
      AnalogIn_Val1=0.97*AnalogIn_Val1+0.03*(float)analogRead(AnalogIn_Pin1);
      Error= (AnalogIn_Val0-AnalogIn_Val1);
      ErrorInteg=ErrorInteg+Error*deltaT;
      ControlFilt=kp*Error+Ki *ErrorInteg;
      Pwmout_Val= constrain (map ((int)ControlFilt,0,1023,0,255),0,220);
     analogWrite (Pwmout_PIN,Pwmout_Val);
     Serial.print(AnalogIn_Val0);
     Serial.print("");
     Serial.print(AnalogIn_Val1);
     Serial.print("");
     Serial.print( Pwmout_Val);
     delay (deltaT_ms);

    }

title: My Serial plotter isn't working (arduino)

Answers: 1

body:
You must have each set of data point (or points) on a separate line and if you are plotting more that one value you need a space or a tab between each value.

So to have 3 lines on your plot, I think you want this:

     Serial.print(AnalogIn_Val0);
     Serial.print(' ');
     Serial.print(AnalogIn_Val1);
     Serial.print(' ');
     Serial.println(Pwmout_Val);

The output in the serial monitor should be something like this:

    123 456 789
    234 567 901
    ...


body:
I am currently running a project with 2 TinyDuinos and 2 TinyShields 433MHz Radio (SI4432) in order to pass 3 axes (x , y ,z) from one to the other from long distance.

I have tried

 - to concat the axes as one string and send the string,
 - to send an array like `string axes = { x , y , z }` to the
   receiver (of course the variables are already defined),
 - send only one string. In this case I have only the first 2 letters of the string. For example if the string was `string first = "456"` , I would get `"45"` on the receiver

The Radio shield's examples uses uint8_t type and arrays to send and receive the data, I have already tried to cast the string to char* and then to uint8_t and nothing different happens. Maybe I am missing something.

Below there are my code screen shots. I will put 2 links for the examples of the transmitter and the receiver I got some code from

Similar Project : [https://tinycircuits.com/blogs/learn/121634375-football-play-calling-watch-tutorial][1]

Radio Shield Page: [https://tinycircuits.com/products/433mhz-long-range-radio-tinyshield][2]

TinyDuino Main Shield : [https://tinycircuits.com/collections/all/products/tinyduino-processor-board][3]
## Code Screenshots ##

[![Transmitter code][4]][4]

[![Receiver code][5]][5]

[![Output from Receiver][6]][6]

  [1]: https://tinycircuits.com/blogs/learn/121634375-football-play-calling-watch-tutorial
  [2]: https://tinycircuits.com/products/433mhz-long-range-radio-tinyshield
  [3]: https://tinycircuits.com/collections/all/products/tinyduino-processor-board
  [4]: https://i.stack.imgur.com/ytxxR.png
  [5]: https://i.stack.imgur.com/QxMek.png
  [6]: https://i.stack.imgur.com/mzrXA.png

title: TinyDuino radio connection

Answers: 1

body:
For this kind of thing you need to craft a packet to contain your data. The best method is to use a *struct*.

    struct coords {
        int x;
        int y;
        int z;
    };

Then you can define a variable from it:

    struct coords myCoords;

And set individual values:

    myCoords.x = 23;
    myCoords.y = 180;
    myCoords.z = -3817;

Now you can cast it to whatever type you need for sending:

    manager.sendtoWait((uint8_t *)&myCoords, sizeof(struct coords), SERVER_ADDRESS);

Receiving is done in much the same way:

    struct coords recCoords;
    uint8_t len = sizeof(struct coords);
    uint8_t from;

    if (manager.recvfromAck((uint8_t *)&recCoords, &len, &from)) {
        Serial.print("X = ");
        Serial.println(recCoords.x);
        Serial.print("Y = ");
        Serial.println(recCoords.y);
        Serial.print("Z = ");
        Serial.println(recCoords.z);
    }

----

In future please *post your actual code*, not pictures of your code. It makes it a real pain having to keep scrolling up and manually typing in bits of your code rather than being able to copy-and-paste a couple of lines.


body:
I got an SD card breakout from an online shop, its the iteed kind without the level shifter, it has the 3.3 / 5 V switch. I cannot find any libraries or write example for it.

Has anyone dealt with it before with Arduino? I have tried finding info but I only get the level shifter kind that has the MOSI pins!

[enter image description here](https://i.stack.imgur.com/pdK9S.jpg)

title: Iteed SD card breakout info for Arduino

Answers: 3

body:
So, a quick google for "Itead SD card breakout" comes up with [their website/wiki][1] where there is a schematic.  Can't believe you did not try this.  It is just that - a breakout board.  It will allow you to connect Arduino to an SD card.  You can look up any generic example for SD + Arduino on the web.

They explicitly say

>  It can work with 5V or 3.3V power supply, and both 5V/3.3V IO operation level. It can be controlled directly by a wide range of microcontrollers such as Arduino, AVR, PIC, ARM and MSP430.

  [1]: https://www.itead.cc/sd-micro-sd-card-breakout-module.html

body:
Use standard Arduino SD library or the SdFat library. All SD card 'modules' are only a holder and eventually level converters. The SPI device is the SD card itself.

Set the SD adapter to the voltage of your board, connect it to power and SPI bus, choose some pin as SS pin, insert SD card and it must work.

Pins: MISO is master in slave out, MOSI is master out slave in. DO is data out, DI is data in. SD card is slave, so MISO to DO and MOSI to DI

body:
Alrighty, For anyone else struggling with this in the future.
Using arduino mega and iteed sd breakout withoit level shifter
G-Ground
DO-50
CLK-52
DI-51
CS-53
+-5V
then in the code before setup specify chip select to 53
Thanks for all the help.


body:
I am HTTP posting a data to this web API https://morning-cliffs-85779.herokuapp.com/api/users from an **Arduino connected to esp8226**. I am using the **wifiesp library** to HTTP_POST data.

The REST APIs are hosted in **Heroku**.

When I post it the Arduino gives the response

> Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting  3

and the Heroku server gives the response

> at=error code=H13 desc="Connection closed without response"

Below is the Arduino code:

      if (client.connect(server, 80)) {
        Serial.println("Connected to server");
        // Make a HTTP request
        String content = "id=5bc58842bdfea0153bb27214&volt=7";
        client.println("POST /api/users HTTP/1.1");
        client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
        client.println("Accept: */*");
        client.println("Content-Length: " + content.length());
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.println();
        client.println(content);
      }

This is the Node Express API:

    app.post('/api/users', function (req, res) {

    console.log('here');

    if (req.body.id) {
        DevReading.findByIdAndUpdate(req.body.id, {
            volt: req.body.volt
        }, function (err, reading) {
            if (err) throw err;

            res.send('Update Success');
        });
    }

    else {

    var newDevReading = DevReading ({
        deviceName: 'test',
        volt: req.body.volt
    });

    newDevReading.save(function (err) {
        if (err) throw err;
        res.send('Reading Post Success');
    });
    }

    });

title: How to HTTP post a data to Node express API from a Arduino esp8226?

Answers: 1

body:
Did it heres the code

    `if (client.connectSSL(server, 443)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String PostData = content + volt;
    Serial.println(PostData);
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com");
    client.println("Cache-Control: no-cache");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(PostData.length());
    client.println();
    client.println(PostData);
    }`

Hope it helps some one


body:
If I understand correctly using the [`Adafruit_Sensor`](https://github.com/adafruit/Adafruit_Sensor) one can extract information from the sensor specific information. These sensors are currently mentioned in the `README`. I am using the BNO055 for two things:

1. Orientation values (Heading, pitch, roll)
2. Linear Acceleration values

My code is similar to the Example mentioned [Adafruit_BNO055's bunny](https://github.com/adafruit/Adafruit_BNO055/blob/master/examples/bunny/bunny.ino)

### Code

I tried the following in my `loop()`

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

    void loop() {
      // put your main code here, to run repeatedly:
      sensors_event_t event;
      bno.getEvent(&event);

      Serial.print(F("Orientation: "));
      Serial.print((float)event.orientation.x);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.y);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.z);
      Serial.println(F(""));

      Serial.print(F("Acceleration: "));
      Serial.print((float)event.acceleration.x);
      Serial.print(F(" "));
      Serial.print((float)event.acceleration.y);
      Serial.print(F(" "));
      Serial.print((float)event.acceleration.z);
      Serial.println(F(""));

      delay(BNO055_SAMPLERATE_DELAY_MS);
    }

Created `sensors_event_t event` and used the `orientation` and `acceleration` parameters to obtain the orientation and acceleration values in x, y, z directions.

### output
The orientation and accleration values are the same:

    Orientation: 105.50 -20.56 -101.00
    Acceleration: 105.50 -20.56 -101.00
    Orientation: 97.81 -14.69 -119.56
    Acceleration: 97.81 -14.69 -119.56
    Orientation: 93.81 -10.94 -125.56
    Acceleration: 93.81 -10.94 -125.56
    Orientation: 94.44 -12.25 -122.56

I tried adding another event `event1` in the `loop()` but I still get the same results

    sensors_event_t event;
      bno.getEvent(&event);

      Serial.print(F("Orientation: "));
      Serial.print((float)event.orientation.x);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.y);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.z);
      Serial.println(F(""));

      sensors_event_t event1;
      bno.getEvent(&event1);
      Serial.print(F("Acceleration: "));
      Serial.print((float)event1.acceleration.x);
      Serial.print(F(" "));
      Serial.print((float)event1.acceleration.y);
      Serial.print(F(" "));
      Serial.print((float)event1.acceleration.z);
      Serial.println(F(""));

      delay(BNO055_SAMPLERATE_DELAY_MS);

Can't the BNO055 along with the Adafruit_Sensor library not provide the acceleration and orientation values as events or is the library used only to obtain orientation values from the BNO055?

title: Get accelerometer values from BNO055 using adafruit's Unified Sensor Library

Answers: 2

body:
You must set the operation mode from [adafruit_bno055_opmode_t][1] enum. Use `bno.setMode`.

For modes see section 3.3 in [the datasheet][2].

The `sensors_event_t` is an union struct so the same memory is accessed with different member names.

  [1]: https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.h
  [2]: https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST_BNO055_DS000_14.pdf

body:
## Findings

If I use the same `sensors_event_t` in the code and use `event.acceleration` and `event.orientation` within the `loop()` and they provide me exactly the same values. I in fact get the same values for heading, pitch, roll and acceleration in x, y, z direction.

    sensors_event_t event;
      bno.getEvent(&event);

      Serial.print(F("Orientation: "));
      Serial.print((float)event.orientation.heading);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.pitch);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.roll);
      Serial.println(F(""));
     Serial.print((float)event.acceleration.x); // same as roll
     Serial.println(F(""));
     Serial.print((float)event.acceleration.y); // same as pitch
     Serial.println(F(""));
     Serial.print((float)event.acceleration.z); // same as heading
     Serial.println(F(""));

## Sensor

I have a __Blue Dot__ BNO055 sensor and it has marking on it for X, Y, Z directions as follows:
[![Orientation on Sensor][1]][1]

I crossed checked with the logic of [Euler Angles from Wikipedia](https://en.wikipedia.org/wiki/Euler_angles#/media/File:Yaw_Axis_Corrected.svg)

If i rotate along the x Axis, I do in fact get roll (0 to 360) and so on.

## Inference

The `Adafruit_Sensor` library provides only orientation values when used with BNO055 and Linear acceleration values need to be called separately using the __Adafruit_BNO055__.

### code for Linear Acceleration and orientation

      sensors_event_t event;
      bno.getEvent(&event);

      Serial.print(F("Orientation: "));
      Serial.print((float)event.orientation.heading);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.pitch);
      Serial.print(F(" "));
      Serial.print((float)event.orientation.roll);
      Serial.println(F(""));
    //  Serial.print((float)event.acceleration.x); // same as roll
    //  Serial.println(F(""));
    //  Serial.print((float)event.acceleration.y); // same as pitch
    //  Serial.println(F(""));
    //  Serial.print((float)event.acceleration.z); // same as heading
    //  Serial.println(F(""));

      imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
      Serial.print(F("Li. Acc.: "));
      Serial.print((float)li_ac.x());
      Serial.print(F(" "));

      Serial.print((float)li_ac.y());
      Serial.print(F(" "));

      Serial.print((float)li_ac.z());
      Serial.print(F(" "));
      Serial.println();

      delay(BNO055_SAMPLERATE_DELAY_MS);

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


body:
Is it possible using an arduino to control more than 4 PWM fan at 25khz ?

I have found this but 4 PWM limited with an UNO

https://arduino.stackovernet.com/fr/q/8407

An other arduino, like a 2560 could be used ?

Thanks
Best regards
Sébastien

title: More than 4 PWM output at 25khz?

Answers: 1

body:
Indeed you could use a Mega. See [this answer][timer1]: it explains how
you can use Timer 1 on an Uno to provide two PWM channels at
25 kHz. This is the only 16-bit timer on that board. The Mega, on
the other hand, has four 16-bit timers: Timers 1, 3, 4 and 5. These
timers are almost identical to the Uno's Timer 1, except that they
provide 3 PWM channels each. So you have potentially up to
12 PWM channels that you can run at 25 kHz.

Now, look at this [pinout diagram][mega]. Every pin labeled `OCnx`,
where `n` is either 1, 3, 4 or 5, and `x` is a letter, is a 16-bit PWM
output. Just take the code from the answer I linked to and adapt it to
the Mega. You configure all those timers in the same way, and you set
the duty cycle for pin `OC3B` by writing to the register `OCR3B` (and so
on...).

[timer1]: https://arduino.stackexchange.com/a/25623
[mega]: http://forum.arduino.cc/index.php?action=dlattach;topic=146511.0;attach=90705


body: What is the least value of time that I could measure(count) using `micros()`?

title: What is the smallest duration that can be measured using micros()?

Answers: 1

body:
> What is the least value of time that I could measure(count) using micro() in Arduino board?

The answer is 64 clock cycles or 4 us @ 16 MHz. Please see the Arduino AVR core[1] for more details.

Cheers!

Ref. [1] https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L25