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

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

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

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

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

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

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

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

title: Float division returns "inf" and 0

Answers: 1

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

    recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and

    recieved = recieved * 1000000.0;

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

    speed_of_sound = (2*target_distance)/recieved;

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

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

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

The solution is to compute `received` as

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

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


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

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

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

title: ESP8266 official library post request returns 400

Answers: 1

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

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

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


body:
**Update**: I realized my relay module was 12V and the current leaving the digitalpin from my Wemos D1R1 is only 3.3V. I bought a 5V relay module that I read in some articles that it could work, but it didn't.

**My new question is**: is there an easy and simple way to amplify the voltage leaving the D5 pin so it could control the 12V or the 5V relay module? I tried using and logic level converter from 3.3V to 5V but had no success. Ideas?

-------------------------

I am having issues with a simple project using Wemos D1 and a relay board. I followed a tutorial that was supposed to work out fine (https://www.instructables.com/id/Control-a-Lamp-With-ESP8266-and-a-Relay/), but for some reason I still don't know it is not working.

I read that it could be that the D5 pin has not enough energy to trigger the relay and change its state. So I tried using a logic level converter and still it didn't work.

I am attaching the image of my board/connections and also the logic level converter (https://br.banggood.com/3_3V-5V-TTL-Bi-directional-Logic-Level-Converter-For-Arduino-p-949438.html), plus my code below.
<!-- language-all: lang-cpp -->

    void setup() {
      // put your setup code here, to run once:
        Serial.begin(115200);

    }

    void loop() {
      digitalWrite(5, HIGH);
      Serial.println("HIGH");
      delay(3000);
      digitalWrite(5, LOW);
      Serial.println("LOW");
      delay(3000);
    }

[![my circuit][1]][1]

Does anyone have any idea of what could be happening? And how to make it work?

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

title: Wemos D1 is not triggering Relay

Answers: 0


body:
I'm trying to set up a HTTP and HTTPS server at the same time on an ESP8266 NodeMCU V3. The compiler however doesn't accept any other name than `client` otherwise no new clients will be catched. But `client` cannot be used twice and I cannot get it to switch every loop because of the different data-type; `WiFiClient` and `WiFiClientSecure`.

Is what I'm trying to accomplish even possible?

`Sketch.ino`
<!-- language-all: lang-cpp -->

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_HTTPPORT  = 80;
    const int   CONFIG_HTTPSPORT = 443;

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

    // Include libraries
    #include <ESP8266WiFi.h>

    // Create webserver object
    WiFiServer HTTPserver(CONFIG_HTTPPORT);
    WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
    static const uint8_t rsakey[] PROGMEM = {
      #include "key.h"
    };
    static const uint8_t x509[] PROGMEM = {
      #include "x509.h"
    };

    // Setup instructions
    void setup() {

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

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

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

      // Print WiFi connection information
      Serial.print("  MAC Address: ");
      Serial.println(WiFi.macAddress());
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  IP Address: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Gateway: ");
      Serial.println(WiFi.gatewayIP());

      // Start webserver
      Serial.println("Starting webserver...");
      HTTPserver.begin();
      HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
      HTTPSserver.begin();
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Hostname: ");
      Serial.println(WiFi.hostname());
      Serial.print("  HTTP Port: ");
      Serial.println(CONFIG_HTTPPORT);
      Serial.print("  HTTPS Port: ");
      Serial.println(CONFIG_HTTPSPORT);

    }

    // Loop instructions
    void loop() {

      // Wait for new client
      WiFiClient HTTPclient = HTTPserver.available();
      WiFiClientSecure HTTPSclient = HTTPSserver.available();
      if (HTTPclient || HTTPSclient) {
      }

    }

**UPDATE (2019-06-05):**

I've tried @KIIV's method which works! However it brings a new problem into the equation. HTTPS requests take pretty long te complete, currently about 2 seconds. And it makes the HTTPS request twice for some reason (see log; I made only one request after setup).

`Sketch-updated.ino`
<!-- language-all: lang-cpp -->

    // Configuration
    const char* CONFIG_SSID      = "mywifi";
    const char* CONFIG_PSK       = "wifipassword";
    const int   CONFIG_SERIAL    = 115200;
    const int   CONFIG_HTTPPORT  = 80;
    const int   CONFIG_HTTPSPORT = 443;

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

    // Include libraries
    #include <ESP8266WiFi.h>

    // Create webserver object
    WiFiServer HTTPserver(CONFIG_HTTPPORT);
    WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
    static const uint8_t rsakey[] PROGMEM = {
      #include "key.h"
    };
    static const uint8_t x509[] PROGMEM = {
      #include "x509.h"
    };

    // Setup instructions
    void setup() {

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

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

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

      // Print WiFi connection information
      Serial.print("  MAC Address: ");
      Serial.println(WiFi.macAddress());
      Serial.print("  SSID: ");
      Serial.println(WiFi.SSID());
      Serial.print("  RSSI: ");
      Serial.print(WiFi.RSSI());
      Serial.println(" dBm");
      Serial.print("  IP Address: ");
      Serial.println(WiFi.localIP());
      Serial.print("  Gateway: ");
      Serial.println(WiFi.gatewayIP());

      // Start webserver
      Serial.println("Starting webserver...");
      HTTPserver.begin();
      HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
      HTTPSserver.begin();
      Serial.println("Webserver started!");

      // Print webserver information
      Serial.print("  Hostname: ");
      Serial.println(WiFi.hostname());
      Serial.print("  HTTP Port: ");
      Serial.println(CONFIG_HTTPPORT);
      Serial.print("  HTTPS Port: ");
      Serial.println(CONFIG_HTTPSPORT);

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

    }

    // Loop instructions
    void loop() {

      // New wait for new client
      if (HTTPserver.hasClient()) {

        // Set client to HTTP for this loop
        //auto client = HTTPserver.available();
        WiFiClient client = HTTPserver.available();

        // Response
        Serial.println("This is HTTP");
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/plain");
        client.println("Connection: close");
        client.println();
        client.println("This is HTTP");

      } else if (HTTPSserver.hasClient()) {

        // Set client to HTTP for this loop
        //auto client = HTTPSserver.available();
        WiFiClientSecure client = HTTPSserver.available();

        // Response
        Serial.println("This is HTTP Secure");
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/plain");
        client.println("Connection: close");
        client.println();
        client.println("This is HTTP Secure");

      }

    }

`Serial Log`

    15:59:34.121 -> Starting setup
    15:59:34.121 -> Connecting to: mywifi
    15:59:34.452 -> .............
    15:59:38.205 -> WiFi connected!
    15:59:38.205 ->   MAC Address: XX:XX:XX:XX:XX:XX
    15:59:38.238 ->   SSID: mywifi
    15:59:38.238 ->   RSSI: -21 dBm
    15:59:38.238 ->   IP Address: 192.168.1.121
    15:59:38.238 ->   Gateway: 192.168.1.1
    15:59:38.238 -> Starting webserver...
    15:59:38.238 -> Webserver started!
    15:59:38.238 ->   Hostname: ESP_XXXXXX
    15:59:38.238 ->   HTTP Port: 80
    15:59:38.238 ->   HTTPS Port: 443
    15:59:38.271 -> Setup completed
    15:59:38.271 ->
    16:00:38.069 -> This is HTTP Secure
    16:00:38.833 -> This is HTTP Secure

title: HTTP and HTTPS server at the same time

Answers: 0


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

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

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

Answers: 2

body:
**Arduino Uno**

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

**External power**

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

**Wires**

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

**Safety**

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

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

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


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

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

title: OTA push sketch to NodeMCU

Answers: 2

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

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

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


body:
This is the question from the homework I'm doing "Design and implement a state machine with a single button to turn on and off two LEDs The first LED should be turned on and off with a quick press of the button, the second LED should turn on and off with a long press (1 second)."

I have this code

    int state_s1 = 0;
    int state_s2 = 0;
    int state_s3 = 0;
    int state_s4 = 0;
    int state_prev_s1 =0;
    int ledPin2 = 8;
    int ledPin = 9;
    int boton = 10;
    int boton2 = 11;
    int val_s1 = 0;
    unsigned long t_0_s1 = 0;
    unsigned long t_s1 = 0;
    unsigned long t_s2 = 0;
    unsigned long tiempo = 50;
    unsigned long bounce_delay_s1 = 5;
    unsigned long bounce_delay_s2 = 1000;
    boolean prendido = false;
    boolean prendidoP = false;

    void setup()
    {
      pinMode(boton, INPUT_PULLUP);
      pinMode(boton2, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      Serial.begin(9600);

    }

    void loop()
    {

      SM_s1();

      if(prendido == true)
      {
        led();
      }

      if(prendidoP == true)
      {
        led2();
      }

       Serial.print("state 1 =");
       Serial.println(state_s1);

       Serial.println("************");

    }

    void led()
    {

      switch(state_s1)
      {
        case 0:         //OFF
        digitalWrite(ledPin, LOW);
        t_0_s1 = millis();
        state_s1 = 1;
        break;

        case 1:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= tiempo)
        {
          state_s1 = 2;
        }
        break;

        case 2:         // ON
        digitalWrite(ledPin, HIGH);
        t_0_s1 = millis();
        state_s1 = 3;
        break;

        case 3:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= tiempo)
        {
         state_s1 = 0;
        }
        break;

      }
    }

    void led2()
    {

      switch(state_s4)
      {
        case 0:         //OFF
        digitalWrite(ledPin2, LOW);
        t_0_s1 = millis();
        state_s4 = 1;
        break;

        case 1:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= tiempo)
        {
          state_s4 = 2;
        }
        break;

        case 2:         // ON
        digitalWrite(ledPin2, HIGH);
        t_0_s1 = millis();
        state_s4 = 3;
        break;

        case 3:         //WAIT
        t_s1 = millis();
        if(t_s1 - t_0_s1 >= tiempo)
        {
         state_s4 = 0;
        }
        break;

      }
    }

     void SM_s1()
     {
      switch(state_s2)
      {
        case 0:         //RESET
        state_s2 = 1;
        break;

        case 1:        //START
        val_s1 = digitalRead(boton);
        if(val_s1 == LOW)
         {
          state_s2 = 2;
         }
        break;

        case 2:         // GO!
        t_0_s1 = millis();
        state_s2 = 3;
        break;

        case 3:         //WAIT
       if(val_s1 == HIGH)
         {
          state_s2 = 0;
         }

        t_s1 = millis();

        if(t_s1 - t_0_s1 >= bounce_delay_s1)
        {
          state_s2 = 5;
        }
        break;

        case 5:         //ARMED & WAIT
        t_s2 = millis();
        val_s1 = digitalRead(boton);
        if(val_s1 == HIGH && t_s2-t_s1 < bounce_delay_s2)
         {
          state_s2 = 4;
         }

         if(t_s2-t_s1 >= bounce_delay_s2)
         {
          state_s2= 6;
         }

        break;

        case 4:       //TRIGGERED
        state_s2 = 0;
        prendido = not prendido;
        break;

        case 6:     // ARMED 2
        state_s2 = 0;
        prendidoP = not prendidoP;
        break;

    }
    }

It will work the first time but then the LEDs won't turn off and sometimes when the button is pressed hard, it will turn both LEDs on, please help me.

title: LED doesn't turn on as specified on code State Machine

Answers: 0


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

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

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

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

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

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

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

Answers: 1

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

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

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

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

      led_on = (led_on + 1) % 4;
    }

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

    (led_on == 0) ? HIGH : LOW

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

    led_on = (led_on + 1) % 4;

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

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

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

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


body:
I am trying to use avrdude with a Mega2560 running ArduinoISP

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

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

I have a couple of tasks I want to do

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

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

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

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

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

I tried using the command:

    avrdude -c arduino -p m8 -P COM8

I get the error

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

    avrdude done.  Thank you.

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

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

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

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

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

Answers: 1

body:
The target board was not reset.

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

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

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

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

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

>Is this all documented somewhere?

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

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


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

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

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

    void loop()
    {

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

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

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

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

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

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

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

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

The following is the code for SW-420 Sensor:

    int LED_Pin = 13;
    int vibr_Pin =3;

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

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

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

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

Answers: 1

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

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

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

"What about `<thing 3>`"

And repeats.

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


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

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

----------

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

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

    #include <ModbusMaster.h>
    #define MAX485_TX_ENABLE  12

    int myInts[6];
    ModbusMaster node;

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

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

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

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

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

title: NodeMCU Modbus interfacing with Pressure Multi-Switch

Answers: 1

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

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

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

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


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

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

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

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

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

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

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

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

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

title: LED blinking issue

Answers: 1

body:
This is your code without unnecessary brackets:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

or do it the other way around:

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

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

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


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

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

Answers: 1

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

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

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

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

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

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

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


body:
I currently have a project that uses a few Xbee S1 modules to report temperature measurements to a computer. I'm thinking about reworking the project to use the newer Arduino Uno WiFi R2 boards.

Is there an existing library that will allow me to create a mesh network for a number of Wifi R2's (about 20+)? I know there's a [Mesh Library for the ESP8266][1] I'd be curious if I could either use this library or if one exits for the native board

  [1]: https://github.com/PhracturedBlue/ESP8266MQTTMesh

title: Arduino Uno Wifi R2 Mesh Network

Answers: 0


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

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

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

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

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

title: Writing Data through Pin at certain frequency

Answers: 1

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

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

where the data bits come from the PC.

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

## Receiving the data

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

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

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

## Transmitting the data

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

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

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

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

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

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

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

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

        ; etc...

        rjmp loop

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

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

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


body:
I was posting a question but to be completely sure i did some more tweaking in the code and solved at least functionally my problem.

I decided to post it anyway to have suggestions for a better solution and / or help whoever has the same problem.

The project is a flowers watering application.
I set up an RTC connected with Arduino Nano using LEDs to simulate the operations, it works really well, no mistakes when RTC.readTime requests.

Once satisfied I replaced the LED with a relay to be connected to the pump, and then the problem appeared:

Randomly the reading is not correct, something like (YYYY/MM/DD H:M:S) represented as 165/0/165 0:165:0.
The combinations of 165 and 0s are completely random but only 165 and 0s are present.

My solution was to check after each reading if there was any 165s into the returned data, and if yes, read the time again. This was the medicine.
This mistake appears only and always when i replace the LED with a relay, with or without connected charge.

Circuitry is very simple as well as is the code.

```c
  RTC.readTime();
  if (RTC.h == 165 ||
      RTC.m == 165 ||
      RTC.s == 165 ||
      RTC.dd == 165 ||
      RTC.mm == 165 ||
      RTC.yyyy == 165 ) {
        RTC.readTime();
        Serial.print("Mistake found in step N. ");
        Serial.println(countCycles);
  }

  countCycles ++;
```

From the printout I can confirm that the mistake is absolutely random but never immediately subsequent to another mistake.
Any clues?
Thank you for any comments

title: RTC 1307 when connected to a relay via Arduino Nano

Answers: 0


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

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

Here my arduino code,

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

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

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

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

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

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

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

title: Python Arduino Serial Communication Speed

Answers: 1

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


body:
I have 4 gyro sensors that communicate to arduino uno using I2C and then arduino uno sends the data to arduino mega.
I was wondering if I could use i2c for this purpose or if I should look for other methods.
gyro sensor used in the project:
https://www.pololu.com/product/2129/resources

title: I2C between two arduinos

Answers: 0


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

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

I'm trying to drive 2 DC motors.

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

title: Is there an Arduino motor shield library?

Answers: 1

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

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

    void setup() {

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

    }

    void loop(){

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

      delay(3000);

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

[From here][2].

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


body: I want to set it up on a mobile hotspot but I'd like to get an idea of how much data my sketch uses first.

title: Is there something I can add to my ESP8266 script to track how much data it uses on WiFi?

Answers: 0


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

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

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

What should I try next?

title: Trouble with i2c on ESP8266

Answers: 1

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


body:
I have a power strip with a ESP8266 which is supposed to turn it on upon command from a OpenHAB server, or to stay on for a predefined time upon command from another ESP8266 (serverless).

The reason is that OpenHAB is used to directly control the strip, while the other master ESP8266 is powered on and off intermittently and periodically sends "refresh" commands to the slave, that will turn off when no more messages are received.

How should I handle the control of the ESP8266? I have never worked with master/slave and I'm confused by the number of available options. For example, MQTT seems a good choice when the server sends the control command, but it requires a software listening and relaying MQTT messages, therefore is not suitable as only control technique because the communication between ESP8266 must not rely on any further network device.

I also thought about simply controlling the slave ESP8266 via webpage and POST/GET commands, since OpenHAB can be set up to use this method as well and that would work also as direct control between ESP8266.

What are my options, their complexity and pros/cons?

title: How can I control a slave ESP8266 from a local server and also from another ESP8266?

Answers: 0


body:
From linux I can send a socket message using netcat

    echo "Hello" | nc 88.109.110.161 100

But I don't know how to setup the socket server for listening incoming messages using the ethernet shield.

What I have so far is one from a lot of examples I tried but still not showing anything

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    EthernetServer server(1000);

    void setup() {
      Ethernet.begin(mac);
      Serial.begin(9600);
    // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Ethernet cable is not connected.");
      }

      // start the server
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients
     EthernetClient client = server.available();
     if (client) {
       Serial.println("Client");
       // an http request ends with a blank line
       boolean currentLineIsBlank = true;
       while (client.connected()) {
         while(client.available()) {
           char c = client.read();
           // if you've gotten to the end of the line (received a newline
           // character) and the line is blank, the http request has ended,
           // so you can send a reply
           if (c == '\n' && currentLineIsBlank) {

    // Here is where the POST data is.
             while(client.available())
             {
                Serial.write(client.read());
                //Serial.println(c);
             }
             Serial.println();

             Serial.println("Sending response");
             // send a standard http response header
             //client.println("HTTP/1.0 200 OK");
             //client.println("Content-Type: text/html");
             //client.println();
             client.println("OK");
             client.stop();
           }
           else if (c == '\n') {
             // you're starting a new line
             currentLineIsBlank = true;
           }
           else if (c != '\r') {
             // you've gotten a character on the current line
             currentLineIsBlank = false;
           }
         }
       }
       Serial.println("Disconnected");
     }
    }

title: How to create a Arduino socket server to receive messages

Answers: 1

body:
I am learning to use the arduino library about sockets and I spent an hour detecting why your example was not working for me, I ended up noticing that you have one line wrong

    if (c = '\n' && currentLineIsBlank) {

should be:

    { if (c != '\n' && !currentLineIsBlank) {

And you still have an error you are missing a return character because you are not printing it in the second loop.

Anyway thanks for your contributions.


body:
I'm trying to use I2C to send and receive commands between an Arduino UNO R3 and an Arduino Mega R3, with a 3.5" TFT display connected to the Mega. I have verified that my display is fully functional without using I2C by running the MCUFRIEND_kbv graphics tests where they perform exactly as I expect, but when I try to use I2C in combination with the TFT shield, I run into an issue where the display goes completely white and does not change. Could this be caused by the I2C interrupting the tft functions causing it to fail? Any advice would be greatly appreciated!

Here is the i2c code on the mega:

    void sendInputs(){
      for(int i = 0; i < NUM_BUTTONS; i++){
        btnArr[i] = digitalRead(btnPinArr[i]);
        Wire.write(btnArr[i]);
      }
      digitalWrite(13, HIGH);
      p = ts.getPoint();
      digitalWrite(13, LOW);
      tsArr[0] = p.x;
      tsArr[1] = p.y;
      tsArr[2] = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
      for(int i = 0; i < NUM_TS_INPUTS; i++){
        Wire.write(tsArr[i]);
      }
    }

    void getDrawData(){
     graphicsBufferSize = Wire.read();
     for(int i = 0; i < graphicsBufferSize; i++){
        graphicsBuffer[i] = Wire.read();
     }
     drawGraphicsBuffer();
    }

Where drawGraphicsBuffer(); parses the array of ints into draw functions

The I2C code on the Arduino UNO is:

    void sendGraphics(){
         Wire.beginTransmission(slaveID);
          Wire.write(graphicsBufferSize);
          for(int i = 0; i < graphicsBufferSize; i++){
            Wire.write(graphicsBuffer[i]);
          }
          Wire.endTransmission();
          graphicsBufferSize = 0;
        }

    void getInputs(){
      Wire.requestFrom(8, NUM_BUTTONS + NUM_TS_INPUTS);
      for(int i = 0; i < NUM_BUTTONS; i++){
        btnArr[i] = Wire.read();
      }
      for(int i = 0; i < NUM_TS_INPUTS; i++){
        tsArr[i] = Wire.read();
      }
    }

    void loop(){
      getInputs();
      delay(1000);
      if(btnArr[0]){
        screen.addFillScreen(0);
      }
      if(btnArr[1]){
        screen.addCircle(50, 50, 50, 50);
      }
      screen.sendGraphics();
    }

Where the screen methods just populate the graphicsBuffer array to be sent to the Arduino mega.

Edit:  [Here is the exact screen I'm using][1]

  [1]: https://www.amazon.ca/gp/product/B077ZT7S38

title: Arduino 3.5" TFT Display going blank after sending data through I2C

Answers: 0


body:
I find trouble updating my firmware with esp8266 with following error message.

[espDownloader.py][line:351][ERROR]: Chip sync error: Failed to connect to ESP8266: Timed out waiting for packet header
[2019-06-04 07:53:16,009][ESP8266Loader_spi[1]][espDownloader.py][line:439][ERROR]: ESP8266 Chip sync error esp_sync_blocking.

I am unable to resolve even after a number of attempts.
Please help me resolve my issue. Thank you in advance.

title: Chip sync error while updating ATfirmware in esp8266

Answers: 0


body:
I'd like to start by saying that I have only been dabbling in electronics (not just Arduino) for about 3 days now.

I am trying to write a sketch which changes an RGB LED when a push switch is pressed.

There are 6 modes -

    0 = off
    1 = dim
    2 = mid brightness
    3 = full brightness
    4 = cycle through RGB colours
    5 = pause the colour cycle at the current colour

I have managed to get this working using the code below this explanation.
What I would like to know is this -
Since the LED only changes state when the button is pressed, is it possible to avoid the use of the main 'loop()' entirely?

Will work fine for modes 0, 1, 2 and 3, but the interrupt cannot fire until mode 4 has finished 1 entire colour cycle.

    /*
     * LED MODES
     * 0 = off
     * 1 = dim
     * 2 = mid
     * 3 = bright
     * 4 = colour cycle
     * 5 = colour select
     */
    volatile int ledMode = 0; // off
    const int maxLEDMode = 5;
    volatile bool buttonPressed = false;

    int rPin = 9;
    int gPin = 10;
    int bPin = 11;
    int ledPin = 5;
    int buttonPin = 2;
    int currentVals[] = {0, 0, 0};

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

      attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);
    }

    void loop() {
      setBrightness(); // try and move outside of main loop
    }

    // Ensure that buttonPress does not trigger twice
    void buttonPress(){
      if(digitalRead(buttonPin) == 0){
        delay(10);
        if(digitalRead(buttonPin) == 0){

          setMode();
          buttonPressed = true;
          Serial.println(ledMode);
        }
      }
    }

    //Increment LED Mode until max level is reached
    void setMode(){
      if(ledMode == maxLEDMode){
        ledMode = 0;
      } else {
        ledMode++;
      }
    }

    //Set LED colours depending on ledMode
    void setBrightness(){
      buttonPressed = false;

      if(ledMode == 0){
        mode0();
      }

      if(ledMode == 1){
        mode1();
      }

      if(ledMode == 2){
        mode2();
      }

      if(ledMode == 3){
        mode3();
      }

      if(ledMode == 4){
        mode4();
      }

      if(ledMode == 5){
        mode5();
      }
    }

    //Fade to off
    void mode0 (){
      fadeTo(0, 0, 0, 10);
    }

    // Fade to dim light
    void mode1 (){
      int val = 255/5;
      fadeTo(val, val, val, 100);
    }

    // Fade to medium light
    void mode2 (){
      int val = (255/3);
      fadeTo(val, val, val, 100);
    }

    // Fade to bright light
    void mode3 (){
      fadeTo(255, 255, 255, 100);
    }

    // Endlessly cycle through RGB colours
    void mode4(){
        fadeToWithCheck(255, 0, 0, 500);
        fadeToWithCheck(255, 255, 0, 500);
        fadeToWithCheck(0, 255, 0, 500);
        fadeToWithCheck(0, 255, 255, 500);
        fadeToWithCheck(0, 0, 255, 500);
        fadeToWithCheck(255, 0, 255, 500);
    }

    // Pause LED on colour inherited from Mode4
    void mode5(){
      int rExisting = currentVals[0];
      int gExisting = currentVals[1];
      int bExisting = currentVals[2];
      fadeTo(rExisting, gExisting, bExisting, 1);
    }

    // Fade to given colour, with awareness of mode4 toggles
    void fadeToWithCheck(int r, int g, int b, int interval){
      if(ledMode == 4){
        int rExisting = currentVals[0];
        int gExisting = currentVals[1];
        int bExisting = currentVals[2];

        for(int i = 0; i <= interval; i++){
          analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
          analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
          analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));

          if(buttonPressed == true){
            Serial.println("stopping loop");
            currentVals[0] = map(i, 0, interval, rExisting, r);
            currentVals[1] = map(i, 0, interval, gExisting, g);
            currentVals[2] = map(i, 0, interval, bExisting, b);
            break;
          }
          delay(10);
        }

        if(buttonPressed == true){
          buttonPressed = false;
        } else {
          currentVals[0] = r;
          currentVals[1] = g;
          currentVals[2] = b;
        }
      }
    }

    // Fade to given colour
    void fadeTo(int r, int g, int b, int interval){
      int rExisting = currentVals[0];
      int gExisting = currentVals[1];
      int bExisting = currentVals[2];

      for(int i = 0; i <= interval; i++){
        analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
        analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
        analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
        delay(10);
      }
      currentVals[0] = r;
      currentVals[1] = g;
      currentVals[2] = b;
    }

    // Invert given value due to cathode/anode LED
    void analogWriteInverted( byte pin, byte value)
    {
      analogWrite(pin, 255-value);
    }

Any help or advice at all would be appreciated!
Many thanks,
Rob

**UPDATE - Working solution**

Following on from the advice given by Michel, the following code meets my needs perfectly.

    #include "TimerOne.h"

    /*
     * LED MODES
     * 0 = off
     * 1 = dim
     * 2 = mid
     * 3 = bright
     * 4 = colour cycle
     * 5 = colour select
     */
    volatile int ledMode = 0; // off
    const int maxLEDMode = 5;
    volatile bool buttonPressed = false;
    unsigned long lastDebounceTime = -1;
    unsigned long debounceDelay = 200;
    int lastButtonState = HIGH;
    int buttonState;
    long secondTimer = 1000000;

    int rPin = 6;
    int gPin = 5;
    int bPin = 3;
    int buttonPin = 2;
    int currentVals[] = {0, 0, 0};
    int mode4Vals[] = {0, 0, 0};
    int mode4Stage = 0;

    long fadeInterval = 0;
    long lastSeenInterval;

    void setup() {
      Serial.begin(9600);
      pinMode(rPin, OUTPUT);
      pinMode(gPin, OUTPUT);
      pinMode(bPin, OUTPUT);
      pinMode(buttonPin, INPUT);

      Timer1.initialize(secondTimer / 1000);
      attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);

      turnOff();
    }

    void loop() {
      //setBrightness(); // try and move outside of main loop

    }

    void turnOff(){
      analogWriteInverted(rPin,0);
      analogWriteInverted(gPin,0);
      analogWriteInverted(bPin,0);

      currentVals[0] = 0;
      currentVals[1] = 0;
      currentVals[2] = 0;
    }

    // Ensure that buttonPress does not trigger twice
    void buttonPress(){
      int reading = digitalRead(buttonPin);

      if (lastDebounceTime < 0 || (millis() - lastDebounceTime) > debounceDelay) {
        lastDebounceTime = millis();
        if(ledMode != 4){
            clearTimer();
        }
            setMode();
            buttonPressed = true;
            Timer1.attachInterrupt(incrementGlobalFadeInterval);
          }
        }

    //Increment LED Mode until max level is reached
    void setMode(){
      if(ledMode == maxLEDMode){
        ledMode = 0;
      } else {
        ledMode++;
      }
    }

    //Set LED colours depending on ledMode
    void setBrightness(){
      buttonPressed = false;

      switch(ledMode){
        case 0: mode0(); break;
        case 1: mode1(); break;
        case 2: mode2(); break;
        case 3: mode3(); break;
        case 4: mode4(); break;
        case 5: mode5(); break;
        default: abort();
      }

    }

    //Fade to off
    void mode0 (){
      fadeTo(0, 0, 0, 400);
    }

    // Fade to dim light
    void mode1 (){
      int val = 255/5;
      fadeTo(val, val, val, 50);
    }

    // Fade to medium light
    void mode2 (){
      int val = (255/3);
      fadeTo(val, val, val, 50);
    }

    // Fade to bright light
    void mode3 (){
      fadeTo(255, 255, 255, 50);
    }

    // Endlessly cycle through RGB colours
    void mode4(){
      switch(mode4Stage){
        case 0: fadeToWithCheck(255, 0, 0, 2000); break;
        case 1: fadeToWithCheck(255, 255, 0, 2000); break;
        case 2: fadeToWithCheck(0, 255, 0, 2000); break;
        case 3: fadeToWithCheck(0, 255, 255, 2000); break;
        case 4: fadeToWithCheck(0, 0, 255, 2000); break;
        case 5: fadeToWithCheck(255, 0, 255, 2000); break;
        default: abort();
      }
    }

    // Pause LED on colour inherited from Mode4
    void mode5(){
      currentVals[0] = mode4Vals[0];
      currentVals[1] = mode4Vals[1];
      currentVals[2] = mode4Vals[2];

      int rExisting = currentVals[0];
      int gExisting = currentVals[1];
      int bExisting = currentVals[2];
      fadeTo(rExisting, gExisting, bExisting, 1);
    }

    // Fade to given colour, with awareness of mode4 toggles
    void fadeToWithCheck(int r, int g, int b, int interval){
      if(ledMode == 4){
        int rExisting = currentVals[0];
        int gExisting = currentVals[1];
        int bExisting = currentVals[2];

        if(fadeInterval <= interval && lastSeenInterval != fadeInterval){
          lastSeenInterval = fadeInterval;
          analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
          analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
          analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));

          mode4Vals[0] = map(fadeInterval, 0, interval, rExisting, r);
          mode4Vals[1] = map(fadeInterval, 0, interval, gExisting, g);
          mode4Vals[2] = map(fadeInterval, 0, interval, bExisting, b);
        } else {
          currentVals[0] = map(fadeInterval, 0, interval, rExisting, r);
          currentVals[1] = map(fadeInterval, 0, interval, gExisting, g);
          currentVals[2] = map(fadeInterval, 0, interval, bExisting, b);
          fadeInterval = 0;

          if(mode4Stage == 5){
            mode4Stage = 0;
          } else {
            mode4Stage++;
          }
        }
      }
    }

    // Fade to given colour
    void fadeTo(int r, int g, int b, int interval){
      int rExisting = currentVals[0];
      int gExisting = currentVals[1];
      int bExisting = currentVals[2];

      if(fadeInterval <= interval && fadeInterval != lastSeenInterval){
        lastSeenInterval = fadeInterval;
        analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
        analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
        analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));
      } else {
        clearTimer();
        currentVals[0] = r;
        currentVals[1] = g;
        currentVals[2] = b;
      }
    }

    void incrementGlobalFadeInterval(){
      fadeInterval++;
      setBrightness();
    }

    void clearTimer(){
      Timer1.detachInterrupt();
      fadeInterval = 0;
      lastSeenInterval = -1;
    }

    // Invert given value due to cathode/anode LED
    void analogWriteInverted( byte pin, byte value)
    {
      analogWrite(pin, 255-value);
    }

title: RGB LED Mode toggle - Trying to avoid using main loop()

Answers: 2

body:
**Keep interrupt shorts**

Inside an interrupt, do not use long pauses, thus not a delay. As chrisl notes below (see comment) delay does not even work inside an interrupt, since it is based on millis(), which are not updated within an interrupt.

The reason is that interrupts should be as short as possible (so even if you would use a for loop with micros() or another way to hold the execution time), because it can cause new interrupts not to be called (during an interrupt, no new interrupts will be called, at least not with the same/lower priority). So always keep code within interrupts very short, especially delay's are violating this, but also serial.print statements.

I see you use this function which will be called if you put everything in the interrupt handler:

    // Fade to given colour
    void fadeTo(int r, int g, int b, int interval){
      int rExisting = currentVals[0];
      int gExisting = currentVals[1];
      int bExisting = currentVals[2];

      for(int i = 0; i <= interval; i++){
        analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
        analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
        analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
        delay(10);
      }
      currentVals[0] = r;
      currentVals[1] = g;
      currentVals[2] = b;
    }

**Removing delays**

To remove the delay, is a bit tricky though. What you need to do is (approximately):

- Create a global variable instead of the loop variable (i, but give it a better name)
- Calling an additional interrupt based on 10 ms (the delay).
- In that interrupt, handle the next iteration (so increase the global variable `i` (but the new name)
- Handle post processing (e.g. if i == interval, execute the last three statements of the function (and possibly other statements from called functions in the original code).

**Multiple `if` to one `switch` statement**

Also you can use a switch statement.. Instead of

     if(ledMode == 0){
        mode0();
      }

      if(ledMode == 1){
        mode1();
      }

      if(ledMode == 2){
        mode2();
      }

      if(ledMode == 3){
        mode3();
      }

      if(ledMode == 4){
        mode4();
      }

      if(ledMode == 5){
        mode5();
      }
    }

Use

    switch (ledMode)
    {
    case 0:
      mode0();
      break;

    case 1:
      mode1();
      break;

    ..

    case 5:
      mode5();
      break;

    default:
       abort(); // Error condition
    }

Since the cases are so simple I put them normally on one line:

    switch (ledMode)
    {
    case 0: mode0(); break;
    case 1: mode1(); break;
    ..
    case 5: mode5(); break;
    default: abort();
    }

**Button debouncing**

In your remark you say after a button press, sometimes the function is called multiple times. This is caused by button bouncing. When you press a button, for a short time, the contact is somewhere between on and off. During this time, it can change a few times between on and off, thus you get multiple calls, mostly very short after each other. To prevent this, use button debouncing (check the Arduino site for a Button Debounce example). It means that you check if a certain state has been stable for some time, and than perform the action, instead of immediately.

body:
Remove the `buttonPressed = false;` from fadeToWithCheck. As in mode4 this function is called four times, only the current call is skipped if the button is pressed. The following calls are not skipped, because your reset buttonPressed back to false.

There is no need for this, as it's already reset back to false at the beginning of setBrightness.


body:
I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.

I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

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

<!-- End schematic -->

I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.

I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

title: Arduino Uno Issue: No output power

Answers: 2

body:
You need to have a current limiting resistor for *each* of the LED segments. Sharing one resistor between them all is a very bad idea, as multiple lit LEDs (in parallel) will be using the same resistor - see this excellent answer to [Why exactly can't a single resistor be used for many parallel LEDs?][1]:

> The main reason is because you can't safely connect diodes in
> parallel.
>
> So when we use one resistor, we have a current limit for the whole
> diode section. After that it's up to each diode to control the current
> that goes through it.
>
> The problem is that real world diodes don't have same characteristics
> and therefore there's a danger that one diode will start conducting
> while others won't.

I would hazard a guess that you've drawn too much current, or, in your case, tried to sink too much through the PWM pin.

Also, it would (probably) be better to use individual data pins, not PWM pins, to turn on each segment, rather than connecting all of the segments to just one pin. It just seems a bit odd to do it that way.

  [1]: https://electronics.stackexchange.com/questions/22291/why-exactly-cant-a-single-resistor-be-used-for-many-parallel-leds

body:
The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.

Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you *think* you have built.


body:
I return a `char[300]` array from a function.  If I intialize a `char*` variable with it, the return is garbled, but not if I append it to a `String`.  What gives?

      const char* post2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
      String postS2 = "";
      postS2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
      //const char* post2 = { uploadHourCsv(timeNow,pulseChangeHour) };
      if( debug ) {
        Serial.print("received in loop() as : [");
        Serial.println(post2);
        Serial.print("String : [");
        Serial.println(postS2);
      }

    ...

    char postStr[300] = "";
    // populate array
    if( debug ) {
      Serial.print("postStrCsv generated: ");
      Serial.println(postStr);
    }
    return postStr;

> postStrCsv generated: 00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

> received in loop() as : [000?⸮@⸮⸮?" ⸮⸮?17.55;9|17.58! @0⸮⸮⸮⸮G% @5~`⸮h⸮?⸮⸮

> String : [00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

title: Receiving garbled `char` array returned by a function

Answers: 2

body:
It's because you're returning a pointer to a local variable.

You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.

When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.

It's pure chance that the data is still available and intact at the point of copying.

In short:

* You must **never** return a pointer to a locally allocated (non-static) array.

Things you can do that are correct:

* Pass an array pointer to the function to be populated by the function
* Return a pointer to a *statically allocated* local array
* Return a `String` object (though [I wouldn't recommend using String for anything](https://majenko.co.uk/blog/evils-arduino-strings))

My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.

For example:

    void myFunc(char *buf, int len) {
        for (int i = 0; i < len - 1; i++) {
            buf[i] = 'A';
        }
        buf[len - 1] = 0;
    }

    char myBuf[20];
    myFunc(myBuf, 20);
    Serial.println(myBuf);

    --> AAAAAAAAAAAAAAAAAAAA

body:
Following Majenko's invaluable advice and incorporating [another similar approach][1], final working implementation was to treat the function as a method to operate upon the `char[300]` array as "out parameter".

    char postStr[300] =  "";
    uploadHourCsv(timeNow,pulseChangeHour,postStr) ;
    ...

    void uploadHourCsv(int unixtimeEvent, int pulseChange, char* postStr) {
      // prepare data and variables
      strcat(postStr, stationId);
      strcat(postStr,";3|"); // chuva hora
      strcat(postStr, dtostrf(rainHour,6,2,charDummy));
      ...
    }

  [1]: https://stackoverflow.com/a/5660565/1166727