message:
ESP8266-01 wdt reset after uploading code

I'm using code from here: [ESP8266 example: Wi-Fi Access point, static IP, web-server and remote GPIO control][1].

Everything running ok this morning, but now I don't know why wasn't working...

This is what serial monitor display:

    Configuring access point...
    AP IP address: 42.42.42.42
    HTTP server started

    Exception (0):
    epc1=0x40226744 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

    ctx: sys
    sp: 3fffed10 end: 3fffffb0 offset: 01a0

    >>>stack>>>
    3fffeeb0:  00000000 3fffdad0 3ffeefec 00000030
    3fffeec0:  3ffe9560 40226dbb 3fff0104 0000d158
    3fffeed0:  00000000 40216ec8 3ffedfe8 4020f68c
    3fffeee0:  00f20e64 3ffe9374 3ffe9204 3ffef190
    3fffeef0:  4020f7c8 3ffef194 3ffe91fc 60000600
    3fffef00:  40226731 3ffe9370 3ffee820 00000001
    3fffef10:  40226814 3ffe9374 3ffee820 0331cfa4
    3fffef20:  3fff0104 40100ab6 00000001 00000000
    3fffef30:  4022df51 40100883 00000000 00000000
    3fffef40:  4022df96 3fffdab0 00000000 3fffdcb0
    3fffef50:  3ffee838 3fffdad0 3ffeefec 402073e3
    3fffef60:  40000f49 40000f49 3fffdab0 40000f49
    3fffef70:  40000e19 40001878 00000004 00000000
    3fffef80:  3fffff10 aa55aa55 000000ed 40104424
    3fffef90:  4010442a 00000004 00000000 a9751f68
    3fffefa0:  4010000d e45c7604 ffd63db0 ca695611
    3fffefb0:  00000000 3fffef4c 00000000 3fffff08
    3fffefc0:  3fffffd0 00000000 00000000 feefeffe
    3fffefd0:  feefeffe feefeffe feefeffe feefeffe
    3fffefe0:  feefeffe feefeffe feefeffe feefeffe
    3fffeff0:  feefeffe feefeffe feefeffe feefeffe
    3ffff000:  feefeffe feefeffe feefeffe feefeffe
    3ffff010:  feefeffe feefeffe feefeffe feefeffe
    3ffff020:  feefeffe feefeffe feefeffe feefeffe
    3ffff030:  feefeffe feefeffe feefeffe feefeffe
    3ffff040:  feefeffe feefeffe feefeffe feefeffe
    3ffff050:  feefeffe feefeffe feefeffe feefeffe
    3ffff060:  feefeffe feefeffe feefeffe feefeffe
    3ffff070:  feefeffe feefeffe feefeffe feefeffe
    3ffff080:  feefeffe feefeffe feefeffe feefeffe
    3ffff090:  feefeffe feefeffe feefeffe feefeffe
    3ffff0a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff0f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff100:  feefeffe feefeffe feefeffe feefeffe
    3ffff110:  feefeffe feefeffe feefeffe feefeffe
    3ffff120:  feefeffe feefeffe feefeffe feefeffe
    3ffff130:  feefeffe feefeffe feefeffe feefeffe
    3ffff140:  feefeffe feefeffe feefeffe feefeffe
    3ffff150:  feefeffe feefeffe feefeffe feefeffe
    3ffff160:  feefeffe feefeffe feefeffe feefeffe
    3ffff170:  feefeffe feefeffe feefeffe feefeffe
    3ffff180:  feefeffe feefeffe feefeffe feefeffe
    3ffff190:  feefeffe feefeffe feefeffe feefeffe
    3ffff1a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff1f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff200:  feefeffe feefeffe feefeffe feefeffe
    3ffff210:  feefeffe feefeffe feefeffe feefeffe
    3ffff220:  feefeffe feefeffe feefeffe feefeffe
    3ffff230:  feefeffe feefeffe feefeffe feefeffe
    3ffff240:  feefeffe feefeffe feefeffe feefeffe
    3ffff250:  feefeffe feefeffe feefeffe feefeffe
    3ffff260:  feefeffe feefeffe feefeffe feefeffe
    3ffff270:  feefeffe feefeffe feefeffe feefeffe
    3ffff280:  feefeffe feefeffe feefeffe feefeffe
    3ffff290:  feefeffe feefeffe feefeffe feefeffe
    3ffff2a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff2f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff300:  feefeffe feefeffe feefeffe feefeffe
    3ffff310:  feefeffe feefeffe feefeffe feefeffe
    3ffff320:  feefeffe feefeffe feefeffe feefeffe
    3ffff330:  feefeffe feefeffe feefeffe feefeffe
    3ffff340:  feefeffe feefeffe feefeffe feefeffe
    3ffff350:  feefeffe feefeffe feefeffe feefeffe
    3ffff360:  feefeffe feefeffe feefeffe feefeffe
    3ffff370:  feefeffe feefeffe feefeffe feefeffe
    3ffff380:  feefeffe feefeffe feefeffe feefeffe
    3ffff390:  feefeffe feefeffe feefeffe feefeffe
    3ffff3a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff3f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff400:  feefeffe feefeffe feefeffe feefeffe
    3ffff410:  feefeffe feefeffe feefeffe feefeffe
    3ffff420:  feefeffe feefeffe feefeffe feefeffe
    3ffff430:  feefeffe feefeffe feefeffe feefeffe
    3ffff440:  feefeffe feefeffe feefeffe feefeffe
    3ffff450:  feefeffe feefeffe feefeffe feefeffe
    3ffff460:  feefeffe feefeffe feefeffe feefeffe
    3ffff470:  feefeffe feefeffe feefeffe feefeffe
    3ffff480:  feefeffe feefeffe feefeffe feefeffe
    3ffff490:  feefeffe feefeffe feefeffe feefeffe
    3ffff4a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff4f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff500:  feefeffe feefeffe feefeffe feefeffe
    3ffff510:  feefeffe feefeffe feefeffe feefeffe
    3ffff520:  feefeffe feefeffe feefeffe feefeffe
    3ffff530:  feefeffe feefeffe feefeffe feefeffe
    3ffff540:  feefeffe feefeffe feefeffe feefeffe
    3ffff550:  feefeffe feefeffe feefeffe feefeffe
    3ffff560:  feefeffe feefeffe feefeffe feefeffe
    3ffff570:  feefeffe feefeffe feefeffe feefeffe
    3ffff580:  feefeffe feefeffe feefeffe feefeffe
    3ffff590:  feefeffe feefeffe feefeffe feefeffe
    3ffff5a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff5f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff600:  feefeffe feefeffe feefeffe feefeffe
    3ffff610:  feefeffe feefeffe feefeffe feefeffe
    3ffff620:  feefeffe feefeffe feefeffe feefeffe
    3ffff630:  feefeffe feefeffe feefeffe feefeffe
    3ffff640:  feefeffe feefeffe feefeffe feefeffe
    3ffff650:  feefeffe feefeffe feefeffe feefeffe
    3ffff660:  feefeffe feefeffe feefeffe feefeffe
    3ffff670:  feefeffe feefeffe feefeffe feefeffe
    3ffff680:  feefeffe feefeffe feefeffe feefeffe
    3ffff690:  feefeffe feefeffe feefeffe feefeffe
    3ffff6a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff6f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff700:  feefeffe feefeffe feefeffe feefeffe
    3ffff710:  feefeffe feefeffe feefeffe feefeffe
    3ffff720:  feefeffe feefeffe feefeffe feefeffe
    3ffff730:  feefeffe feefeffe feefeffe feefeffe
    3ffff740:  feefeffe feefeffe feefeffe feefeffe
    3ffff750:  feefeffe feefeffe feefeffe feefeffe
    3ffff760:  feefeffe feefeffe feefeffe feefeffe
    3ffff770:  feefeffe feefeffe feefeffe feefeffe
    3ffff780:  feefeffe feefeffe feefeffe feefeffe
    3ffff790:  feefeffe feefeffe feefeffe feefeffe
    3ffff7a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff7f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff800:  feefeffe feefeffe feefeffe feefeffe
    3ffff810:  feefeffe feefeffe feefeffe feefeffe
    3ffff820:  feefeffe feefeffe feefeffe feefeffe
    3ffff830:  feefeffe feefeffe feefeffe feefeffe
    3ffff840:  feefeffe feefeffe feefeffe feefeffe
    3ffff850:  feefeffe feefeffe feefeffe feefeffe
    3ffff860:  feefeffe feefeffe feefeffe feefeffe
    3ffff870:  feefeffe feefeffe feefeffe feefeffe
    3ffff880:  feefeffe feefeffe feefeffe feefeffe
    3ffff890:  feefeffe feefeffe feefeffe feefeffe
    3ffff8a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff8f0:  feefeffe feefeffe feefeffe feefeffe
    3ffff900:  feefeffe feefeffe feefeffe feefeffe
    3ffff910:  feefeffe feefeffe feefeffe feefeffe
    3ffff920:  feefeffe feefeffe feefeffe feefeffe
    3ffff930:  feefeffe feefeffe feefeffe feefeffe
    3ffff940:  feefeffe feefeffe feefeffe feefeffe
    3ffff950:  feefeffe feefeffe feefeffe feefeffe
    3ffff960:  feefeffe feefeffe feefeffe feefeffe
    3ffff970:  feefeffe feefeffe feefeffe feefeffe
    3ffff980:  feefeffe feefeffe feefeffe feefeffe
    3ffff990:  feefeffe feefeffe feefeffe feefeffe
    3ffff9a0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9b0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9c0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9d0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9e0:  feefeffe feefeffe feefeffe feefeffe
    3ffff9f0:  feefeffe feefeffe feefeffe feefeffe
    3ffffa00:  feefeffe feefeffe feefeffe feefeffe
    3ffffa10:  feefeffe feefeffe feefeffe feefeffe
    3ffffa20:  feefeffe feefeffe feefeffe feefeffe
    3ffffa30:  feefeffe feefeffe feefeffe feefeffe
    3ffffa40:  feefeffe feefeffe feefeffe feefeffe
    3ffffa50:  feefeffe feefeffe feefeffe feefeffe
    3ffffa60:  feefeffe feefeffe feefeffe feefeffe
    3ffffa70:  feefeffe feefeffe feefeffe feefeffe
    3ffffa80:  feefeffe feefeffe feefeffe feefeffe
    3ffffa90:  feefeffe feefeffe feefeffe feefeffe
    3ffffaa0:  feefeffe feefeffe feefeffe feefeffe
    3ffffab0:  feefeffe feefeffe feefeffe feefeffe
    3ffffac0:  feefeffe feefeffe feefeffe feefeffe
    3ffffad0:  feefeffe feefeffe feefeffe feefeffe
    3ffffae0:  feefeffe feefeffe feefeffe feefeffe
    3ffffaf0:  feefeffe feefeffe feefeffe feefeffe
    3ffffb00:  feefeffe feefeffe feefeffe feefeffe
    3ffffb10:  feefeffe feefeffe feefeffe feefeffe
    3ffffb20:  feefeffe feefeffe feefeffe feefeffe
    3ffffb30:  feefeffe feefeffe feefeffe feefeffe
    3ffffb40:  feefeffe feefeffe feefeffe feefeffe
    3ffffb50:  feefeffe feefeffe feefeffe feefeffe
    3ffffb60:  feefeffe feefeffe feefeffe feefeffe
    3ffffb70:  feefeffe feefeffe feefeffe feefeffe
    3ffffb80:  feefeffe feefeffe feefeffe feefeffe
    3ffffb90:  feefeffe feefeffe feefeffe feefeffe
    3ffffba0:  feefeffe feefeffe feefeffe feefeffe
    3ffffbb0:  feefeffe feefeffe feefeffe feefeffe
    3ffffbc0:  feefeffe feefeffe feefeffe feefeffe
    3ffffbd0:  feefeffe feefeffe feefeffe feefeffe
    3ffffbe0:  feefeffe feefeffe feefeffe feefeffe
    3ffffbf0:  feefeffe feefeffe feefeffe feefeffe
    3ffffc00:  feefeffe feefeffe feefeffe feefeffe
    3ffffc10:  feefeffe feefeffe feefeffe feefeffe
    3ffffc20:  feefeffe feefeffe feefeffe feefeffe
    3ffffc30:  feefeffe feefeffe feefeffe feefeffe
    3ffffc40:  feefeffe feefeffe feefeffe feefeffe
    3ffffc50:  feefeffe feefeffe feefeffe feefeffe
    3ffffc60:  feefeffe feefeffe feefeffe feefeffe
    3ffffc70:  feefeffe feefeffe feefeffe feefeffe
    3ffffc80:  feefeffe feefeffe feefeffe feefeffe
    3ffffc90:  feefeffe feefeffe feefeffe feefeffe
    3ffffca0:  feefeffe feefeffe feefeffe feefeffe
    3ffffcb0:  feefeffe feefeffe feefeffe feefeffe
    3ffffcc0:  feefeffe feefeffe feefeffe feefeffe
    3ffffcd0:  feefeffe feefeffe 40227cb3 00000001
    3ffffce0:  ffffffff 00000000 3ffe96b1 00000008
    3ffffcf0:  40227d02 3ffeccf8 3ffefadc 00000001
    3ffffd00:  3fff07e8 00000000 4010106b 3ffeccf8
    3ffffd10:  000000c0 4021a0c2 00000008 3fff06d8
    3ffffd20:  40226d70 3ffeccf8 3ffed470 3fff07e8
    3ffffd30:  00000000 4021a22b 3ffefd84 feefeffe
    3ffffd40:  00000000 00000002 00000001 3ffeccf8
    3ffffd50:  00000000 400042db 3fff07e8 3ffeff44
    3ffffd60:  40004b31 3fff080c 0000049c 0007e000
    3ffffd70:  401057e0 4020dfcd 3ffef154 3ffeff44
    3ffffd80:  40106475 3fff080c 0000049c 00000000
    3ffffd90:  00000000 00000000 00000020 40100f22
    3ffffda0:  00000000 00000000 00000020 40100f22
    3ffffdb0:  3ffe9560 40104304 3fff0104 40100f22
    3ffffdc0:  00000001 40103523 3ffed6e0 40100f22
    3ffffdd0:  40103986 00000000 00000020 40100f22
    3ffffde0:  4010346a 0000007f 7fffffff 00000000
    3ffffdf0:  4010346a 0000007f 7fffffff 00000000
    3ffffe00:  0000007f 00040000 7fffffff 00000000
    3ffffe10:  40103269 00040000 7fffffff 00000000
    3ffffe20:  00000000 00000000 0000001f 40104bfd
    3ffffe30:  00000000 00000000 0000001f 40104bfd
    3ffffe40:  4000050c 00000030 00000011 ffffffff
    3ffffe50:  00000000 00000000 0000001f 40104bfd
    3ffffe60:  4000050c 00000002 03316038 00000000
    3ffffe70:  4020386b 00000030 00000010 ffffffff
    3ffffe80:  00000000 00000000 0000001f 40104bfd
    3ffffe90:  4000050c 00000000 00000000 fffffffe
    3ffffea0:  40000ea6 00000030 0000001e ffffffff
    3ffffeb0:  40000ea3 00000000 00000001 00000001
    3ffffec0:  3fffdab0 00000000 3fffd9d0 3ffeefec
    3ffffed0:  00000000 00000000 00000001 3ffeefe4
    3ffffee0:  00000000 3fffdad0 3ffeefec 00000030
    3ffffef0:  ffffffff 3fffc6fc 00000001 3ffe85e8
    3fffff00:  00000000 3fffdad0 3ffeefec 00000030
    3fffff10:  00000000 3fffdad0 3ffeefec 00000030
    3fffff20:  402077a4 3ffeedfc 000003e8 402074e2
    3fffff30:  3ffe8f00 00000000 00000000 40207525
    3fffff40:  3ffe8cac 3ffeedfc 3ffeee00 40203fbe
    3fffff50:  3fff014c 00ffffff 3ffeef2c 4020671c
    3fffff60:  3fffdad0 3ffeedfc 3ffeedfc 40207918
    3fffff70:  4020290c 00000000 3ffeedfc 40204f31
    3fffff80:  40207b28 00000000 00001388 40207c40
    3fffff90:  00000000 00000000 feefeffe feefeffe
    3fffffa0:  00000000 00000000 00000001 40207449
    <<<stack<<<

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

    wdt reset

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

    wdt reset

Could someone please tell me how can I make it work again?

  [1]: https://42bots.com/tutorials/esp8266-example-wi-fi-access-point-web-server-static-ip-remote-control/

body:
I tried the sketch you posted and it works.

The most likely problem is the power source for the ESP8266. You have in the title ESP8266-1 so I will assume you have a ESP-01 module.

A lot of people who start with the ESP-01, or any other module without an onboard 3.3v regulator, don't know how demanding the ESP8266 is on the power source. It needs to have a stable 500mA capacity for it to work reliably. Also the regulator must be electrically close to the module. Using long connecting wires is one problem I see often.

The ESP8266 could have enough power to get programmed correctly but when it comes to transmitting it will draw a lot more current and if the power supply is insufficient a voltage dip occurs and then unpredictable behaviour occurs.

Check over any connections that might be poor. Please post what you are using for hardware if you can't get things running again.


sender: user

message:
How to make Built in LED blink systematically?

I am trying to make my built in LED on my arduino blink every 1 second while recording my data and putting it in the EEPROM, but I am not sure how to do that. I am supposed to print data to the EEPROM every minute, until the EEPROM is full and while that is going on my built in LED should blink for approx 1 second. My problem seems to be that I am setting a delay to delay how long the data is stored on the EEPROM, but it is also affecting the time it takes for my LED to blink as it is waiting to blink as the data is stored. Any help would be appreciated, the code is below:

    #include<EEPROM.h>
    const int SWITCH = 4;

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

    }

    void loop() {
      // put your main code here, to run repeatedly:
      int addr = 0;
      int r = analogRead(0);

      if (digitalRead(SWITCH) == LOW) {
        Serial.println("----Recording----");
      }
      while (addr <= 1024) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay (250);
        digitalWrite(LED_BUILTIN, LOW);
        delay(750);
        Serial.println(r);
        EEPROM.put(addr, r);
        addr = addr + 2;
        delay(600);
      }
      while (true);
    }

sender: assistant

body:
Do not use delay(). Use the example Blink without delay example as the starting point.

https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Find it under Examples    02.Digital

Simple code like delay() is called blocking code. It prevents other things from happening until t is through. That is acceptable in very sequential linear programs where only one thing is ever happening. And you have discovered the limitation of that. Time to get more sophisticated in your programming.

Please open the example and play with it. Make sure you understand it before thinking of how to modify your code.


body:
As Rudy mentions in his answer, don't use `delay()`, and start with the `BlinkWithoutDelay` example that comes with the Arduino IDE. Here is a sketch to get you started. If you compare it to the `BlinkWithoutDelay` example, it's very similar, except I added some button code to "start" and "stop" the LED flashing.

    const byte SWITCH = 4;
    const byte ledPin = 13;
    const unsigned long oneSecond = 1000;
    unsigned long previousMillis = 0;
    byte ledState = LOW;
    byte recording = 0;

    void setup(){
      pinMode(ledPin, OUTPUT);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){

      unsigned long currentMillis = millis();

      if(digitalRead(SWITCH) == LOW){
        recording = 1;
      }
      else{
        recording = 0;
        digitalWrite(ledPin, LOW);
      }

      if(currentMillis - previousMillis >= oneSecond){

        previousMillis = currentMillis;

        if(recording){
          if(ledState == LOW){
            ledState = HIGH;
          }
          else{
            ledState = LOW;
          }
        }
        digitalWrite(ledPin, ledState);
      }
    }


message:
Stacks on arrays on arrays

I am trying to find a "vanilla" way of writing several arrays into one. I spent a lot of time searching for how to do this but everything that comes up is either a tutorial that doesn't cover concatenation or someones question that ended up being an unrelated syntax problem.

I put several strands of WS2812B LEDs wired in series so the Arduino sees them as one continuous strand. I have been able to run some very cool patterns as one strand using the Pololu library but I would like to program the strands separately. The number of lights I have is very resource intensive and I like to keep things simple so I'm looking for advice on the best way to go about combining arrays without importing more libraries.

Because the patterns I have used so far write to an array and the output is an array, my first thought was that I could write one pattern to an array made up of sections 1, 4, and 5, and another pattern that would be mapped to sections 2, 3, and 6 and then concatenate it all together in order. However, adding arrays seems to be somewhat complicated without worrying about this or that persons favorite library or looping through one value at a time and I am trying to work on my C skills. Is there a simple way to concatenate arrays or a better way for me to think about this? Any best practice or organizational advice is welcome. I want to write clean code.

Bonus Round: I use several different languages at work and I cant figure out why I have it in my head that this would work...

    array1 = [a, b, c]
    array2 = [x, y]
    array3 = array1 + array2

    // array3 = [a, b, c, x, y]

Any idea if that is possible or what language I am thinking of?

body:
C(++) does not natively let you "add" arrays like that.  Your code looks like maybe Python.

There are several ways to do what you want to do.  You could make your code which writes the pattern to the array accept an offset - so rather than always starting at position 0, you could tell it where to start.

You could write a function to "concatenate" arrays, or use one someone else has written, if you can find one.  It's pretty trivial to do.

However the method I'd use in your situation, probably just a matter of preference really, is this:

Let's say (for example) you have 6 strips of 10 LEDs each.  You need 60 elements to represent them all.  (I'm assuming each element is an `int`; I can't remember if it is.)  Create one big array for the whole lot:

    int allElements[60];

You might think of the variable `allElements` as an array, but it is really an `int*` (a pointer to an `int`), with that memory address happening to have 59 other memory addresses after it reserved.  C knows that when you say `allElements[7]` it needs to looks 7 `int`s on from the address pointed to by `allElements`.  What this means is that you can create new variables which point to parts of that array, and use those variables as if they were their own arrays.  For example:

    int *firstStrip = &(allElements[0]);
    int *secondStrip = &(allElements[10]);
    int *thirdStrip = &(allElements[20]);
    /* ... and so on */

(There is a more idiomatic way to write this which is exactly equivalent, but I think the above is more explicit if you're new to it.)

As an extra improvement you might now notice that you have a load of similarly-named variables with similar functions -- and you might want to put them into an array.

    int* strips[] = { &(allElements[0]), &(allElements[1]), &(allElements[2]) /* and so on */};

Now you can use `strips[3]` to give you the fourth strip.

There are several other ways too, but I think this will get you going.


message:
Does NodeMCU have some protection against wrong connections that could kill a computer USB?

I know *some* computer USB could handle some bad connection (by blocking the port, which need to reboot the computer). But I wonder if a NodeMCU 8266 offers some protection.

body:
Most USB ports are shut down when an over-current event is detected.

There is nothing in a NodeMCU that can prevent an over-current event in the case of things like short circuits. The 5V (or VIN on some versions) pin is directly (or sometimes via a single diode) connected to the 5V pin of the USB. Cause a short on the 5V pin and you cause a short on the USB.

Protection is designed to be at the port level not the device level so that devices don't have to be forced to comply to protection "standards" that would drive up costs and result in devices being non-compliant and risk damaging the computer.

If you find that you are often causing shorts on the 5V pin and killing (albeit temporarily) your USB ports you should change your working practices.

It can be good to always connect your devices to an external powered USB hub instead of directly to your computer. That way if you kill a port you can just unplug the hub and plug it back in again to reset all the ports. No need to reboot your computer.

Cheap hubs often just have a simple PTC fuse instead of proper over-current protection which can actually be more useful for device developers since the port won't be disabled, just the external power shut off.

Most Arduino boards do incorporate a PTC fuse in the USB power circuitry, but NodeMCU and similar boards don't.


message:
ESP8266 library: 2 requests received instead of 1

I have a strange issue with my sketch using WiFiEsp.h library from [https://github.com/bportaluri/WiFiEsp][1]

When i send 1 request to my ESP8266 from my browser as [http://192.168.0.25
][2], it seems that my ESP8266 receives 2 requests and run 2 times. See the sketch here and Serial Termninal:

    void loop()
    {
      // listen for incoming clients
      WiFiEspClient client = server.available();
      if (client) {
        Serial.println("New client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected())
        {
          if (client.available())
          {
            char c = client.read();
            Serial.write(c);
            // 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) {
              Serial.println("Sending response");

              // send a standard http response header
              // use \r\n instead of many println statements to speedup data send
              client.print(
                "HTTP/1.1 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "Connection: close\r\n"  // the connection will be closed after completion of the response
                "\r\n");
              client.print("<!DOCTYPE HTML>\r\n");
              client.print("<html>\r\n");
              client.print("Hello World!\r\n");
              client.print("</html>\r\n");
              break;
            }
            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;
            }
          }
        }
        // give the web browser time to receive the data
        delay(10);

        // close the connection:
        client.stop();
        Serial.println("Client disconnected");
      }
    }

Serial temrinal:

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful - 2.0.0
    Attempting to connect to WPA SSID: Numericable-6010
    [WiFiEsp] Connected to Numericable-6010
    You're connected to the network
    SSID: Numericable-6010
    IP Address: 192.168.0.25

    To see this page in action, open a browser to http://192.168.0.25

    [WiFiEsp] Server started on port 80
    [WiFiEsp] New client 0
    New client
    GET / HTTP/1.1
    Host: 192.168.0.25
    Connection: keep-alive
    Cache-Control: max-age=0
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    Referer: http://192.168.0.25/
    Accept-Encoding: gzip, deflate
    Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

    Sending response
    [WiFiEsp] Disconnecting  0
    Client disconnected
    [WiFiEsp] New client 1
    New client
    GET /favicon.ico HTTP/1.1
    Host: 192.168.0.25
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
    Accept: image/webp,image/apng,image/*,*/*;q=0.8
    Referer: http://192.168.0.25/
    Accept-Encoding: gzip, deflate
    Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

    Sending response
    [WiFiEsp] Disconnecting  1
    Client disconnected

Please, could you explain why 2 clients connected ? How can i disconnect just after the first one ?

  [1]: https://github.com/bportaluri/WiFiEsp
  [2]: http://192.168.0.25

body:
Adding head part with hortcut icon link in html response fix the issue. Thanks !!!

                client.print(
                "HTTP/1.1 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "Connection: close\r\n"  // the connection will be closed after completion of the response
                "\r\n");
              client.print("<!DOCTYPE HTML>\r\n");
              client.print("\r\n");
              client.print("<link rel='shortcut icon' href='data:image/x-icon;,' type='image/x-icon'> \r\n");
              client.print("\r\n");
              client.print("\r\n");
              client.print("Hello World!\r\n");
              client.print("\r\n");


body:
Browsers automaticaly request /favicon.ico for sites. Add this to `<head>` section of your HTML to eliminate the 'favicon' request:

`<link rel="icon" href="data:;base64,iVBORw0KGgo=">`

    client.println("HTTP/1.1 200 OK\r\n" "Content-Type: text/html");
    client.println("Connection: close");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("");
    client.println("<link rel='icon' href='data:;base64,iVBORw0KGgo='>");
    client.println("");
    client.println("Hello World!");
    client.println("");

based on [this SO answer][1], instead of pointing to a server, the icon is encoded in the href parameter as base64 string

  [1]: https://stackoverflow.com/questions/1321878/how-to-prevent-favicon-ico-requests/13416784#13416784


message:
32u4 using internal clock on custom PCB - loading sketch

I have a custom PCB with a 32u4 running fine with an 8MHz external oscillator.  I burned the bootloader and loaded my sketch with an UNO using Arduino as ISP.

I have no USB on my PCB nor do I need precise timing, so I wanted to see if I could simplify things by removing the external oscillator and caps.

Reading the 32u4 datasheet it states "The device is shipped with Low Power Crystal Oscillator (8.0 - 16MHz) enabled and with the fuse CKDIV8 programmed".

With that, can I simply hook my PCB (assuming a factory fresh 32u4) via ISP to the UNO as before and in IDE just use Sketch > Upload Using Programmer?    Basically not burning any bootloader at all.

Also, in IDE I have been choosing the Sparkfun ProMicro 3.3v, 8MHz board.  Can I still use that selection?

body:
Yes you can reprogram your 32U4 chips via the ISP, they do not have to be fresh chip. If you set your Fuses to `-U lfuse:w:0xE2:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m` using AVRDUDE you will have an 8mhz internal RC oscillator set and you do not have to have the external crystal.

You can play with these settings at http://www.engbedded.com/fusecalc/.

I recommend learning the command line AVRDUDE commands this way you have more control over what you are doing to your chip.

I use this all the time, and if you need to do more than one quickly I typically make a batch file that does the Fuse Burn and hex at the same time.

this is for a attiny167 but you get the idea:
`.\avrdude\avrdude -C".\avrdude\avrdude.conf" -v -pattiny167 -cstk500v2 -PCOM3 -Ulfuse:w:0xE2:m -Uhfuse:w:0xDF:m -Uefuse:w:0xFF:m  -Uflash:w:1060X01-001.hex:i `


body:
I just received some 32u4RC chips and confirmed:
If you are building a custom PC and want to use the 32u4 chip and use the chip's internal clock for your project, simply purchase the 32u4RC version of the chip.  Your sketch can be loaded onto the chip via SPI without the need to set any fuses with avrdude.


message:
How to allow cross-domain requests on ESP8266WebServer

I am using a Raspberry Pi running Chrome (handling the user interface) and connecting via ajax to an Arduino D1 compatible using the IP address as follows:

  $.ajax({
   type: "GET",
   url: "http://10.1.1.100/myfunc?id=5",
   error:  function(jqXHR, exception, response) {
     console.log(exception, response);

            etc...

I recently started getting this error (wonder why it didn't happen for the last two years):

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.1.1.100/myfunc?n=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I tried various things including setting the browser (Chrome) to `--disable-web-security` and various suggestions, [here][1] and [here][2] (and many more) but I can't seem to get it to work. Currently, I have:
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>
    ESP8266WebServer server(80);

    void handleRoot() {
      server.send(200, "text/plain", "Root of WebServer!");
    }

    void setup() {
    IPAddress ip(10.1.1.100);
    IPAddress gateway(10.1.1.1);
    IPAddress subnet(...);
    WiFi.begin(ssid, password);
    WiFi.config(ip, gateway, subnet);
      // put your setup code here, to run once:
      WiFi.begin(ssid, password);
      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
      }

      server.on("/", handleRoot);

      server.on("/myfunc", [](){
        String message = "";
        message += "URI: ";
        message += server.uri();
        message += "\nMethod: ";
        message += (server.method() == HTTP_GET)?"GET":"POST";
        message += "\nArguments: ";
        message += server.args();
        message += "\n";
        for (uint8_t i=0; i<server.args(); i++){
          message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }
          String num = server.arg(0);

        server.send(200, "text/plain", message);
     });
      server.on("/myfunc", HTTP_OPTIONS, []() {
        server.sendHeader("Access-Control-Allow-Origin","*")
        server.send(204);
     });

      server.onNotFound(handleNotFound);
      server.begin();
    }

    void loop() {
      delay(1000);
      ...
      server.handleClient();
    }

    void handleNotFound(){
      String message = "Error!";
      server.send(404, "text/plain", message);
    }

  [1]: https://hackaday.io/project/12227-smart-home-in-the-iot-way/log/43430-esp8266-direct-access-from-web-app
  [2]: https://www.esp8266.com/viewtopic.php?f=24&t=1085

So what am I doing wrong? Also, one complication that might crop up later is that the domain from where I am calling this in ajax is https and from what I understand https and http are not compatible with cross-domain requests.

Any help is appreciated!

body:
Add the CORS header to every response, not only for 'preflight' OPTIONS request. The OPTIONS support is optional, but the response returning the 'shared resource' must contain the CORS header

`"Access-Control-Allow-Origin: *"`

EDIT: since 2020, the library has `server.enableCORS(true);`


body:
just add this line before every response:

`server.sendHeader("Access-Control-Allow-Origin", "*");`


body:
```
server.enableCORS(true);
```
The server will add the response `Access-Control-Allow-Origin=*` header


message:
Arduino IDE Board Selection for 32u4 on custom PCB

I am using a 32u4 on a custom PCB: 3.3v, 8MHz.

Are there any operational differences between using the Sparkfun ProMicro selection versus the Adafruit ItsyBitsy selection in IDE, since they are both for the 32u4?

body:
There should not be any difference, However you would need to load the ItsyBitsy bootloader instead of the ProMicro Bootloader. Personally, I use the Pro Micro Bootloader on my 32u4 Boards.

The only difference would be in the size of each bootloader, one may be smaller and give you more actual codespace. Other than that there should be no performance difference because your code runs independently of the bootloader.


message:
Getting individual outputs from 4 load cells

This is my first time using an Arduino, and I want to connect 4 load cells to one Arduino board and then get 4 separate outputs for each load cell on a computer.
What would I need to accomplish this and how would I set it up?
Can all four load cells connect to a single Arduino?

Also, could I get it to work with these load cells in particular:

https://www.amazon.co.uk/HALJIA-Weighing-Resistance-Half-bridge-Original-Silver/dp/B0792WCGJC/

or would I have to use ones with a 4 wire output?

body:
For this purpose there are 'simple' interface boards like the HX711 (google on HX711). A guy named Bogde has written an Arduino library to manage this board which you can find on GitHub (https://github.com/bogde/HX711). There you can also subscribe to the corresponding email group, which is rather lively and also handles similar questions as yours.

Also Sparkfun sells these sort of interface boards and has very good and extensive documentation and tutorials on the site (see comment from VE7JRO below your question).

You can manage 4 load cells with one Arduino depending on the frequency with which you want to read them. If all 4 load cells are used to weigh one platform then Sparkfun sells an interface board to combine them in one "weight sensor" making it even more simple to interface with the Arduino.


message:
Digispark don't work when I power it by 5v and GND inputs and chip starts heating

I'm beginner so probably I did something stupid, but now my digispark don't work when I power it by 5v and GND inputs but chip starts heating immediately. When I power it by USB everything works well. Did i broke it? And how can I check it?

body:
You connected the power backwards - so all the current is being shunted straight through the ESD protection diodes (and likely other routes too) generating lots of heat and risking permanent damage to the MCU.

Take better care next time...


message:
FreeRTOS Timer Use

I use Timer1 on an UNO to generate a 38KHZ signal for IR communications. It all works as expected.

BUT, I need to convert the code to run as a task under FreeRTOS, and can't seem to find any details about which HW timers are available for the UNO or MEGA.

Also, as long as I'm asking about FreeRTOS, is it reliable for the timer tick to be changed from the 15ms that I think is standard to something faster?

body:
FYI, I found my own answer by looking into the FreeRTOS source code.

FreeRTOS uses timer0, timer1, timer2 and timer3 according to the source code. I assume that it uses the timers as required based on CPU type and capability.


message:
Arduino Power Consumption

I am pairing an Arduino Uno along with both a HC-05 bluetooth module and a sensor circuit.

Show below is the circuit conditions as well as the circuit.
[![enter image description here][1]][1]

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

As far as powering up the system, I am planning to use a 9 Volt battery(550 ampere) to connect to the Arduino which draws in 45 mA and the sensor circuit which takes in a total of 28 mA. I calculated the total life of one of the batteries to be 7.53 hours by (550/(28+45)). Can someone help me with the total power consumed by the system?

UPDATE:
I read on the sensor data sheet that there are two parameters which heater power as well as sensor consumption. Heater Power consumers approximately 140 mW and the sensor consumes approximately 10 mW. I believe the Arduino will consume 405 mW because of (9 volts * 45 mA)  and the bluetooth module will consume 26.5 mW because (3.3 volts * 8). Therefore, the total power consumption is 571.5 mW. Is this correct??? Also will the 9 volt battery be able to support the total power?

body:
Your calculations are not totally right. I did not check the data you provided, so I'm just using the numbers you put.

The arduino draws up 45mA @5V.
The sensor has a power of 150 mW and is powered at 5V, which means a current of 30mA.
The bluetooth module gets 8mA (are you really sure? it seems too low) @3.3V.

Now, the battery gives you 9V. So you need to convert them to the proper (5V and 3.3V) voltages required by the devices.

You have mainly two options:

* you use a linear regulator
* you use a switching regulator

(Please note that if you use the regulators already present on the UNO board - the 1117 and the LP2985 - you will use the first approach)

In the linear case, the regulator will drop the voltage by dissipating the excess power through heat. In this case, you will need to sum the currents:

Total current = 45mA + 30mA + 8mA = 83mA. Please note that if using a 9V battery, the 5V regulator will need to dissipate (9-5) * 83mA = 332mW of power (or slightly less if the 3.3V regulator directly interfaces to the 9V battery).

Now, according to the [first datasheet][1] I stumbled upon on google, this kind of battery have a capacity rated at 10mA, but at 100mA it loses about 40% of it. In fact, batteries tend to last less when the current increases (if you double the current you will get less than half of the time).

Considering so a mere 30% of loss at 83mA, your battery will last slightly above 4 hours and a half (550mAh*70%/83mA)

Now, if you use a switching regulator to get 5V from the 9V (and then a linear one to get the 3.3V), you will have to generate 83mA at 5V. This means that, considering an efficiency of 85%, your battery will have to provide roughly 54mA (83mA*5V/9V/85%).

According to the datasheet of the battery, this lower current reduces the degradation of the capacity to about 25%. The total uptime is consequently 7 hours and a half (550mAh*75%/54mA).

If you put a second switching regulator to get the 3.3V, you will have
- 75mA at 5V, which with a 85% efficiency will become 49mA
- 8mA at 3.3V, and with a lower efficiency due to the very low current (let's say 75%) become 4.4mA

Total current from battery: 53.4mA (which can be considered equal to the case with just one switching converter.

Just one last note: please consider that a heated sensor like the one you have is not engineered for battery-powered devices, since a lot of power becomes heat. When you want to develop a real battery-powered sensor, you will need to go with a lower-power solution for both the microcontroller (and the board) and the sensor

  [1]: http://data.energizer.com/pdfs/522.pdf


message:
Feed values to an array using keypad interfaced with Arduino Uno

I am trying to input keypad values to an array. The code compiles without any error. When running the code, the code proceeds into the for loop and prints 'm' on the lcd, but doesn't execute "customKey = customKeypad.getKey();" and the below steps and keeps printing 'm' 5 times. I am not able to enter keypad values. Please help.

    #include <LiquidCrystal.h>
    #include <Keypad.h>

    const int rs = A1, en = A0, d4 = A2, d5 = A3, d6 = A4, d7 = A5;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

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

    char hexaKeys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, {
        '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } };

    byte rowPins[ROWS] = { 13, 12, 11, 10 };
    byte colPins[COLS] = { 9, 8, 7, 6 };

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,
        COLS);

    //String inputString = "";
    char customKey;
    char a[5];

    void setup() {
      Serial.begin(9600);
      //inputString.reserve(200);
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.clear();
      if (Serial.read() == '1') {
        lcd.setCursor(0, 0);
        lcd.print("WELCOME !");
        delay(1000);
        lcd.clear();
        lcd.print("Enter UserID :");
        lcd.setCursor(0, 1);
        for (int i = 0; i < 5; i++) {
          lcd.print('m');
          customKey = customKeypad.getKey();
          delay(30);

          if (customKey) {
            lcd.print('*');
            a[i] = customKey;
          }
          if (i == 5) {
            a[i] = '\0';
            break;
          }

          delay(1000);
        }
      }
    }

body:
`customKeypad.getKey();` doesn't wait for the key press. it returns 0 if no key is pressed.

you should rewrite the sketch to a version where the loop() can loop and key presses are read as they are pressed.


message:
Using TFT with hardware SPI and speaker with tone()

I want to make a device with a TFT screen and a speaker that uses the builtin `tone()` function. However, according to the [documentation][1], using `tone()` interferes with PWM on pins 3 and 11. On the Arduino Uno, the [MOSI pin is default on pin 11][2], and it seems like defining another pin for MOSI disables hardware SPI, which, according to the module page, slows down the device. As well, the examples are written for hardware SPI and the SD card is only available with hardware SPI. What should I do here? Is there a way to redefine the default MOSI pin without disabling hardware SPI?

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
  [2]: https://www.arduino.cc/en/Reference/TFTLibrary

body:
You are getting your wires crossed in your brain and imagining a problem where there is none.

Both PWM on pins 3 & 11, and `tone()`, use the Timer2 device. Only one of those can use Timer2 at a time, and they both want to use it in different ways, so there is a conflict between them.

Timer2 has nothing to do with SPI. So `tone()` has no effect on SPI, and nor does PWM have any effect on SPI (other than the fact that only one can come out of pin 11 at any time), since there is no internal resource conflict.


message:
Strange compiler error (Segmentation Fault)

You're getting a compiler error. It happens in strange parts of code that really shouldn't be having a problem.  The error looks something like:

    C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault

    }

    ^

    Please submit a full bug report,

    with preprocessed source if appropriate.

    See http://gcc.gnu.org/bugs.html for instructions.

    lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status

    compilation terminated.

    c:/program files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed

    collect2.exe: error: ld returned 1 exit status

What is it, and how do you fix it?

body:
This is a known fault with the compiler in Windows.  The annoying thing is that it's the version of the compiler that is included in the Windows Store App version of the Arduino IDE.

It also snuck into the Windows version of the IDE from version 1.8.6 from the Arduino.cc website, with the bundled version of the Arduino AVR core.

There are numerous Github issues open for the problem and navigating the tangled web of them is a bit of a chore, but this one seems to be the most promising for digging into the root cause:

* [AVR core 1.6.22 (IDE 1.8.6) crashes avr-gcc compiler (5.4.0) when F() string is assigned to a static variable](https://github.com/arduino/ArduinoCore-avr/issues/39)

The simplest fix is to downgrade your compiler to 4.9.2.  This can be done by using the Boards Manager to install version **1.6.21** of the **Arduino AVR Boards**.  This should give you compiler version `4.9.2-atmel3.5.4-arduino2` which doesn't suffer from the problem.


body: I've been having this kind of error off and on lately for no apparent reason. What eliminated it for me was going into the IDE preferences and changing compiler output to verbose and also show all warnings. What??? I know it's crazy. I was just trying to get more information about the error, but I haven't gotten it since. And I was getting it a lot before.


body:
Sometimes it seems like I have to reboot my PC, as exiting from Arduino and rerunning still doesn't always allow me to compile again.

>> "changing compiler output to verbose and also show all warnings"

This worked for me too.


body: I put back the settings to its default state again, after a restart and compile. It worked. Not sure whats under this?


message:
How to transmit Float sensor values via NRF24L01 module?

I'm trying to figure out a way to transmit four sensor values: Voltage, Current, Power and consumption but I'm unable to do that.
Yet, my syntax is correct... what am I missing?

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include <RF24.h>

    #define ACS712 A0

    int lastData = 0;
    int dataSum = 0;
    int Count = 0;

    float Voltage;
    float Current;
    float Power;
    float kWh;
    float Consumption;
    String Data;

    float vpc = 4.882813; // approx. voltage per count

    RF24 radio(9, 10); // CE, CSN
    const byte addresses[][6] = {"00001", "00002"};

    void setup() {
      Serial.begin(115200);
      pinMode(13, OUTPUT);
      radio.begin();
      radio.openWritingPipe(addresses[1]); // 00001
      radio.openReadingPipe(1, addresses[0]); // 00002
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
    }

    void loop() {

      radio.stopListening();

      if (millis() > lastData + 1) {
        dataSum += sq(analogRead(ACS712) - 512);
        Count++;

        lastData = millis();
      }
      // If statement to make calculations.
      if (Count == 1000) {

        // To get the RMS of the data.
        float mean = dataSum / Count;
        float value = sqrt(mean);

        // To get the Voltage (in volts) consumed.
        float Voltage = value * vpc;

        // To get the Current (in amps) consumed.
        float Current = Voltage / 66;

        // To get the Power (in watts) consumed.
        float Power = Current * 240;

        float kWh = Power / 1000;
        float Consumption = kWh;

        dataSum = 0;
        Count = 0;

        Data += F("\nVoltage: ");
        Data += String(Voltage, 3);
        Data += F("\nCurrent: ");
        Data += String(Current, 3);
        Data += F("\nPower: ");
        Data += String(Power, 3);
        Data += F("\nConsumption: ");
        Data += String(Consumption, 3);
        //Serial.println(Data);

        radio.write(&Data, sizeof(Data));
        if (radio.write(&Data, sizeof(Data)) && true) {
          Serial.println("Sent!");
        } else {
          Serial.println("Failed!");
        };
        delay(10);
      }
    }

body:
Simple float transmission:

For TX use

    float payload = 0.12345;
    radio.write(&payload, sizeof(payload));

For RX use

    float payload = 0;
    radio.read(&payload, sizeof(payload));


message:
library mixing log4Esp & Syslog for esp8266

has someone finaly made a new lib combining log4esp and syslog
cf :
https://arduino.stackexchange.com/questions/52563/syslogappender-for-log4esp
thanks:!

body:
I did a rather **dirty** *(but efficient for my purpose)* job : While creating a new logger I declared and attached to it a log4esp formatter in which I sent ... syslog messages

*dirty dirty dirty*

my config constants are : `SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME`
<!-- language-all: cpp -->

My `logger.h`:

    #ifndef Logging_H
    #define Logging_H
    #include <Log4Esp.h>
    namespace Logging
    {
    void setup() ;
    log4Esp::Logger Logger(const char *name);
    }
    #endif

my `logger.cpp`:

    #include <Log4Esp.h>
    #include <Syslog.h>
    #include <WiFiUdp.h>
    #include <ESP8266WiFi.h>
    #include "Logger.h"
    #include "config.h"
    namespace Logging
    {
    // A UDP instance to let us send and receive packets over UDP
    WiFiUDP udpClient;
    // Create a new syslog instance with LOG_KERN facility
    Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN);
    //new logger
    log4Esp::Logger Logger(const char *name)
    {
      //new instance
      log4Esp::Logger logger = log4Esp::Logger(name);
      //minimal level
      logger.addLevelToAll(log4Esp::Appender::LOG_LEVEL);
      // formatting for serial logging
      logger.addFormatterToAll([name](Print & output, log4Esp::Appender::Level level, const char *msg, va_list * args) {
        ////////////////////////////////////////
        // serial log format
        // output uptime of this program in milliseconds
        output.printf("d", millis());
        output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
        // output free heap space
        output.printf("(%d)", ESP.getFreeHeap());
        output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
        // output logger name
        output.printf("%-4s", name);
        output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
        // output log level
        output.print(log4Esp::Appender::toString(level, true));
        if (level <= log4Esp::Appender::Level::ERROR) {
          output.print("***");
        } else {
          output.print("   ");
        }
        output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
        // determine buffer length for formatted data
        size_t length = vsnprintf(NULL, 0, msg, *args) + 1;
        char buffer[length];
        // output formatted data
        vsnprintf(buffer, length, msg, *args);
        output.print(buffer);
        ////////////////////////////////////////
        // Stop here if wifi is down
        if (WiFi.status() != WL_CONNECTED)
          return;
        ////////////////////////////////////////
        // format for syslog
        uint16_t slevel;
        switch (level) {
          case log4Esp::Appender::Level::FATAL    :
            slevel = LOG_CRIT;
            break;
          case log4Esp::Appender::Level::ERROR    :
            slevel = LOG_ERR;
            break;
          case log4Esp::Appender::Level::WARNING  :
            slevel = LOG_WARNING;
            break;
          case log4Esp::Appender::Level::VERBOSE  :
            slevel = LOG_INFO;
            break;
          case log4Esp::Appender::Level::TRACE    :
          default:
            slevel = LOG_DEBUG;
            break;
        }
        syslog.logf(slevel, "d|(%d)|%-4s|%s", millis(), ESP.getFreeHeap(), name, buffer);
      });
      return logger;
    }
    void setup() {

    }
    }


message:
Question about browsing the web using arduino

I have got an arduino, a TFT touch screen and a WIFI module. The question is can i visit a specific web site and display it on that screen and interact with it.

body:
You just have to install Chromium and call the desired page.

No, just kidding. I don't think you will ever fit a parsing and rendering engine on an arduino. Chromium for example takes about 150MiB of storage and depending on the opened page hundreds of MiB of RAM. Both of which is multiple orders of magnitude larger than the Arduino has to offer.

You might want to consider going to use a SBC like the Raspberry Pi for such usecase.

Alternatively you can query the data over network and write your own rendering code for the TFT display.


message:
Arduino button-controlled LED with AVR Assembly

I am trying to make a simple button-controlled LED, but I cannot seem to get any input from the button that would change the state of the LED. In other words, the program keeps branching to lighton, keeping the LED always on, regardless of the button state. I am using an Elegoo Uno R3.

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

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

Code:

.text
.global setup
.global loop

setup:
  ser r16
  sts DDRB, r16
  ldi r16, 0b00000000
  sts DDRD, r16
  ldi r16, 0b00100000
  sts PORTB, r16
  clr r16
  sts PORTD, r16

loop:
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  rjmp loop

Edit: I also implemented the method in https://stackoverflow.com/questions/39361410/creating-a-toggle-switch-in-avr-assembly to create a short delay with `r18` instead of `del`, but it didn't help; see revised loop method below:

loop:
  cpi r18, 0
  brne dec_jmp
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  ldi r18, 250
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  ldi r18, 250
  rjmp loop

dec_jmp:
  dec r18
  rjmp loop

With delay:

lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  call delay150
  ldi r16, 0b00000000
  sts PORTB, r16
  call delay150
  rjmp loop

body:
Fixed it with the below code for the loop:
<pre>
loop:
  sbic PIND, 2
  call nopressb
  ; button pressed
  ldi r16, 0b00100000
  out PORTB, r16
  rjmp loop
nopressb:
  ldi r16, 0b00000000
  out PORTB, r16
  rjmp loop
</pre>


message:
Arduino Voice recognition

Is it possible to use only arduino to do voice recognition? or maybe with esp32 no internet.

I found speech recognition chip but that's not what i want
I got esp32 esp8266 and arduino board.
I would like to know if somebody could do it

body:
No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).

A voice recognition chip generally is pre-programmed to respond to specific words.


body:
A simple speech (word) recognition can be done. I made one in 1998. Chip was atmega16. Now there are ready to use sound detectors and you just use digital out. https://s.click.aliexpress.com/e/cn6IwDhI
From that digital signal you get frequencies, durations and delays. First output results to serial and then get key features, ranges of voice command or a word. Put those boundaries to table and there you have it. It works like a charm with few words but then you have to make indexed database or something to keep it reasonable fast. I had only 8 commands and recognition was about 85% There were only 2 times when it "hear" some other word as a listed word. Language was finnish. I assume that it might lower those false positive occurrencies. As you see this is nothing compared to real systems but can be easily used in non critical solutions. ESP32 can do so much more that I think this might be interesting..
You may also want to look -> https://github.com/MhageGH/esp32_CloudSpeech


body:
Yes it is possible - see here for ESP32 example:

https://github.com/espressif/esp-adf/tree/master/examples/speech_recognition/asr


message:
Trouble understanding connection diagram

![https://imgur.com/a/dfR5LDj][1]

The image shows a way of connecting an optocoupler.
My problem comes from how the emitter (Q1 in the image) is connected. The emmiter goes to a resistance going to ground and to v_out. When i try to add this to my circuit the pin that is suppost to be receiving data, the v_out pin goes silent. If i remove the resistance going from the emitter to ground and just have vout to the emitter everything works fine.

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

body:
Normally you would connect the ground (0V) side of resistor R2 to the ground of the Arduino and the other side of R2 (which is also connected to the emitter of Q1) to an input pin of the Arduino. When the LED is energized by pressing the button it sends light to the fototransistor. Because of this the phototransistor starts conducting current (I1) which causes a voltage drop I1xR2 over R2. When this voltage is high enough the input pin will show a "1" (or HIGH) when read out.  "High enough" means >= 0.7 x Vcc, where Vcc is the voltage of the powerline to the Arduino.

The website from which the picture in your question originates (here) has an extensive article about the working and implementation of optocouplers. It also shows examples of alternative circuits.


message:
SD card initialization failed

i use the example sketch of SD card presented in Arduino IDE.
It runs well, but when i reboot my Adruino Mega by the reset button, the SD card initialization fails.
To fix it, i need to remove the SD card, insert it in his socket and reboot the board again. Then, SD card initialization is OK.
How can i update my code to try initialize the SD card until initialization is OK?
Also, can you explain me where come this bug ?

See the example SD card setup on the Arduino Mega:

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

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

body: I just add an external 9V power supply to my Arduino Mega. The SD device is power by arduino 5V pinout.


message:
Count fuel liters with Arduino

We have created a fuel sensor in our lab with Arduino in order to get fuel data from vehicles. Regarding the code below, I receive an error

> PARSE ERROR: 'attachInterrupt': this function needs to be defined.

Could you please advice?

    int pin = 2;
    volatile unsigned int pulse;
    float volume = 0;
    float flow_rate =0;
    const int pulses_per_litre = 2000;
    int count_pulse;

    void setup()
    {
     Serial.begin(9600);
     pinMode(pin, INPUT);
     attachInterrupt(0, count_pulse, RISING);

    }

    void loop()
    {
     pulse=0;
     interrupts();
     delay(1000);
     noInterrupts();

     Serial.print("Pulses per second: ");
     Serial.println(pulse);

     flow_rate = pulse * 1000/pulses_per_litre; //

     Serial.print("FUEL FLOW rate: ");
     Serial.print(flow_rate);
     Serial.println(" milliliters per second");

     volume = volume + flow_rate * 0.1; //Time Interval is 0.1 second

     Serial.print("Volume: ");
     Serial.print(volume);
     Serial.println(" milliliters");
    }

    void count_pulse()
    {
    pulse++;}

body:
Just initialize `pulse` to zero in its definition at line 2.

The message "'pulse': used without being explicitly initialized" is due to the count_pulse() function: The compiler can't analyze the run-time behavior of the code, nor your intentions. Some interrupts could arrive before loop() runs, so in fact, `pulse` could very well get incremented without having been initialized. You may not care about and can discard the first few readings, but the compiler doesn't (and shouldn't!) guess that.


body:
You have declared `count_pulse` as a variable and NOT as function prototype.

    int pin = 2;
    volatile unsigned int pulse;
    float volume = 0;
    float flow_rate =0;
    const int pulses_per_litre = 2000;

    void count_pulse(); \\ <--- Function prototype

    void setup()
    {
        Serial.begin(9600);
        pinMode(pin, INPUT);
        attachInterrupt(0, count_pulse, RISING);
    }


message:
Arduino MEGA Timer Help

Nick Gammon posted some code to setup a counter on an Arduino UNO using timer2 to generate a 38KHZ signal, and I've used it on several IR projects.

On my current project, I'm using FreeRTOS for the Arduino, and the source says it uses timers 0-3 for its own kernel operation, so the timer code obviously will interfere with the RTOS.

I'm using an Arduino MEGA for this project, and AFAICT it also has a timer4 and timer5. Unfortunately, my programming ability for the ATMel products is lacking at that level, so I'm looking for some help to create a timer that will generate a 38KHZ output using timer4 or timer5 of the MEGA 2560 on any output pin. Interrupts shouldn't be used because it would also probably cause issues with RTOS.

BTW, on the Arduino MEGA, you can do a context switch between tasks in less that 200usec, and be able to determine what task YOU want to execute next.

body:
Using a pre-emptive Real Time Operating System on a Arduino board with a AVR microcontroller (Arduino Uno, Leonardo, Mega 2560) is an academic exercise.

The FreeRTOS is reliable, and for someone that is used to write multitasking code, it can be useful.
In my opinion, the FreeRTOS does not match with the simple AVR Arduino boards:

 - Not enough ram memory.
   Every task gets its own stack.
   The ram memory is limited on a AVR board. That means that every
   task should be written very careful to limit the stack usage.
 - Not enough ram when the fun is about to start.
   When there are a few tasks and perhaps a few interrupt routines,
   then a number of buffers and message queues are needed.
   There is not enough ram memory for that.
 - The Arduino was not developed with a multitasking system in mind.
   The Arduino libraries are not suitable for that.
   Some functions wait
   for something (Serial.parseInt, Wire.requestFrom,
   Wire.endTransmission)
   and that makes a RTOS work worse than expected.
 - The FreeRTOS is large, it requires memory and cpu time.

Without FreeRTOS, some known techniques are very efficient for the AVR Arduino boards:

 - A Finite State Machine uses very little ram memory.
   A Finite State Machine without `delay()`
   that uses `millis()` can be very responsive.
 - Avoiding interrupt routines.
   It is often possible to avoid interrupt routines.
   Reading buttons can often be done by polling the buttons
   in the `loop()`.
 - Avoiding the String object and moving text into PROGMEM
   can be used
   to have enough memory for a more complex and reliable sketch.

At this moment the "FreeRTOS by Richard Barry" is in the Library Manager. It is a smaller version of FreeRTOS and it only uses the WatchDog timer. It has no conflict with Arduino libraries.

A larger FreeRTOS version and many examples can be found at https://github.com/feilipu/avrfreertos
Not every version of FreeRTOS uses the WatchDog timer. Look for the file `FreeRTOSBoardDefs.h` to see which timer is used for your specific Arduino board.

crusader27529, I don't see a problem to remove the FreeRTOS and call the three tasks sequencially.

    void loop() {
      task1();
      task2();
      task3();
    }


message:
Confusion between switch and if?

Following code is to control two LEDs for on and off by two dedicated push buttons. I have used `if()` for each condition and I was not comfortable writing this code, as I could feel, it can be better with `switch...case`, because if we increase more buttons, it will be a messy solution for that. However, I couldn't get optimized `switch...case` for it. Can some one suggest the nice switch transformation for this `if()`.

    int buttonState1 = 0; // variale for reading pushbutton1 status
    int buttonState2 = 0;  // variable to reading push button2 status
    //set pin numbers
    int button1 = 2; // push button no. 1
    int button2 =3;  // push button no. 2
    int Led1 = 4; // led 1
    int Led2 =5;  // led 2

    void setup() {
      Serial.begin(9600); // serial begins at 9600
      // defining pin modes for led and buttons
      pinMode(button1, INPUT);
      pinMode(button2, INPUT);
      pinMode (Led1, OUTPUT);
      pinMode (Led2, OUTPUT);
    };

    void loop() {
     buttonState1 = digitalRead(button1); // reading pushbutton 1 in the variable buttonstate1
     buttonState2 = digitalRead(button2); // reading pushbutton 2 in the variable buttonstate2
     // condintion for led 1 ON, if pushbutton1 is pressed
     if (buttonState1 == HIGH) {
      digitalWrite(Led1, HIGH);
      }
      // condition for led2 ON, if pushbutton2 is pressed.
     if (buttonState2 ==HIGH){

      digitalWrite(Led2, HIGH);

      }
      // both led are off if no push button is pressed
      else{
        digitalWrite(Led1, LOW);
        digitalWrite(Led2, LOW);
      }

    };

body:
A switch case does not seem like it would be an effective way of controlling your LEDs. It would make more sense (and would probably be easier) to create a function instead to control the LEDs.

    void buttonToggle(int buttonPin, int ledPin) {
      int buttonState = digitalRead(buttonPin);
      if(buttonState == HIGH) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
    }

You would then need to replace your `if` statement with calls to the function (EX `buttonToggle(Button1, Led1);`


body:
If you want to use a dedicated push button for every led, then it is not handy to use a switch .. case statement. This is because first you have to construct the switch-variable based on the readings of the switches before you can use it (the switch variable) for de case statements.

When you combine the reading of the switches with the setting of the leds you get a nice Loop-section:

        void loop() {
          digitalWrite(Led1, digitalRead(button1));
          digitalWrite(Led2, digitalRead(button2));
          digitalWrite(Led3, digitalRead(button3));
          digitalWrite(Led4, digitalRead(button4));
          digitalWrite(Led5, digitalRead(button5));
          // and so on
        }


message:
ATMEGA 328P Standalone on 3.3v controlling a servo

I'd like to use an ATMEGA 328P on standalone mode powered by a 3.3V supply source to control a servo (which is powered by 4 AA batteries, resulting in 6V). My question is: do I have to convert the PWM signal's peak amplitude to 5V for it to work? Or will the servo work just fine with a 3.3V amplitude signal? My servo's datasheet says its operation voltage ranges from 4.8V to 6V, but I'm not sure if that applies only to its power source or if it has implications on the control signal as well.

Servo's datasheet:
https://www.donkeyhoute.com/UploadFiles/2014916134245511.pdf

Also, since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency, or do I just set the board to the 'Lilypad' option when burning the bootloader and keep the sketch the way it is now?

body:
> do I have to convert the PWM signal's peak amplitude to 5V for it to work?

There is insufficient information to determine that.  It may, or it may not. You'll have to try it and see.

> since I will be using an 8 MHz external clock, do I have to change anything in my Arduino sketch regarding the PWM signal frequency

If the board you select is 8MHz then no, you don't need to change anything. The fact you have selected the right frequency for the board means that all the timing calculations the Arduino API does will be correct.


message:
Addressable RGB LED Strip

I am looking to create an addressable RGB LED strip circuit with my NodeMCU v3 Wi-Fi. I am looking at a strip of 150 RGB LEDs, 5 meters long, so 30 LED/m. But I am only going to use about 50 LEDs for the backlight on my desk. My understanding is that if each RGB LED pulls 60 mA on full white, and I'm running 50 LEDs, then I will need at least 60 mA x 50 LEDs = 3000 ms (3 A) of power to sufficiently light all of them. I am thinking about upgrading this in the future, and so I am thinking about going with a 5V 10A power supply. Am I okay to go with a 5 V 10 A power supply? Or will this be too much current for the system.

body:
Each will only draw as much current as they normally would from a 5 volt supply. If you had a 5 volt 100 amp supply they still would not draw any more.

The amount of excess current a power supply can deliver doesn't change what the load will take from that supply.

For example, if you had a 5 volt supply with a 1 ohm resistor as a load the current would be 5 amps. 5 volts / 1 ohm = 5 amps. And if you had a 5 volt 10 amp supply the current would still be 5 amps. Same with a 20 amp supply. As long as the voltage is the same, going up in current capacity is safe.

(LEDs are not resistors but with this application it is much the same)

When you do wire up the LED strips make sure you are using thick enough wires.


message:
Maze solving robot turning failure due to sensor distance to the corner increasing during the turn

At my school we have a project where we have to make a robot that can solve a 3D-maze using an arduino controlled robot that uses ultrasonic sensors to determine how to turn. The robot may not be pre-programmed and must work on all simple mazes with 90d turns.

I have figured out most of the code I think, however my problem is that when the robot needs to turn. Since how much and which direction the robot should turn is determined by distance sensors, the distance to the corners increase, making it longer than what is required to turn. This makes the robot want to turn back into the corner and then it gets stuck in a loop of turning in and out of the corner (see image attached).

Note: we don't want to program a 90d turn as it could mess up later and we believe it better to try make how long the robot should turn be determined by the value of the different sensors.

The robot is made up of three ultrasonic sensors, front, right, and left. The robot has tracks which lets it turn on the spot. The arduino is an arduino mega, so it is fast at updating and measuring values (unless the time needed for measuring the distance is long).

Files:

![The maze (.sldprt if wanted)][1]

Pictures describing the turning problem:

![robot before the corner][2]

![turning problem image 1][3]

![turning problem image 2][4]

Images of the robot:

![front of robot][5]

![right of robot][6]

![left of robot][7]

If any other information is needed that is left out, I will try to obtain it (such as images, dimensions, exact component names, etc.)

The entire code:

    enum robState {
      robInit,
      robInitForward,
      robInitRotL,
      robInitRotR,
      robStop,
      //robWaitCrystals,
      robInitBack,
      robReset,
      robFindWay
    };

    struct LFR {
      int L;
      int F;
      int R;
    };

    struct robMotor {
      byte pwm;
      byte dir_1;
      byte dir_2;
    };

    robState robStatus;
    //const int robTurnSpeed = 255;
    robMotor motorL = {2, 4, 3};
    robMotor motorR = {5, 6, 7};

    int dirInt = 1;
    LFR echoPin = {12, 11, 13};
    LFR trigPin = {24, 26, 22};
    LFR distance;
    const int robStartStopPin;

    void setup() {
      // put your setup code here, to run once:

      //init pinModes
      initPins();

      Serial.begin(9600);
      robStatus = robInit;
    }

    void loop() {
      int disWall = 12;
      // put your main code here, to run repeatedly:
      distance.L = distanceUpdater(trigPin.L, echoPin.L);
      distance.F = distanceUpdater(trigPin.F, echoPin.F);
      distance.R = distanceUpdater(trigPin.R, echoPin.R);
      Serial.print("/n distance.L= ");
      Serial.println(distance.L);
      Serial.print("/n distance.F= ");
      Serial.println(distance.F);
      Serial.print("/n distance.R= ");
      Serial.println(distance.R);
      //delayMicroseconds(50);

      switch (robStatus) {

        case robInit:
          //init motors and shit
          motor(0, 0);
          motor(1, 0);
          //wait for start/stop
          //while (digitalRead(robStartStopPin) == LOW);
          Serial.print("/n robInit");
          robStatus = robFindWay;
          break;

        case robInitForward:
          motor(0, 1);
          motor(1, 1);
          Serial.print("/n robInitForward");
          robStatus = robFindWay;
          break;

        case robFindWay:

          Serial.print("/n robFindWay");
          if (distance.R > disWall) {
            //if open to right, turn right.
            robStatus = robInitRotR;
          }
          else if ((distance.R < disWall) && (distance.F > disWall)) {
            //go forward if you can't go right
            robStatus = robInitForward;
          }

          else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L > disWall)) {
            //if nothing else works, turn left.
            robStatus = robInitRotL;
          }
          else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L < disWall)) {
            //found the end, must turn. turns left.
            robStatus = robInitRotL;
          }
          else {
            Serial.print("shit somethings wrong with path finding");
          }
          break;

        case robInitRotL:
          Serial.print("robInitRotL");
          //forward direction of motorR
          motor(1, 1);
          //reverse direction of motorL
          motor(0, -1);
          //send the correct motor speed*/
          robStatus = robFindWay;
          /*analogWrite(motorR.pwm, robTurnSpeed);
            analogWrite(motorL.pwm, robTurnSpeed);*/
          break;

        case robInitRotR:
          Serial.print("robInitRotR");
          //reverse direction of motorR
          motor(1, -1);
          //forward direction of motorL
          motor(0, 1);
          //send right motor speed
          robStatus = robFindWay;
          /*analogWrite(motorR.pwm, robTurnSpeed);
            analogWrite(motorL.pwm, robTurnSpeed);*/
          break;

        case robStop:
          motor(0, 0);
          motor(1, 0);
          //while (digitalRead(robStartStopPin) == LOW);
          robStatus = robInit;
          break;

        case robInitBack:
          //reverse both motors
          motor(0, -1);
          motor(1, -1);
          break;
      }

    }

    void initPins() {
      //init motors
      pinMode(motorL.pwm, OUTPUT);
      pinMode(motorL.dir_1, OUTPUT);
      pinMode(motorL.dir_2, OUTPUT);

      pinMode(motorR.pwm, OUTPUT);
      pinMode(motorR.dir_1, OUTPUT);
      pinMode(motorR.dir_2, OUTPUT);
      //init sensors
      pinMode(trigPin.L, OUTPUT);
      pinMode(trigPin.F, OUTPUT);
      pinMode(trigPin.R, OUTPUT);

      pinMode(echoPin.L, INPUT);
      pinMode(echoPin.F, INPUT);
      pinMode(echoPin.R, INPUT);
      //init button
      pinMode(robStartStopPin, INPUT);
      //init power sources
      /*pinMode(VCCPin1, OUTPUT);
      digitalWrite(VCCPin1, HIGH);
      pinMode(GNDPin1, OUTPUT);
      digitalWrite(GNDPin1, LOW);*/
    }

    void motor(int side, int action) {
      //side 0=L 1=R
      //action -1=reverse 0=still 1=forward
      int normalSpeed = 255;
      if ((side == 0) && (action == -1)) {
        //reverse left
        digitalWrite(motorL.dir_1, LOW);
        digitalWrite(motorL.dir_2, HIGH);
        analogWrite(motorL.pwm, normalSpeed);
      }
      else if ((side == 0) && (action == 0)) {
        //still left
        digitalWrite(motorL.dir_1, HIGH);
        digitalWrite(motorL.dir_2, LOW);
        analogWrite(motorL.pwm, 0);
      }
      else if ((side == 0) && (action == 1)) {
        //forward left
        digitalWrite(motorL.dir_1, HIGH);
        digitalWrite(motorL.dir_2, LOW);
        analogWrite(motorL.pwm, normalSpeed);
      }
      else if ((side == 1) && (action == -1)) {
        //reverse right
        digitalWrite(motorR.dir_1, LOW);
        digitalWrite(motorR.dir_2, HIGH);
        analogWrite(motorR.pwm, normalSpeed);
      }
      else if ((side == 1) && (action == 0)) {
        //still right
        digitalWrite(motorR.dir_1, HIGH);
        digitalWrite(motorR.dir_2, LOW);
        analogWrite(motorR.pwm, 0);
      }
      else if ((side == 1) && (action == 1)) {
        //forward right
        digitalWrite(motorR.dir_1, HIGH);
        digitalWrite(motorR.dir_2, LOW);
        analogWrite(motorR.pwm, normalSpeed);
      }
      else {
        Serial.print("monkaS wrong motor inputs");
      }
    }

    int distanceUpdater(int trigPin, int echoPin) {
      long duration;
      int distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration * 0.034 / 2);
      return distance;
    }

The pathfinding and turning:

    switch (robStatus) {

        case robInit:
          //init motors and shit
          motor(0, 0);
          motor(1, 0);
          //wait for start/stop
          //while (digitalRead(robStartStopPin) == LOW);
          Serial.print("/n robInit");
          robStatus = robFindWay;
          break;

        case robInitForward:
          motor(0, 1);
          motor(1, 1);
          Serial.print("/n robInitForward");
          robStatus = robFindWay;
          break;

        case robFindWay:

          Serial.print("/n robFindWay");
          if (distance.R > disWall) {
            //if open to right, turn right.
            robStatus = robInitRotR;
          }
          else if ((distance.R < disWall) && (distance.F > disWall)) {
            //go forward if you can't go right
            robStatus = robInitForward;
          }

          else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L > disWall)) {
            //if nothing else works, turn left.
            robStatus = robInitRotL;
          }
          else if ((distance.R < disWall) && (distance.F < disWall) && (distance.L < disWall)) {
            //found the end, must turn. turns left.
            robStatus = robInitRotL;
          }
          else {
            Serial.print("shit somethings wrong with path finding");
          }
          break;

        case robInitRotL:
          Serial.print("robInitRotL");
          //forward direction of motorR
          motor(1, 1);
          //reverse direction of motorL
          motor(0, -1);
          //send the correct motor speed*/
          robStatus = robFindWay;
          /*analogWrite(motorR.pwm, robTurnSpeed);
            analogWrite(motorL.pwm, robTurnSpeed);*/
          break;

        case robInitRotR:
          Serial.print("robInitRotR");
          //reverse direction of motorR
          motor(1, -1);
          //forward direction of motorL
          motor(0, 1);
          //send right motor speed
          robStatus = robFindWay;
          /*analogWrite(motorR.pwm, robTurnSpeed);
            analogWrite(motorL.pwm, robTurnSpeed);*/
          break;

        case robStop:
          motor(0, 0);
          motor(1, 0);
          //while (digitalRead(robStartStopPin) == LOW);
          robStatus = robInit;
          break;

        case robInitBack:
          //reverse both motors
          motor(0, -1);
          motor(1, -1);
          break;
      }

  [1]: https://i.stack.imgur.com/ZnxlY.jpg
  [2]: https://i.stack.imgur.com/1f4N7.png
  [3]: https://i.stack.imgur.com/aSsD6.png
  [4]: https://i.stack.imgur.com/oC8bW.png
  [5]: https://i.stack.imgur.com/XnrUx.jpg
  [6]: https://i.stack.imgur.com/DMmLJ.jpg
  [7]: https://i.stack.imgur.com/NHI8S.jpg

body:
Your main loop (`loop()`) is powering through the whole code continuously. It wouldn't be a bad idea to put some "breaks" between each sensor scan cycle. For example:

<!-- language: c -->

    long timerCounter = 0;

    void setup()
    {
        // Do your setup here

        timerCounter = millis();
    }

    void loop()
    {
        // Only do some code every 1 second (1000ms)
        if (millis() - timerCounter >= 1000)
        {
            ScanSensor1();
            ScanSensor2();
            ScanSensor3();

            robState state = DetermineStateFromSensorReadings();

            DoActionForState(state);
        }
    }

What this does is break the cycle down to 1Hz (change as you wish). When you are using ultrasonics (as per your images), it's always a good idea to reduce the intervals between each reading, as it allows residual noise to quieten down. Imagine the beeping sound from the sonar on a submarine.

You've got the right idea by using a state machine in your code. Each cycle can determine which state it should be in after reading the sensor data. Good job on that!

Just some additional information about ultrasonics regarding your project:

- Sonar has an emission angle of 30 degrees (not a straight line!). Imagine a code pointing out with an angle of 30 degrees. This means anything inside this range could be picked up by the sensor. Looking at your _turning problem image 2_, I'd expect a lot of erroneous data from that sensor pointing towards the corner.
- Multiple sensors working at the same frequency (40kHz?) may interfere with each other.

The problem you are seeing is mainly caused by the fact that you are checking the walls around you as you are turning. I would suggest you use either the forward facing sensor or the opposite sensor to that in _turning problem image 2_ to significantly reduce erroneous data.

If your budget (and time) allows, you may benefit from using a cheap Lidar (like [this one](https://www.adafruit.com/product/3317) for example) to more accurately determine your surrounding. Lidar doesn't have an emission angle, which means that it's measurement point is in a straight line from the source.


body:
You need two states. Making a turn and not making a turn.

Once you start making a turn, ignore the side sensors, and continue turning until *the front sensor distance has reached its peak*.


message:
Remotely uploading code to an Arduino board over the internet

I recently used [Particle Photon][1] that allows me to upload firmware (.bin file) [remotely over the internet][2].

I would like to use something like this for my Arduino but I cannot find anything like that. Does anyone know any possible way to upload firmware to my Arduino board remotely connected to internet via Ethernet shield of any WiFi module?

  [1]: https://www.particle.io/
  [2]: https://docs.particle.io/support/troubleshooting/firmware-upgrades/electron/

body:
This will do it. ESP8266 as wireless AVR (arduino) ISP programmer.

https://github.com/rene-win/esp_avr_programmer

or

https://github.com/jeelabs/esp-link

The ESP8266 can be programmed with the Arduino IDE. So it can be used for a lot of Arduino projects. And it can be OTA (Over The Air) programmed as well.

https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html


body:
You can upload to your Arduino board over Ethernet if you flash it with a special bootloader named Ariadne.

You will need an Ethernet module or shield that uses the W5100, W5200, or W5500 Ethernet controller chip. You can not use the ENC28J60 Ethernet controller with Ariadne.

You will need an ISP programmer to burn the Ariadne bootloader to your Arduino board. If you don't own an ISP programmer, you can use a spare Arduino board as an ["Arduino as ISP" programmer](https://www.arduino.cc/en/Tutorial/ArduinoISP). If you're going to purchase an ISP programmer, I recommend the 6 pin USBasp. The USBasp works well with the Arduino IDE and is very reasonably priced. You can buy them on eBay.

A description of how the Ariadne upload over Ethernet process works:

1. Compile the sketch you want to upload.
1. Use avr-objcopy to convert the .hex file of the sketch generated from the Arduino IDE compilation into a binary (.bin) file.
1. Reset the Arduino board to activate the bootloader code. You could do this by pressing the reset button on the board but the need to have physical access to the board negates much of the advantages of uploading over Ethernet. For this reason, the upload will typically be accomplished by sending a command to your Arduino board which triggers the application to reset the microcontroller by activating the watchdog timer and then allowing it to time out. There is a library named EthernetReset bundled with the Ariadne hardware package for this purpose, but you can easily implement your own solution if you have other needs.
1. Start a TFTP upload of the .bin file to the IP address of your Arduino board within the 10 seconds that the bootloader is activated after the reset. The upload doesn't need to finish within the 10 second window, it only needs to start.

You can get the Ariadne bootloader, as well as detailed instructions, here:
https://github.com/loathingKernel/ariadne-bootloader


message:
how to compile arduino sketch from termnial without using arduino ide

I want to know how can I compile and upload the arduino sketch from my terminal instead of using Arduino IDE. I want to use a different IDE for writing code.

body:
As a contributor to [Sloeber][1], an Eclipse Plugin dedicated to Arduino and other micro controllers, I can tell you it's all a matter of using the correct version of `gcc` and provide the correct options.

Even if that might seem simple, it's not like that, so my advice is to download Sloeber and look at the build console output where we print all the statements used to fulfill the build task: you can infer a lot from that.

As Sloeber is also open source, you can also inspect how we create those build commands for the different boards and tool chains.

  [1]: http://sloeber.io


body:
I have been using PlatformIO for about 2 years now I think. It’s simply amazing.

https://platformio.org

You can use it standalone just for the CLI compile or bundled with VisualCode Studio for a complete IDE solution.


message:
Defining array in switch case

I’m completely new to arduino, so be polite. I’m trying to program my esp32 to drive neopixels as seven segment display. So I take a digit and pass it to switch case and in switch case I mention which led number should be lit.
`

    function showDigits(digit){

    switch(digit){

     case 1:
       int a[]={1,3,4,.....};
      break;

     case 2:
        int a[]={1,3,4,6,8,...};
       break;
      .
      .
      .
    default:
       int a[]={1,2,3,4,5,6,7,8,9,....};
      }
    }

Now this is throwing multiple errors including redeclare of array a in same scope. Is there any better way to code this?

body:
While I don't discourage you from doing it yourself. I would go the easy route and use an available library. As is, or if need be, after modifying it. For me, it is the better way as I'm not that good at programming.

https://learn.adafruit.com/adafruit-neopixel-uberguide/neomatrix-library

And this looks good.

**FastLED NeoMatrix**
> Better support for ESP32 than Adafruit::Neopixel

https://github.com/marcmerlin/FastLED_NeoMatrix


body:
If you want to declare multiple variables with the same name inside different case statements, you can enclose the code inside each of them inside curly braces:

    case 1:{
        Code...
    break;}
    case 2:
    ...

The curly braces will set the limits for the variables scope to just this case.


body:
I see several issues with your code.

First one is the issue of "scope". If you define the `int a[]` inside the `switch` it will be destroyed as soon as the `switch` will finish and no code that runs outside of its brackets will be able to access it.

I also think that array of `integers` is the wrong choice here. It would be much less memory consuming to use array of `boolean` that mean if each LED should be lit or not. You can use it later like that:

    if (a[4]) { digitalWrite(LED4, HIGH); } else { digitalWrite(LED4, LOW); }

or even better using "ternary operator":

    digitalWrite(LED4, (a[4] ? HIGH : LOW));

Third problem is that your function is incorrectly defined and it does not contain any type information. This is C and not Python so the types are EXTREAMLY important! The correct definition of your function should be:

    void showDigits(int digit)

Take a look at this example that compiled correctly:

    void showDigits(int digit)
    {
      bool a[6] = {false, false, false, false, false, false};
      switch (digit)
      {
        case 1:
          a[0] = true;
          a[1] = false;
          break;
        case 2:
          a[1] = false;
          break;
        default:
          a[0] = true;
      }

      if (a[4]) {
        digitalWrite(4, HIGH);
      } else {
        digitalWrite(4, LOW);
      }
    };

The `switch..case` is a very particular syntax. If you don't use the `break;` at the end of a `case` the execution will actually continue to next `case` definition, and compiler told you that you tried to define `int a[]` several times in the same scope. (which is a no-no)


message:
Unexpected behavior of ++myCount

I'm new to Arduino and C.
This behavior is not what I'd expect:

    Serial.begin(9600);
    while ( ! Serial );

    int myCount = 0;

    for (int i=0; i<10; i++) {
        myCount = min( ++myCount, 8 );
        Serial.print( myCount );
        Serial.print( "  " );
    }

I would expect:

    1  2  3  4  5  6  7  8  8  8

But I get:

    2  4  6  8  8  8  8  8  8  8

Why is my code counting by 2?

body:
Jaromanda X is indeed correct - `min()` is defined on line 92 of [Arduino.h][1], thusly:

    #define min(a,b) ((a)<(b)?(a):(b))

Therefore when the `++mycount` is substituted for the `a`, it is in fact substituted *twice*, in both the `(a)<(b)` *and* the `(a):(b)`, leading to the increment by 2, each time `min(++mycount,8)` is executed.

As VE7JRO mentions, as it is defined in this way, the [reference for `min(x,y)`][2] states:

> **Warning**
>
> Because of the way the min() function is implemented, avoid using
> other functions inside the brackets, it may lead to incorrect results
>
>
>     min(a++, 100);   // avoid this - yields incorrect results
>
>     min(a, 100);
>     a++;            // use this instead - keep other math outside the function

As the second example states, keep *any* incrementing *outside* of the `min()` macro.

Alternatively, I think that you could use the `inline` function to workaround this issue:

    #undef min
    inline int min(int a,int b) {return ((a)<(b)?(a):(b)); }

Because `inline` provides a *real* function call (with parameters) it avoids the use of macros and substitution, which gives rise to the issue that you encountered.

`inline` is a much better (safer) way to implement the functionality provided by macros, in many cases. For more information, see [Inline functions in C++][3] or read a C++ reference.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h
  [2]: https://www.arduino.cc/en/Reference.Min
  [3]: https://www.geeksforgeeks.org/inline-functions-cpp/


message:
Idenitifying pins in my code. which pin is which?

I'm new to arduino and knnow nothing about electronics.
How do I idenitify which pin is which in the coding?
eg- I have a pin on my esp8266 "D3"... how would I reference that in the code?

body:
If you select the right board in Tools menu, you can use constants corresponding to labels.

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


message:
Control I2C relay board from two Arduino Uno

how can I make multi master Arduino device to work with single I2C device?
As both the master device are 20 m away from Slave device,

I am using the [I2C relay board][1] to connect with 2 Arduino boards and need to connect I2C device and create the two way switching technique from this.

Any suggestions here will be a great help.

  [1]: https://store.ncd.io/product/8-channel-general-purpose-spdt-relay-controller-with-i2c-interface/

body:
What you want is to operate in *multi-master* mode.  This is a supported configuration of I2C - however the Arduino API has no support for it.

It involves each master identifying if a collision has occurred and stopping transmission if it has - to then retry transmission later on.

The Arduino hardware can do it, but the software can't. You would have to bypass the software and control the I2C interface yourself (or locate a better library than the Wire library that supports multi-master).


body:
The `Wire` library has no complete multi-master support (as I remember). You can join the bus as slave and becoming master by using the master functions for the time of these transmissions (on execution of `endTransmission()` the master style I2C transmission is started. When it's finished the library will change to slave again). But you will run into problems, when the two masters send at the same time.

The I2C protocol incorporates a technique named bus arbitration. When two masters write to the bus at the same time, the first one to write a `1` on the bus, must retreat from transmission and become slave again. Unfortunately it seems, that the `Wire` library doesn't implement this.

So you might not run into problems, until the master are sending simultaneously. Depending on what the Arduinos also have to do, you may be able to recover from such a condition by using the Watchdog Timer to reset both masters, when they are stuck there.

Or you try to find a good I2C/TwoWire library, that works for Arduino and has Bus arbitration implemented.

---

Sidenote: 20m is quite a long distance for I2C. It is designed for short distances, mostly on the same PCB (hence it is called Inter Integrated Circuit, short IIC or I2C). You may not run into issues, but you should keep this in mind. The bus will have a greater capacitance and you may need strong pullup resistors.


body:
The answers by Majenko and chrisl are far too optimistic in my opinion.

A distance of 20 meters is not possible. The I2C bus can be 20 cm or 50 cm.

There is no library that supports a multi-master bus for the Arduino Uno.

You have to change your project. Make one Arduino board the Master, and let the Master retrieve data from the other board and the Master writes to the relay board. You need a bus capable of such a distance or use wireless. The RS-485 bus has no problems with 20 meters. Adafruit has a number of RFM69 modules, those should have no problem with 20 meters.

----------

There are chips that translate the I2C bus signals into differential signals that can be used with a twisted pair cable (for example a cheap Cat5 ethernet cable). The [SparkFun Differential I2C Breakout][1] makes it easy to put a I2C device at a longer distance.
(*Thanks to @PimV for this addition*).

  [1]: https://www.sparkfun.com/products/14589


message:
4 digit 7 segments display wrong number

I'm an Arduino newbie having problems with 4 digit 7 segments display.
I want to display some thousands to 4 digit 7 segments display but it display only 0000.
I want to receive data from serial with string. And display the data to 4 digit 7 segments display... So test make String = '2575'... but it's not work.
What's wrong in my codes?
Any suggestions here will be a great help. thanks

    int segments[] = {A0, A1, A2, A3};

    byte digits[10][7] =
    {
      { 1,1,1,1,1,1,0 }, // 0
      { 0,1,1,0,0,0,0 }, // 1
      { 1,1,0,1,1,0,1 }, // 2
      { 1,1,1,1,0,0,1 }, // 3
      { 0,1,1,0,0,1,1 }, // 4
      { 1,0,1,1,0,1,1 }, // 5
      { 1,0,1,1,1,1,1 }, // 6
      { 1,1,1,0,0,0,0 }, // 7
      { 1,1,1,1,1,1,1 }, // 8
      { 1,1,1,0,0,1,1 }  // 9
    };

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

      for(int i=2;i<10; i++) {
        pinMode(i, OUTPUT);
      }

      for(int i=0; i<4; i++) {
        pinMode(segments[i], OUTPUT);
      }
    }

    void loop() {
      String IncomingData = "2575";

      for(int i=0; i<4; i++) {
        digitalWrite(segments[i], LOW);
        int digit = atoi(IncomingData[i]);
        displayDigit(digit);
        delay(5);
        digitalWrite(segments[i], HIGH);
      }
    }

    void displayDigit(int num){
      int pin = 2;
      for(int i=0;i<7;i++){
        digitalWrite(pin+i, digits[num][i]);
      }
    }

body:
You call `atoi()` with a char. Parameter of `atoi` is `const char*`. To convert ASCII code of digit to the digit use

`int digit = IncomingData[i] - '0'`