body:
There are 5 ESP8266s being used. Three act as a middleman (in AP_STA mode), one sends the message, and the last one receives the message after being passed over the middlemans (imagine it as a line, starting with nr. 1 in STA mode, sending the date to middleman 1. M1 sends it to M2, M2 sends it to M3, M3 sends it to the receiver, set in AP mode).

After like 10 min. of sending a message, one chip always stops. Stops as in, not receiving or sending the message. Every time a message is send, I use the command `Client21.flush()` (Client21 is just a name).

My idea is that I have to somehow also flush() after recieving a message, not just after sending one. Is there like a "receive buffer" that I can `flush()`, and how is it possible?

(no code provided)

**Update 1:** This is what the first middleman (chip no.3) printed in serial monitor when he "crashed":

    Exception (29):
    epc1=0x4000e1c3 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000018 depc=0x00000000

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

    stack
    3fffed60:  3fffc278 40101fe8 3fffc200 00000000
    3fffed70:  3ffed93c 3fffb374 000000c0 401004e4
    3fffed80:  40000f83 3fffb374 402384b0 401068b0
    3fffed90:  402268ac 00000023 00000000 402268d1
    3fffeda0:  000000c0 4021403b 00000018 3ffed6cc
    3fffedb0:  00000000 00000000 00000020 40100f22
    3fffedc0:  4021881e 4021873c 3ffef80c 40100f22
    3fffedd0:  01004e43 4010000d 3ffee034 4021cb7d
    3fffede0:  00000018 3ffed750 3ffed6cc 00000000
    3fffedf0:  402188df 3ff20a00 3ffef80c 3ffe9be6
    3fffee00:  3ffe9bcc 3fffee90 3fffee90 00000000
    3fffee10:  4c4c4148 3331324f 40102200 3ffe9bcc
    3fffee20:  3ffe9be6 0000002c 00000004 40100518
    3fffee30:  3ffe9bd6 3ffefc74 402154a0 3ff20a00
    3fffee40:  3ffef80c 3fffbfcc 00000015 40215373
    3fffee50:  4000050c 3ffef45c 00000000 4021b377
    3fffee60:  40106afd 00000030 00000011 ffffffff
    3fffee70:  00000000 4bc6a7f0 7645a1ca 00000000
    3fffee80:  00000000 00000000 4bc6a7f0 00000000
    3fffee90:  4020cb8c 3ffe8f84 40106520 00190810
    3fffeea0:  00000000 4bc6a7f0 3ffe8f84 40212cbc
    3fffeeb0:  1cf15308 00000000 00000002 4020bad8
    3fffeec0:  4021d149 ffffffa2 00000000 000001f4
    3fffeed0:  40214baf 3ffe9bcc 3ffecd80 3ffef80c
    3fffeee0:  00000000 3ffe9bd6 3ffe9bf0 3ffeeec4
    3fffeef0:  4020cb8c 00000000 00000000 3ffe9bd6
    3fffef00:  61c78017 000000c3 00000000 3ffefc74
    3fffef10:  3ffe9bc0 00000000 00000002 4022463a
    3fffef20:  3ffecd80 3ffe9bc0 3fffdcc0 3ffe9370
    3fffef30:  3ffe9bdc 3ffefab4 00000040 3ffe9370
    3fffef40:  00000040 3ffecd80 00000000 3ffe85e0
    3fffef50:  40223f17 3fffdab0 00000000 40204ac7
    3fffef60:  3ffe9370 40000f49 3fffdab0 40000f49
    3fffef70:  40000e19 40001878 00000002 00000000
    3fffef80:  3fffff10 aa55aa55 0000008f 40104424
    3fffef90:  4010442a 00000002 00000000 056f21c7
    3fffefa0:  4010000d 31c0f00e 8b4afbe9 f30f0180
    3fffefb0:  00000000 3fffef4c 00000000 3fffff28
    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:  00000000 00000000 00000020 40100f22
    3ffffb10:  3ffe92f0 40104304 3ffefd44 feefeffe
    3ffffb20:  00000001 40103523 3ffed470 feefeffe
    3ffffb30:  40103986 feefeffe feefeffe feefeffe
    3ffffb40:  feefeffe feefeffe feefeffe feefeffe
    3ffffb50:  4010346a 0000007f 7fffffff 00000000
    3ffffb60:  0000007f feefeffe feefeffe feefeffe
    3ffffb70:  401022eb 00080000 00000020 40100f22
    3ffffb80:  00000000 00000000 00000000 4000050c
    3ffffb90:  3fffc278 40101fe8 3fffc200 00000022
    3ffffba0:  3ffffbb0 00000030 00000008 ffffffff
    3ffffbb0:  00000000 00000000 0000001f 40104bfd
    3ffffbc0:  4000050c 3ffedf28 00000002 00008e88
    3ffffbd0:  40226856 00000030 00000008 ffffffff
    3ffffbe0:  4021744b 00000000 00000001 3ffec950
    3ffffbf0:  00000002 00000000 3fffab2a 00000001
    3ffffc00:  00000003 00020021 00000001 3fff02f8
    3ffffc10:  00000000 00000000 0000001f 40104bfd
    3ffffc20:  4000050c 00ffffff 0000003f 3ffeca10
    3ffffc30:  40000f83 00000030 00000008 ffffffff
    3ffffc40:  4020b372 00000023 3fffdcc0 3fffb452
    3ffffc50:  0000003a 000000f1 000000b9 00000003
    3ffffc60:  00000001 fffffffd 00000001 3ffeee88
    3ffffc70:  00000000 00000000 0000001f 40104bfd
    3ffffc80:  4000050c 00000000 40225077 00000001
    3ffffc90:  40000e86 00000030 0000001f fffffffe
    3ffffca0:  40000e86 00000023 00000002 00000010
    3ffffcb0:  00000010 00000000 3fffdbc0 3ffe93a8
    3ffffcc0:  00000000 3fffc6fc 00000002 00000000
    3ffffcd0:  3ffed440 00000001 00000000 00000030
    3ffffce0:  00000000 3ffed470 20110486 00000000
    3ffffcf0:  ffffffff 3fffc6fc 00000000 3ffefd44
    3ffffd00:  3ffed440 00000001 00000000 00000030
    3ffffd10:  3fffb41c 00000000 00000020 40100f22
    3ffffd20:  3ffe92f0 4020b391 3ffeee88 3ffefc74
    3ffffd30:  3fffb452 0000003a 3ffed470 40100f22
    3ffffd40:  0000000c 00000000 00000020 3ffef2e1
    3ffffd50:  000005e0 00000000 40103125 3ffed470
    3ffffd60:  0000003c 00000000 3fffb452 00000100
    3ffffd70:  0000001c 00000001 4010426a 3ffed470
    3ffffd80:  3ffed440 4010431f 00000000 3ffed094
    3ffffd90:  00000005 00000000 00000020 40100f22
    3ffffda0:  3ffe92f5 4010431f 3ffecd80 40100f22
    3ffffdb0:  40101c3d 3ffecd80 3ffefd44 40100f22
    3ffffdc0:  00000023 61c7d6c4 3ffed750 40101e0e
    3ffffdd0:  3ffe9b70 00000000 00000000 40100f22
    3ffffde0:  00000023 61c7d6c4 4010224e 00000100
    3ffffdf0:  7fffffff 3ffe9b70 3ffe9b70 00000001
    3ffffe00:  00000001 00000040 3ffed750 40101e0e
    3ffffe10:  3ffe9ba0 61c7d6c4 00000000 4000050c
    3ffffe20:  3fffc278 40101fe8 3fffc200 00000022
    3ffffe30:  3ffe9bac 3ffe9ba0 3ffe9ba0 00000001
    3ffffe40:  40204bf3 00000030 00000010 ffffffff
    3ffffe50:  40204bf3 00000001 00000001 00000000
    3ffffe60:  00000000 00000000 00000000 fffffffe
    3ffffe70:  ffffffff 3fffc6fc 00000001 00000064
    3ffffe80:  3ffeebc8 3ffeeb98 3ffeec60 00000030
    3ffffe90:  40204b9b 00000000 3ffeee68 00000000
    3ffffea0:  00000000 00000000 00000000 fffffffe
    3ffffeb0:  ffffffff 3fffc6fc 00000001 00000000
    3ffffec0:  00000000 3fffdad0 3ffeed20 00000030
    3ffffed0:  00000000 00000000 00000001 3ffeed18
    3ffffee0:  00000000 3fffdad0 3ffeed20 00000030
    3ffffef0:  ffffffff 3fffc6fc 00000001 3ffeed18
    3fffff00:  00000000 3fffdad0 3ffeed20 00000030
    3fffff10:  00000000 3fffdad0 3ffeed20 00000030
    3fffff20:  3ffeeb98 3ffeebc8 3fffff60 401006dc
    3fffff30:  3ffeeb98 3ffeec60 40204b0c 40204734
    3fffff40:  4020158e 00000000 3ffeed18 40204f14
    3fffff50:  3ffeeb98 3ffeebc8 3ffeed18 40202b38
    3fffff60:  00000000 00000000 00000000 0106a8c0
    3fffff70:  00000000 00000000 00000000 00000000
    3fffff80:  00000000 3ffeec14 3ffeec60 40202a43
    3fffff90:  40205198 6407a8c0 00000000 3ffeed20
    3fffffa0:  00000000 00000000 00000001 40204b2d
    stack

    last failed alloc call: 3FFED93C(192)

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

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

**Update 2:** It isn't only the first middleman (chip no.1) which crashes, now it happened to be the second one (chip no.4)

title: ESP8266 won't receive messages after a while

Answers: 1

body:
I've swapped through 25 ESP8266-12 chips hoping I just had bad luck when receiving these things. I also tried changing the baud-rate, which resulted into some chips becoming a so called "brick" (don't set the baud-rate to 9600, or else you will have to flash them again). Changing the power supply wasn't helpful too. I tried to see if this was caused by a memory leak, so I included the method `ESP.getFreeHeap()` and printed the results. They didn't seem suspicious at all.

What I think did the trick was to put a `delay(1)` at the end of the loop and reduce the time interval of messages being sent from five seconds to one. For now this seems stable and reliable.

**Update:** I changed the `delay(1)` to the method `yield()`. As the ESP8266 runs a lot of utility functions in the background (keeping WiFi connected, managing the TCP/IP stack, and performing other duties) blocking these functions from running can cause the ESP8266 to crash and reset itself. To avoid these mysterious resets, avoid long, blocking loops in your sketch. Blocking loops can be for example sending messages with the TCP/IP.

Still `delay(1)` also worked for me because delays don't "freeze" the chip completely. There are multiple layers, some which are reachable for us and some which are not (keeping WiFi connected etc.), so `delay()` has a similar outcome as `yield()`. You can even find `yield()` in the `delay()` method in wiring.c.

    void delay(unsigned long ms)
    {
        uint32_t start = micros();

        while (ms > 0) {
            yield();                       //<-------
            while ( ms > 0 && (micros() - start) >= 1000) {
                ms--;
                start += 1000;
            }
        }
    }

But to set a `delay()` one needs to know how long it has to be so the duties get finished in time. `yield()` on the other hand pauses reading the script until the background duties are finished (that doesn't take too long).

Editing your script so that the chip keeps executing the `yield()` method often enough per run fixed it for me.


body:
I am trying to make a program that accepts four digit password using a 3*4 keypad.

The program should start with flashing LED1 and when password 1 is entered it switches this LED and blinks LED2. If password 2 is entered it switches to LED3 and so on.

Here is the code:

    #include <Keypad.h>
    #include <TimedBlink.h>

    #define Password_Length 5

    TimedBlink led1(14);
    TimedBlink led2(15);
    TimedBlink led3(16);
    TimedBlink led4(17);

    const unsigned long PERIOD1 = 1000;
    char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
    unsigned long previousMillis[5]; //[x] = number of leds
    char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

    byte data_count = 0;
    bool Pass_is_good;
    char customKey;

    const byte ROWS = 4;
    const byte COLS = 3;
    char keys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
    int ledservos[4] = {14, 15, 16, 17};
    Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

    void setup() {
      pinMode(14, OUTPUT);
      pinMode(15, OUTPUT);
      pinMode(16, OUTPUT);
      pinMode(17, OUTPUT);
      led1.blink(150, 50); // On for 150ms, off for 50ms
      led2.blink(150, 50);
      led3.blink(150, 50); // On for 150ms, off for 50ms
      led4.blink(150, 50);
      Serial.begin(9600);
      Serial.print("Enter Password");
      Serial.println();
    }

    void loop() {
      led1.blink();
      led2.blink();
      led3.blink();
      led4.blink();
      customKey = customKeypad.getKey();
      if (customKey) {
      // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
        Data[data_count] = customKey; // store char into data array
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
      }
      if (data_count == Password_Length - 1) {
        // if the array index is equal to the number of expected chars, compare data to master
        Serial.print("Password is ");
        for (byte i = 0; i < Password_Length; i++)
          Serial.print(Data[i]);
        for (x = 0; x < 4; x++) { //this loop for number of passwords in the array
          for (y = 0; y < 4; y ++) { //this loop for number of characters in each of the password array
            if (strcmp(Data[y], buffers[x][y]) != 0) {
              break;
            }
          }
          if (y == 4) {
            break;
          }
        }
        if (x < 4) {
          Serial.print(" Found at index ");
          Serial.println(x);
          switch (x) {
            case 0:
              led1.blinkOff();
              break;
            case 1:
              led2.blinkOff();
              break;
            case 2:
              led3.blinkOff();
              break;
            case 3:
              led4.blinkOff();
              break;
          }
        }
        clearData();
      }
    }

    void clearData() {
      Serial.println();
      while (data_count != 0) {
        // This can be used for any array size,
        Data[data_count--] = 0; //clear array for new data
      }
    }

    void BlinkLed (int led, int interval, int arry) {
      //(long) can be omitted if you dont plan to blink led for very long time I think
      if (((long)millis() - previousMillis[arry]) >= interval) {
        previousMillis[arry] = millis(); //stores the millis value in the selected array
        digitalWrite(led, !digitalRead(led)); //changes led state
      }
    }

Now I can make the program, but all LEDs start blinking and switch off after the password is entered and I got stuck at this point.

Here is a link to the [TimedBlink][1] Library.

  [1]: https://github.com/lpasqualis/TimedBlink

I have tried the `millis()` function to be used to blink LEDs in the next code:

    #include <Keypad.h>
    #include <Wire.h>

    #define buzzer 13
    #define greenled 20
    #define redled 21
    #define Password_Length 5

    unsigned long previousMillisLED14 = 0;
    unsigned long previousMillisLED15 = 0;
    unsigned long previousMillisLED16 = 0;
    unsigned long previousMillisLED17 = 0;
    // different intervals for each LED
    int intervalLED14 = 500;
    int intervalLED15 = 600;
    int intervalLED16 = 700;
    int intervalLED17 = 800;
    // each LED gets a state varaible
    boolean LED14state = false;     // the LED will turn ON in the first iteration of loop()
    boolean LED15state = false;     // need to seed the light to be OFF
    boolean LED16state = false;     // need to seed the light to be OFF
    boolean LED17state = false;     // need to seed the light to be OFF
    const unsigned long PERIOD1 = 1000;
    char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
    unsigned long previousMillis[5]; //[x] = number of leds
    byte i, x, y;
    char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7
    byte data_count = 0;
    bool Pass_is_good;
    char customKey;
    const byte ROWS = 4;
    const byte COLS = 3;
    char keys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };
    byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
    int ledservos[4] = {14, 15, 16, 17};
    Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

    void setup() {
      pinMode(14, OUTPUT);
      pinMode(15, OUTPUT);
      pinMode(16, OUTPUT);
      pinMode(17, OUTPUT);
      Serial.begin(9600);
      pinMode(buzzer, OUTPUT);
      pinMode(redled, OUTPUT);
      pinMode(greenled, OUTPUT);
      Serial.print("Enter Password");
      Serial.println();
    }

    void loop() {
      unsigned long currentMillis = millis();
      if ((unsigned long)(currentMillis - previousMillisLED14) >= intervalLED14) {
        LED14state = !LED14state;
        digitalWrite(14, LED14state);
        // save current time to pin 12's previousMillis
        previousMillisLED14 = currentMillis;
      }
      customKey = customKeypad.getKey();
      if (customKey) {
        // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
        Data[data_count] = customKey; // store char into data array
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
      }
      if (data_count == Password_Length - 1) {
        // if the array index is equal to the number of expected chars, compare data to master
        Serial.print("Password is ");
        for (byte i = 0; i < Password_Length; i++)
          Serial.print(Data[i]);
        for (x = 0; x < 4; x++) {
          //this loop for number of passwords in the array
          for (y = 0; y < 4; y ++) {
            //this loop for number of characters in each of the password array
            if (strcmp(Data[y], buffers[x][y]) != 0) {
              break;
            }
          }
          if (y == 4) {
            break;
          }
        }
        if (x < 4) {
          Serial.print(" Found at index ");
          Serial.println(x);
          switch (x) {
            case 0:
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              digitalWrite(17, LOW);
              if ((unsigned long)(currentMillis - previousMillisLED15) >= intervalLED15) {
                LED15state = !LED15state;
                digitalWrite(15, LED15state);
                // save current time to pin 12's previousMillis
                previousMillisLED15 = currentMillis;
              }
              break;
            case 1:
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(17, LOW);
              if ((unsigned long)(currentMillis - previousMillisLED16) >= intervalLED16) {
                LED16state = !LED16state;
                digitalWrite(16, LED15state);
                // save current time to pin 12's previousMillis
                previousMillisLED16 = currentMillis;
              }
              break;
            case 2:
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              if ((unsigned long)(currentMillis - previousMillisLED17) >= intervalLED17) {
                LED17state = !LED17state;
                digitalWrite(17, LED17state);
                // save current time to pin 12's previousMillis
                previousMillisLED17 = currentMillis;
              }
              break;
            case 3:
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              digitalWrite(17, LOW);
              break;
          }
        }
        clearData();
      }
    }

    void clearData() {
      Serial.println();
      while (data_count != 0) {
        // This can be used for any array size,
        Data[data_count--] = 0; //clear array for new data
      }
    }

But it blinks the first LED only, then each of the following LEDs according to the condition got permanent on.
I have tried the solution that Adafruit suggested, to use a class in code but unfortunately I got the same result as the previous code.

Here is the code:

    #include <Keypad.h>
    #include <Wire.h>

    class Flasher {
        // Class Member Variables
        // These are initialized at startup
        int ledPin;      // the number of the LED pin
        long OnTime;     // milliseconds of on-time
        long OffTime;    // milliseconds of off-time
        // These maintain the current state
        int ledState;                 // ledState used to set the LED
        unsigned long previousMillis;   // will store last time LED was updated
        // Constructor - creates a Flasher
        // and initializes the member variables and state
      public:
        Flasher(int pin, long on, long off) {
          ledPin = pin;
          pinMode(ledPin, OUTPUT);
          OnTime = on;
          OffTime = off;
          ledState = LOW;
          previousMillis = 0;
        }
        void Update() {
          // check to see if it's time to change the state of the LED
          unsigned long currentMillis = millis();
          if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime)) {
            ledState = LOW;  // Turn it off
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(ledPin, ledState);  // Update the actual LED
          } else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime)) {
            ledState = HIGH;  // turn it on
            previousMillis = currentMillis;   // Remember the time
            digitalWrite(ledPin, ledState);   // Update the actual LED
          }
        }
    };

    Flasher led1(14, 100, 400);
    Flasher led2(15, 350, 350);
    Flasher led3(16, 100, 400);
    Flasher led4(17, 350, 350);

    #define buzzer 13
    #define greenled 20
    #define redled 21
    #define Password_Length 5

    char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
    unsigned long previousMillis[5]; //[x] = number of leds
    byte i, x, y;
    char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

    byte data_count = 0;
    bool Pass_is_good;
    char customKey;
    const byte ROWS = 4;
    const byte COLS = 3;
    char keys[ROWS][COLS] = {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };
    byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
    int ledservos[4] = {14, 15, 16, 17};
    Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

    void setup() {
      Serial.begin(9600);
      pinMode(buzzer, OUTPUT);
      pinMode(redled, OUTPUT);
      pinMode(greenled, OUTPUT);
      Serial.print("Enter Password");
      Serial.println();
    }

    void loop() {
      led1.Update();
      customKey = customKeypad.getKey();
      if (customKey) {
        // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
        Data[data_count] = customKey; // store char into data array
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
      }
      if (data_count == Password_Length - 1) {
        // if the array index is equal to the number of expected chars, compare data to master
        Serial.print("Password is ");
        for (byte i = 0; i < Password_Length; i++)
          Serial.print(Data[i]);
        for (x = 0; x < 4; x++) {
          //this loop for number of passwords in the array
          for (y = 0; y < 4; y ++) {
            //this loop for number of characters in each of the password array
            if (strcmp(Data[y], buffers[x][y]) != 0) {
              break;
            }
          }
          if (y == 4) {
            break;
          }
        }
        if (x < 4) {
          Serial.print(" Found at index ");
          Serial.println(x);
          switch (x) {
            case 0:
              led2.Update();
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              digitalWrite(17, LOW);
              break;
            case 1:
              led3.Update();
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(17, LOW);
              break;
            case 2:
              led4.Update();
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              break;
            case 3:
              digitalWrite(15, LOW);
              digitalWrite(14, LOW);
              digitalWrite(16, LOW);
              digitalWrite(17, LOW);
              break;
          }
        }
        clearData();
      }
    }

    void clearData() {
      Serial.println();
      while (data_count != 0) {
        // This can be used for any array size,
        Data[data_count--] = 0; //clear array for new data
      }
    }

Any idea why is this happening?

title: Blinking LEDs in sequence with a class

Answers: 1

body:
**EDIT**

Now that you added a link to the TimedBlink library I was able to go look at it. That is not a very well written library, and its documentation is **horrible**.

It seems that `blink(int,int)` starts a TimedBlink LED blinking, and blinkOff stops it. So you should not call `LEDx.blink(150,50)` on any of your LEDs until you want them to start blinking.

You need to refactor your code to only call `LEDx.blink(150,50)` on one LED at a time. You probably want your switch statement to call `LEDx.blink(150,50)` on the LED that you want to blink and ledOff() on the others.


body:
I'm looking for a cheap and small bluetooth board for a project.
I found [this][1] one, but I find this one too expensive, are there cheaper alternatives, in similar size?

Thank you!

  [1]: https://www.dfrobot.com/product-1259.html

title: Looking for a cheap small arduino ish board

Answers: 1

body:
I'd suggest investigating the ESP32.

It's not only a far more powerful chip than any normal Arduino, but it has both WiFI *and* Bluetooth Low Energy, all on the one chip.

It's available as surface mount modules, similar to the ESP8266, and there are a number of small development boards that have been created around it as well.


body:
I'm a complete newbie with Arduino. I've bought a couple of Nano clones from China. According to supplier description, it is Arduino Nano V3.0 ATMEGA328P ATMEGA328 CH340. Not sure why they list both 328 and 328P, but my struggle is to make it work anyway: IDE doesn't see it.

Power LED is on, L-LED is blinking regularly.

After some online reading, I conclude that the root cause may be in the USB-serial chip. My question is: if, when connecting this device to my Mac, I see a `/dev/tty.usbserial-1420` device appearing, does it mean that the USB-serial interface actually works correctly? Or does it not, and I should continue trying with installing some extra drivers etc.?

I am on Macbook Pro 2015, Mac OS 10.14.3. Many thanks in advance.

The error I am getting in IDE is:
> avrdude: stk500_recv(): programmer is not responding
>
> avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

Note: In a [similar question][1] the user didn't have the usbserial device in his /dev list.

  [1]: https://arduino.stackexchange.com/questions/12133/mac-osx-yosemite-no-serial-ports-showing-for-uno-r3

title: What is /dev/tty.usbserial-1420

Answers: 1

body:
These China clones are frequently shipped with no bootloader burned to the chip. There is a way to get it working but, you need a working Arduino or programmer to burn the bootloader. I have used an Arduino Uno to burn a bootloader on my nano. The Uno and nano were both purchased from the same seller, on the same order, from AliExpress. [Here are the instructions that worked for me.][1]

The instructions provide a link to download the Windows drivers so here’s a link to the macos drivers. [CH341_MAC.ZIP][2] (CH340 uses CH341 drivers)

  [1]: http://acoptex.com/project/63/chinese-clone-of-arduino-nano-with-chip-ch340g-how-to-fix-it-at-acoptexcom/#sthash.iwpgOddr.dpbs
  [2]: http://www.wch.cn/downloads/file/178.html


body:
I am making a project using IR sensor,servomotor and Push button.
I am not able write code for the logic as stated:
it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse  on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

title: How to execute operation once till a condition then restart it from start

Answers: 1

body:
My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.

Such an approach helps you in creating code easy to maintain and change to new requirements

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

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

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.

    Switch(state) {
      case 00:
      // if IR set state = 10;
      break;
      case 10:
      // if button was pressed set state = 11
      break;
      case 11:
      // turn motor
      // if treshold set state = 12
      break;
    .
    .
    .

    }


body:
Is the idea of connecting AD0 pins of MPU9250 is still valid like the 2nd answer of this question? - [https://arduino.stackexchange.com/questions/9106/how-to-change-i2c-address-for-mpu9250][1]

I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didnt work. What could be the solution?

Code to control 1 sensor:- It worked when I set AD0 to high and changed address to 0x69

    #include "MPU9250.h"

    // an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
    MPU9250 IMU(Wire,0x68);
    int status;

    void setup() {
      // serial to display data
      Serial.begin(115200);
      while(!Serial) {}

      // start communication with IMU
      status = IMU.begin();
      if (status < 0) {
        Serial.println("IMU initialization unsuccessful");
        Serial.println("Check IMU wiring or try cycling power");
        Serial.print("Status: ");
        Serial.println(status);
        while(1) {}
      }
    }

    void loop() {
      // read the sensor
      IMU.readSensor();
      // display the data
      Serial.print(IMU.getAccelX_mss(),6);
      Serial.print("\t");
      Serial.print(IMU.getAccelY_mss(),6);
      Serial.print("\t");
      Serial.print(IMU.getAccelZ_mss(),6);
      Serial.print("\t");
      Serial.print(IMU.getGyroX_rads(),6);
      Serial.print("\t");
      Serial.print(IMU.getGyroY_rads(),6);
      Serial.print("\t");
      Serial.print(IMU.getGyroZ_rads(),6);
      Serial.print("\t");
      Serial.print(IMU.getMagX_uT(),6);
      Serial.print("\t");
      Serial.print(IMU.getMagY_uT(),6);
      Serial.print("\t");
      Serial.print(IMU.getMagZ_uT(),6);
      Serial.print("\t");
      Serial.println(IMU.getTemperature_C(),6);
      delay(100);
    }

Code to control 2 sensors:-

    #include "MPU9250.h"

    // an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
    MPU9250 IMU1(Wire,0x68);
    MPU9250 IMU2(Wire,0x68);

    int status;

    void setup() {
      // serial to display data
      Serial.begin(115200);
      pinMode(D7, OUTPUT);
      pinMode(D8, OUTPUT);

    }

    void IMU_1() {
      digitalWrite(D7, LOW);
      digitalWrite(D8, HIGH);
      IMU1.begin();
      IMU1.readSensor();
      Serial.print("IMU 1 is active: "); Serial.print(IMU1.getAccelX_mss(),6);
      digitalWrite(D8, LOW);
    }

    void IMU_2() {
      digitalWrite(D7, HIGH);
      digitalWrite(D8, LOW);
      IMU2.begin();
      IMU2.readSensor();
      Serial.println("IMU 2 is active: "); Serial.print(IMU2.getAccelX_mss(),6);
      digitalWrite(D7, LOW);
    }

    void loop() {

    IMU_1();
    IMU_2();

      delay(500);

    }

  [1]: https://arduino.stackexchange.com/questions/9106/how-to-change-i2c-address-for-mpu9250

Result:- It Shows reading on one sensor but the 2nd sensor shows '0' every time.

What's the best way to use 3 I2C sensors when there is only 1 I2C bus?

title: Possible to connect 3 MPU9250 to Node MCU without multiplixer?

Answers: 1

body:
It sounds like the MPU9250 has a pin, AD0, that lets you switch the device between 2 fixed I2C addresses.

That gives you an easy solution if you need to use 2 of them.

For more, the post you linked suggests keeping them all at the same AD0 state except the one you want to talk to. You’d switch that one’s AD0 pin to the other state, which would cause it’s I2C address, and then talk to it at that address, which would be unique on the I2C bus.

That approach should work, but it’s a bit of a hack.

You say "I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didn't work." What didn't work? What happens? What output do you get What pins on your mcu are connected to AD0 on your 3 different MPU9250 modules? Where is the code that manipulates the digital pins to select one and only one of your MPU9250 modules for reading?

You need to throughly explain your setup, including the different pin assignments and how they are supposed to work. Don't leave us to read your code and try and figure out your intentions.

Looking at your code it looks like you're using D7 and D8 on your mcu to try to control which MPU9250 is active. However i don't see any code the sets D7 and D8 as outputs.

Why don’t you want to use an I2C address mapping chip? They are readily available, and the ones I’ve seen would let you address up to 8 I2C devices that are hard-wired with the same address.


body:
I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.

I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.

When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.

I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.

Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).

In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.

Can anyone help me figuring out why does the connection is lost as soon as it is established?

title: HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem

Answers: 1

body:
I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect.
Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.

This worked for me try this out.


body:
I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.

I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.

So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:

https://youtu.be/Tp5LtOKBKHw

(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)

Thanks!

title: Arduino acts odd when disconnected from computer

Answers: 1

body:
What seems is that you are facing an power shortage while working with on board power supply.
While running DC motors and Arduino on same battery set your Arduino is not getting enough power.

Try switching to a better power supply which can maintain a constant EMF, as eventually you'll always run out of power.
Try an adaptor to use wall socket current.
This way you'll not lose any functionality of Arduino project.


body:
I am trying to blink two LED's, starting at slow rate then increasing to fast s follows: 1 on, 1&2 on, 2 on, 1&2 on, 1 on, etc. The blinks go through the loop twice then speed up and repeat until both are on continuously. Then I want LED's 3 & 4 to come on.
I got the 1 & 2 LED's to blink as I want but anything I put following my for / if loop goes into the loop.
This works for blinking the 1 & 2 LED's:

    int led1 = 9;
    int led2 = 10;
    int led3 = 11;
    int led4 = 12;
    int delay1 = 700;
    int delayAmount1 = delay1 / 10;

    void setup() {

    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
    }

    void loop() {{
    delay1 = delay1 - delayAmount1;

    for (int i=0 ; i <2 ; i++) {

    if (delay1 > 10)

    digitalWrite(led1, HIGH); //yellow on (yellow)

    delay(delay1);

    digitalWrite(led2, HIGH); //red and yellow on (orange)

    delay(delay1);

    digitalWrite(led1, LOW); //yellow off (red)

    delay(delay1);

    digitalWrite(led1, HIGH); //yellow on (orange)

    delay(delay1);

    digitalWrite(led2, LOW); //red off (yellow)

    digitalWrite (led1, LOW); //yellow off (all off)

    }
    }

    // digitalWrite(led3, HIGH); //blue on

    //delay(1000);

    //digitalWrite(led4, HIGH); //green on

    }

If I remove the // from

    // digitalWrite(led3, HIGH); //blue on
    //delay(1000);
    //digitalWrite(led4, HIGH); //green on

they become part of the loop. Can someone tell me what I am doing wrong? Kind of new to this.

title: Blinking LED's at changing rate

Answers: 2

body:
The `if(delay1>10)` does not have the conditional code in {}, so it should look like

    if(delay1>10) {
    //conditional code, what happens if statement == true
    }

And if I understood your project and code correctly, when `delay1 <= 10` then you want the led3 and led4 to light up. So you want to add an optional `else{}` block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.

    else{
    //led3 and led4 light up
    }

body:
You have a number of code formatting problems, some aesthetic, and some structural.

You need to indent your code, and you need to use braces. If you don't format your code well you will have a very hard time figuring out what you are doing.

Here is an attempt to clean up your code:

void loop() {

    delay1 = delay1 - delayAmount1;

    for (int i=0 ; i <2 ; i++) {
        if (delay1 > 10) {
            digitalWrite(led1, HIGH); //yellow on (yellow)
            delay(delay1);
            digitalWrite(led2, HIGH); //red and yellow on (orange)
            delay(delay1);
            digitalWrite(led1, LOW); //yellow off (red)
            delay(delay1);
            digitalWrite(led1, HIGH); //yellow on (orange)
            delay(delay1);
            digitalWrite(led2, LOW); //red off (yellow)
            digitalWrite (led1, LOW); //yellow off (all off)
        }
    }
    // digitalWrite(led3, HIGH); //blue on
    //delay(1000);
    //digitalWrite(led4, HIGH); //green on
}

(I'm not sure what's supposed to be inside the if statement or not since you didn't have an opening brace.)

You also had 2 opening braces on your loop statement, which is very odd.

Note that using `delay()` to try to control more than one thing at a time is a bad idea. The delay() function causes your program to freeze everything until the delay is over. If you try to blink different LEDs at different rates, you can't. If you try to detect button presses while you are also blinking LEDs, you miss the button presses while your code is in a delay. There are lots of threads on the various Arduino boards on how to avoid using delay. Search on "Arduino blink no delay" to find the basics.


body:
I'm trying to push some data to ThingSpeak using the [EtherCard] library with the `ENC28J60` ethernet module.

At the moment I'm using the exemple code that comes with the library just for tests. But no matter what I do, always receive the same reply:

    REPLY recieved....
    HTTP/1.1 400 Bad Request
    Date: Sat, 09 Mar 2019 17:26:52 GMT
    Content-Type: text/html; charset=utf-8
    Transfer-Encoding: chunked
    Connection: close
    Status: 400 Bad Request
    X-Frame-Options: SAMEORIGIN
    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
    Access-Control-Allow-Headers: origin, content-type, X-Requested-With
    Access-Control-Max-Age: 1800
    Cache-Control: no-cache
    Set-Cookie: request_method=POST; path=/
    X-Request-Id: 9184d325-402d-4512-a942-e7

**Code:**

    #include <EtherCard.h>

    // Simple demo for feeding some random data to Pachube.
    // 2011-07-08 <jc@wippler.nl>
    //
    // License: GPLv2

    // Handle returning code and reset ethernet module if needed
    // 2013-10-22 hneiraf@gmail.com

    // Modifing so that it works on my setup for www.thingspeak.com.
    // Arduino pro-mini 5V/16MHz, ETH modul on SPI with CS on pin 10.
    // Also added a few changes found on various forums. Do not know what the
    // res variable is for, tweaked it so it works faster for my application
    // 2015-11-09 dani.lomajhenic@gmail.com

    // change these settings to match your own setup
    //#define FEED "000"
    #define APIKEY "XXXXXXXXXXXX" // put your key here

    // ethernet interface mac address, must be unique on the LAN
    static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x32 };
    const char website[] PROGMEM = "api.thingspeak.com";
    byte Ethernet::buffer[700];
    uint32_t timer;
    Stash stash;
    byte session;

    //timing variable
    int res = 100; // was 0

    void setup () {
      Serial.begin(9600);
      Serial.println("\n[ThingSpeak example]");

      //Initialize Ethernet
      initialize_ethernet();
    }

    void loop () {
      //if correct answer is not received then re-initialize ethernet module
      if (res > 220){
        initialize_ethernet();
      }

      res = res + 1;

      ether.packetLoop(ether.packetReceive());

      //200 res = 10 seconds (50ms each res)
      if (res == 200) {

        //Generate random info
        float demo = random(0,500);
        //word one = random(0,500);
        //String msje;

    //    if (demo < 250){
    //      msje = "low";
    //    }
    //    else{
    //      msje = "high";
    //    }

        // generate two fake values as payload - by using a separate stash,
        // we can determine the size of the generated message ahead of time
        // field1=(Field 1 Data)&field2=(Field 2 Data)&field3=(Field 3 Data)&field4=(Field 4 Data)&field5=(Field 5 Data)&field6=(Field 6 Data)&field7=(Field 7 Data)&field8=(Field 8 Data)&lat=(Latitude in Decimal Degrees)&long=(Longitude in Decimal Degrees)&elevation=(Elevation in meters)&status=(140 Character Message)
        byte sd = stash.create();
        stash.print("&field1=");
        stash.println(demo);
        //stash.print("&field2=");
        //stash.print(one);
        //stash.print("&field3=");
        //stash.print(msje);
        stash.save();

        //Display data to be sent
        Serial.println(demo);

        // generate the header with payload - note that the stash size is used,
        // and that a "stash descriptor" is passed in as argument using "$H"
        Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
          "Host: $F" "\r\n"
          "Connection: close" "\r\n"
          "X-THINGSPEAKAPIKEY: $F" "\r\n"
          "Content-Type: application/x-www-form-urlencoded" "\r\n"
          "Content-Length: $D" "\r\n"
          "\r\n"
          "$H"),
        website, PSTR(APIKEY), stash.size(), sd);

        // send the packet - this also releases all stash buffers once done
        session = ether.tcpSend();

     // added from: http://jeelabs.net/boards/7/topics/2241
     int freeCount = stash.freeCount();
        if (freeCount <= 3) {   Stash::initMap(56); }
      }

       const char* reply = ether.tcpReply(session);

       if (reply != 0) {
         res = 0;
         Serial.println(F(" >>>REPLY recieved...."));
         Serial.println(reply);
       }
       delay(300);
    }

    void initialize_ethernet(void){
      for(;;){ // keep trying until you succeed
        //Reinitialize ethernet module
        //pinMode(5, OUTPUT);  // do notknow what this is for, i ve got something elso on pin5
        //Serial.println("Reseting Ethernet...");
        //digitalWrite(5, LOW);
        //delay(1000);
        //digitalWrite(5, HIGH);
        //delay(500);

        // Change 'SS' to your Slave Select pin, if you arn't using the default pin
        if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0){
          Serial.println( "Failed to access Ethernet controller");
          continue;
        }

        if (!ether.dhcpSetup()){
          Serial.println("DHCP failed");
          continue;
        }

        ether.printIp("IP:  ", ether.myip);
        ether.printIp("GW:  ", ether.gwip);
        ether.printIp("DNS: ", ether.dnsip);

        if (!ether.dnsLookup(website))
          Serial.println("DNS failed");

        ether.printIp("SRV: ", ether.hisip);

        //reset init value
        res = 180;
        break;
      }
    }

I searched the site and saw that the `Bad Request` is related to syntax error.

Any attempt I made was in this part of the code, almost every change I tried was on the first line:

    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
          "Host: $F" "\r\n"
          "Connection: close" "\r\n"
          "X-THINGSPEAKAPIKEY: $F" "\r\n"
          "Content-Type: application/x-www-form-urlencoded" "\r\n"
          "Content-Length: $D" "\r\n"
          "\r\n"
          "$H"),
        website, PSTR(APIKEY), stash.size(), sd);

I think that is the part responsible for the URL syntax.

I tried to change the `POST` for `GET`, to put all the URL on the first line, something like: `"POST https://$F/update?api_key=$F HTTP/1.1"`(that one I saw on `StackOverflow`).

But I don't have any more idea where is the problem.

To confirm that the channel is OK I tried to send data directly via URL, and everything is OK.

**URL Exemple:**

    https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0

I don't know what to do to get it work. Thanks for your help!

[EtherCard]: https://github.com/njh/EtherCard

title: Can't push data to ThingSpeak - Status 400 Bad Request

Answers: 0


body:
I want to extract the latitude and longitude values of my location but my gps led is not blinking. Also result appearing on the serial monitor is wrong.

This is my Arduino code:

    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>

    SoftwareSerial gpsSerial(3, 4);
    TinyGPSPlus gps;
    float latitude,longitude;
    void setup() {
      // put your setup code here, to run once:
      gpsSerial.begin(9600);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    while(gpsSerial.available())
      {
        int data=gpsSerial.read();
        if(gps.encode(data))
           {
              latitude = (gps.location.lat());
              longitude = (gps.location.lng());
              Serial.print("Latitude");
              Serial.println(latitude);
              Serial.print("Longitude ");
              Serial.println(longitude);
           }
       }
    }

Please tell me what is wrong in the code?

title: GPS led not blinking and wrong LAT Long values

Answers: 0


body:
So I'm trying to make a program that allows you to enter a number in decimal and it displays it in binary, and it's going fairly well after some initial struggles (for some reason it read integers as 48 more than they are (5 read as 53)) but there's something I still don't understand, and I'm scared that it may be a hardware issue.

For some reason, I can't display two-digit numbers. For example, if I input 12, it displays 1, and THEN it displays 2. Also, to make things worse, it ALWAYS outputs 10 after I input ANY number. For example, if I input 5, it displays 5, and then ALWAYS 10.

        void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      int number;
      if (Serial.available() > 0) {

        number = Serial.read();
        Serial.print("Number to display: ");
        Serial.println(number);

        if (number <= 15){
          int LEDPin = 2;
          digitalWrite(2, LOW);
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
            for (int n = 0; n <= 4; n++){
              int binval = bitRead(number, n);
              Serial.println(binval);
              digitalWrite(LEDPin, binval);
              LEDPin++;
          }
        }
        else{
        Serial.println("Number must be less than 16!");
        }

        delay(1000);
      }
    }

EDIT: And of course, after asking the question I re-ran the code and its AGAIN showing ints as 48 bigger than they are (5 as 53).

At this point, I'm extremely confused. Am I doing something wrong? Is this a hardware issue? What can I do?

title: Serial read multiple digits and always reading 10 at the end?

Answers: 2

body:
> for some reason it read integers as 48 more than they are (5 read as 53)

That's because you're not entering numbers, you're entering ASCII characters that represent numbers.

Everything you see on a computer or similar device is not really what is there. It is all translated into a form that we mere humans can see.  Every number is translated into readable characters, and readable characters have to be converted into numbers.

For example, the number 165 is the characters 1 (49), 6 (54) and 5(53).  When you enter that number you are sending those three individual characters.

You see the entire ASCII table [here](http://www.asciitable.com/).

Another effect of sending individual characters is that you also send a marker to say "This is the end of the line". That can either be character 13 (Carriage Return), character 10 (Line Feed), or a combination of the two.  You can select which is sent in the Serial Monitor.

You should really use that line ending character or combination of characters to work out how many characters there are in your number so you can convert them into a proper integer value.

Some further reading:

* [Reading Serial on the Arduino](https://majenko.co.uk/blog/reading-serial-arduino) (my blog)
* [The `atoi()` function](http://nongnu.org/avr-libc//user-manual/group__avr__stdlib.html#ga3a1fe00c1327bbabc76688a7a1d73370)

body:
I would suggest getting the user input with `Serial.readBytesUntil()`, store it in a `char` array, then use `itoa()` to get the integer value. Here is a modified version of your sketch.

    char inputBuffer[5];
    byte number = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
    }

    void loop() {

      if (Serial.available() > 0) {

        Serial.readBytesUntil('\n', inputBuffer, 4);
        number = atoi(inputBuffer);
        Serial.print("Number to display: ");
        Serial.println(inputBuffer);

        if (number <= 15){
          int LEDPin = 2;
          digitalWrite(2, LOW);
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
            for (int n = 0; n <= 4; n++){
              int binval = bitRead(number, n);
              Serial.println(binval);
              digitalWrite(LEDPin, binval);
              LEDPin++;
          }
        }
        else{
          Serial.println("Number must be less than 16!");
        }
        delay(1000);
      }
    }


body:
I am having this problem when trying to compile my sketch. I am using RF frequency modules to send data between devices and a servo motor to control the tilt of a ramp. I understand that both libraries use TIMER 1 but I am unsure how to change one of them to use TIMER 2 thanks.

    Arduino: 1.8.7 (Windows 10), Board: "Arduino/Genuino Uno"

    libraries\Servo\avr\Servo.cpp.o (symbol from plugin): In function `ServoCount':

    (.text+0x0): multiple definition of `__vector_11'

    libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Uno.
    Board at COM4 is not available

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

title: RadioHead and Servo compile problems

Answers: 1

body:
You can force the RadioHead library to use Timer 2 instead. This can be done by enabling the define RH_ASK_ARDUINO_USE_TIMER2 near the top of RH_ASK.cpp.

More details about how to do this may be found in the RadioHead library documentation. Please see https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html.

Cheers!


body: I need to produce a log to base 10 with at least 4 decimal places. However, the log10 inbuilt function is giving the output with only two decimal places. What do I do? Is there a different function or a library that I can use?

title: Higher precision logarithms

Answers: 1

body:
You should be able to get 6 or 7 decimal places out of the Arudino float type. Try using Serial.print for floats with a number of decimal places. Something like this:

    float x = log10(3.141592658);
    Serial.print(x, 6);


body:
I have an Arduino Due and I want to connect the output from the DAC as an input to an Arduino Uno's analog input pin. From this link http://forum.arduino.cc/index.php?topic=164763.0, user DuaneB suggested that a resistor should be used in series with the DAC output to prevent an excessive flow of current that could damage the pin. But he was talking about this when the question was about powering a motor using the current generated from the DAC's voltage.

However, is this series resistor required when simply connecting the output of the pin to the input of another pin? I haven't seen any issue when connecting the output of my Raspberry Pi's GPIO to an arduino's input.

title: Connecting DAC output from Arduino Due to another arduino

Answers: 1

body:
The inputs to Arduino pins are CMOS inputs, and present very high impedance.  (There is a tiny capacitor on every CMOS input, and the only current into the input is the very small amount needed to charge that capacitor.)

You don't need resistors when connecting inputs and outputs (digital or analog) between Arduinos. Should be the same with Raspberry Pi GPIO lines, or any other CMOS devices.


body:
I'm trying to communicate between Arduino Nano and Arduino Uno using nRF24L01+.

I tried using RF24 by ManiacBug and TMRH20, but when I open the serial monitor after uploading the Example Programs Getting Started from ManiacBug and pingpair Program from TMRH20, it does not change its address.

The addresses for reading and writing I'm using are 0xF0F0F0F0E1LL and 0xF0F0F0F0D2LL, but the response I'm receiving is as follows:
[![enter image description here][1]][1]

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

I check all the connection and tried different examples available on the internet, but nothing worked at all.

title: nRF24L01+ Unable to set address

Answers: 1

body:
You can set addresses using SPI commands.  For example a 5-byte transmitter address could be written as (MSB first):

      digitalWrite(CSN_pin, LOW);
      SPI.transfer(0x30); // write TX_ADDR register
      SPI.transfer(tx_addr[0]);
      SPI.transfer(tx_addr[1]);
      SPI.transfer(tx_addr[2]);
      SPI.transfer(tx_addr[3]);
      SPI.transfer(tx_addr[4]);
      digitalWrite(CSN_pin, HIGH);

where `tx_addr` is an array of 5 bytes.  Similarly you can write to the RX_ADDR registers, see the nRF24L01+ datasheet, section 9 for the register map.

Furthermore, the following code allows you to read the TX_ADDR register:

      digitalWrite(CSN_pin, LOW);
      SPI.transfer(0x10); // read TX_ADDR register
      data_out[0] = SPI.transfer(0x0);
      data_out[1] = SPI.transfer(0x0);
      data_out[2] = SPI.transfer(0x0);
      data_out[3] = SPI.transfer(0x0);
      data_out[4] = SPI.transfer(0x0);
      digitalWrite(CSN_pin, HIGH);

      Serial.print("TX_ADDR=");
      Serial.print(data_out[0]);
      Serial.print(data_out[1]);
      Serial.print(data_out[2]);
      Serial.print(data_out[3]);
      Serial.println(data_out[4]);


body:
I want to reset this counter variable which I created after each 1 second, but I don't want to disturb the `if` statement.

Here is the code:

    int button=A0;
    int val;
    int count=0;
    int presss;

    void setup() {
      pinMode(button,INPUT);
      Serial.begin(9600);
    }

    void loop() {
      val=analogRead(button);
      if(val>1000){
       presss=count++;
       delay(200);
     }
      Serial.println(presss);
      delay(1000);
     }

title: I want to reset a variable after each 1 second on an Arduino

Answers: 3

body:
I would do it the following way:

- Use a variable declared as: `unsigned long time_passed;`

- In the setup() section I would add the line `time_passed = millis();`

- In the loop() section I would add the if condition:

`if(millis()-time_passed > 1000) {
   time_passed = millis();
   presss = 0;
   }`

I think this is still not working properly with your example, I recommend to make two changes in your code:

- you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop

- I cannot understand how `presss = count++;` should work. For proper counting I would suggest to do it this way: `presss = presss + 1;`

- Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms

body:
You could do something like this:

    void loop() {
      for (int i = 0; i < 5; i++) {
        val = analogRead(button);
        if (val > 1000) count++;
        delay(200);
      }
      Serial.println(count);
      count = 0;
     }

This will sample the button five times and count the number of times the value is larger than 1000, with a 200 ms delay between each read. This give approx. 1 s.

But this might not be the logic you are looking for.

Cheers!

body:
If I understood the project, you want to count how many button clicks you did in one second, so I've adjusted your code a little bit. If you don't want your program to do something after a certain amount of time, but don't want it to wait don't use `delay(ms)` use `millis()` instead (see https://www.arduino.cc/reference/en/language/functions/time/millis/ )

    int button=A0;
    int val;
    int presss=0;

    int millisBegin = 0;
    int millisNow;
    int millisBorder = 1000;

    void setup()
    {
      pinMode(button,INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      val=digitalRead(button);

      if(val==HIGH)
      {
        presss++;     //If the button is pressed it will count + 1

        while(val==HIGH)
        {
          val=digitalRead(button); //It will wait till you release the button here
        }
      }

      Serial.println(presss);

      millisNow = millis();

      if(millisNow-millisBegin >= millisBorder)
      {
        presss = 0;
        millisBegin = millisNow;
        Serial.println("~1 second passed");
      }
    }

I checked it and it worked for me (I changed the `if(val>1000)` to `if(val==HIGH)`, otherwise it might not always detect a button press


body:
I am trying to use `L293D` with relay to power a 12V DC motor. Can I use arduino's 5V to provide L293D inputs 4 and 8 such as in the drawing? Or do I need to use a separate source, e.g. a power module?

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

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

title: L293D with arduino's 5V

Answers: 1

body:
it looks like that motor controller chip has separate logic level and motor power inputs.

VCC1, at pin 16, is a low current logic level power input. You should be able to drive that from the Arduino's power supply.

VCC2, at pin 8 is the motor power input. You should **NOT** drive that from your Arduino's power supply. You should have a separate power supply for that (+5V with enough current for all the motors you are powering - 600mA is the max that chip can drive for a single motor, so a 1A power supply for VCC2 would be fine.

It looks like you are feeding the Arduino's +5V line into VCC2. **DON'T DO THAT.**


body:
I have tried to set up a very simple REST API on an Arduino Industrial 101 (which is, as far as I understand, equivalent to a Yún). The Arduino is hooked up to a temperature sensor, which value is returned over the REST interface. Everything works fine at first, but over the course of a day it starts taking longer and longer for the device to respond until it completely crashes and becomes unresponsive. (At that point it also doesn't respond to `ping` and `ssh` anymore.)

On the Arduino forum there are several threads reporting similar problems (e.g. [this one][1]) but they all seem to be at least a few years old and have been solved in the mean time. ([The solution reported here][2], for instance, has already been incorporated in my Linino version.)

If I reset the ATMega the problem persists, but if I reboot the OS it is solved for a day, so I have reason to suspect something on the Linino side is not working properly. Any help would be much appreciated, although I realize this is quite an old board.

My sketch is basically a dumbed-down version of the [Bridge example][3]:

```c++
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  BridgeClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

void process(BridgeClient client) {
  // no matter what the command is, return value on A1 sampled 4096 times

  int pin = 1;
  float val = 0;
  for (int i = 0; i < 4096; i++){
    val += float(analogRead(pin))/4096.0;
  }
  client.println(val*5.0/1024.0, 5); //multiply by 5/1024 to get volts

}
```

  [1]: https://forum.arduino.cc/index.php?topic=198998.0
  [2]: http://forum.arduino.cc/index.php?topic=204077.15
  [3]: http://www.arduino.cc/en/Tutorial/Bridge

title: REST API on Industrial 101 (Yún family) lags, then crashes

Answers: 2

body:
First of all you should try changing the `delay(50);`. Try using `millis();` instead and see if the problem still persists.

```c++
int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

```

If that doesn't help, try adding the `yield();` method after the `delay(50);` / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.

My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.

body:
I inspected the source code of the Bridge library. It is very simple.

There are no dynamic memory allocations. It uses String in client.connect(), but your sketch doesn't use it. You could print free memory in ATmega with [MemoryFree library][1]. But I am 99% percent sure it will show no memory leak.

There is no 'background' processing in the Bridge library as suggested by other answers. All commands and data are sent to the WRT on Atheros and wait for result or acknowledge. The WRT side of the Bridge library is coded in python.

The fact that the restart of the WRT is what helps to continue, confirms that the problem is on the python side of the Bridge.

Python on WRT is very far from Arduino knowledge base, so I doubt you will get a solution here.

  [1]: https://github.com/McNeight/MemoryFree


body:
I'm working on the rfid module and found an example that do it well. But it has a long testing the 5 bytes of the rfid received bytes, and I've tried to write it in a more compact way.

I did it with a for loop, but how to AND the conditions of the if statement?

How to change this:

    if(bt0[cnt-1] == rfid.serNum[0] &&
       bt1[cnt-1] == rfid.serNum[1] &&
       bt2[cnt-1] == rfid.serNum[2] &&
       bt3[cnt-1] == rfid.serNum[3] &&
       bt4[cnt-1] == rfid.serNum[4]){
       lcd.clear();
       lcd.print("card accepted");
       digitalWrite(green_led,HIGH);
       digitalWrite(red_led,LOW);
     }
     else{
        lcd.clear();
        lcd.print("card denied");
        digitalWrite(green_led,LOW);
        digitalWrite(red_led,HIGH);
    }

To something like this:

        for(byte i=0;i<MXCD;i++){
          if(bt[i] == rfid.serNum[i%5]){
            cnt++;
          }
        }
        if(cnt==5){
          lcd.clear();
          lcd.print("card accepted");
          digitalWrite(green_led,HIGH);
          digitalWrite(red_led,LOW);
          cnt = 0;
        }
        else{
          lcd.clear();
          lcd.print("card denied");
          digitalWrite(green_led,LOW);
          digitalWrite(red_led,HIGH);
          cnt = 0;
        }

In this way, I did it with 'cnt' variable to count the number of successful matched bytes then test of the number is equal to 5.

Is there a better way than this one ?

Thanks for any comments or suggestions :)

title: How to write a more compact ANDed conditions with if statement?

Answers: 1

body:
There is a standard C function for this, `memcmp()`. It performs a memory block compare and can be used like this:

    if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
      lcd.clear();
      lcd.print("card accepted");
      digitalWrite(green_led,HIGH);
      digitalWrite(red_led,LOW);
    }
    else {
      ...
    }

Ref. http://www.cplusplus.com/reference/cstring/memcmp/


body:
I am sending some data from ESP8266 01 module to Arduino. But the data received by Arduino is not complete.

Below are the images of the output from ESP8266 01 module and Arduino.

[![ESP8266 01 output][1]][1]
[![Data received by Arduino][2]][2]

  [1]: https://i.stack.imgur.com/uM2v0.png
  [2]: https://i.stack.imgur.com/unDEu.png

Here is the ESP8266 01 Module code:-

    #include <ESP8266WiFi.h>
    #include<String.h>

    char c,e;                       //stores the bytes coming from the server
    int DEBUG = 0;

    int co=0;                       //control the sending of Alert

    const char* ssid     = "ssid";            //your SSID of WIFI
    const char* password = "password";       // password of Wifi
    //--------------------------------------------

    const char* host = "api.thingspeak.com";

    void setup() {
      //dht.begin();
        Serial.begin(115200);
        delay(10);
      // We start by connecting to a WiFi network

        if (DEBUG){
          Serial.println();
          Serial.println();
          Serial.print("Connecting to ");
          Serial.println(ssid);
      }

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

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

        if (DEBUG){
          Serial.println("");
          Serial.println("WiFi connected");
          Serial.println("IP address: ");
          Serial.println(WiFi.localIP());
        }
    }

    int value = 0;

    void loop() {
      delay(1000);
      ++value;

      if (DEBUG){
        Serial.print("connecting to ");
        Serial.println(host);
      }

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }

      if (DEBUG){
        Serial.print("Requesting URL: ");
      }

    //============================================================================================================
    //                                Sending Control info to arduino Serially
    //============================================================================================================
      // This will send the request to the server
      client.print(String("GET ")  + "/channels/******/feeds.json?api_key=*****************&results=2 HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");         // get information about device control
      unsigned long timeout = millis();
      while (client.available() == 0) {
        if (millis() - timeout > 5000) {
          Serial.println(">>> Client Timeout !");
          client.stop();
          return;
        }
      }

      // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);                         // received by arduino serially
      }
     //Serial.println("closing connection");
    }

Here is the Arduino code:-

        //This sketch in the implementation of home automation
    #include <SoftwareSerial.h>// import the serial library
    #include<String.h>
    //-----------------------------------------
    //    pin definations
    //-----------------------------------------
    #define Light 2              // pin 2 to control light
    #define fan 3                 // pin 3 to control fan
    //------------------------------------------
    //       variables
    //------------------------------------------
    char e;
    int p=0,q=0;        //these variables prevent switching ON/OFF of already turned ON/OFF devices
    int DEBUG = 1;

    SoftwareSerial home_monitor(10, 11); // RX, TX

    char control_data; // the data transmitted over Bluetooth

    void setup() {
      // put your setup code here, to run once:
      home_monitor.begin(115200);
      Serial.begin(9600);
      pinMode(13,OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (home_monitor.available()){
         control_data=home_monitor.read();   // getting control information from ESP8266 serially
         e=control_data;
         if (DEBUG){
          Serial.print(control_data);
         }
         //Serial.print(e);
     //============================================================================================================
     //                                        Device Control
     //============================================================================================================

     // Performing required operations based on the value of channel
        //-------------------------------------------------------------
        //                        LIGHT
        //-------------------------------------------------------------

        if(e=='0'&&p==0)         //Light ON
        {
          if (DEBUG){
            Serial.println("Light ON");
          }
          digitalWrite(Light,LOW);
          p=1;
        }
         if(e=='1'&&p==1)        //Light off
        {
          if (DEBUG){
            Serial.println("Light OFF");
          }
          digitalWrite(Light,HIGH);
          p=0;
        }

        //-------------------------------------------------------------
        //                        Heater
        //-------------------------------------------------------------

        if(e=='2'&&q==0)
        {
          if (DEBUG){
            Serial.println("Fan ON");
          }
          digitalWrite(fan,LOW);
          q=1;
        }
        if(e=='3'&&q==1)
        {
          if (DEBUG){
            Serial.println("Fan OFF");
          }
          digitalWrite(fan,HIGH);
          q=0;
        }
      }
    }

title: Data received by Arduino from ESP8266 01 Module is not complete

Answers: 1

body:
You are using `client.print()` and the Arduino uses `home_monitor.read()` to receive the message (if I understood correctly). What I did in my sketch was change the `home_monitor.read()` to `home_monitor.readStringUntil('\n')`.

Also before your ESP sends a message via `client.print()` it is recommended to run the `client.flush()` method so it waits until all outgoing characters in the buffer have been sent, before sending the next.

When using the ESP you should be aware of the useful `yield()` method (call it at the end of the loop). This let's the ESP get his background duties finished before going on (not calling this method may result in some issues.


body:
I wrote a simple `Timer` class that's designed to work even in the face of the 49 day wrap of the `millis()` counter. I wanted a library that I could easily re-use and I could never remember the right way of dealing with the wrap-around so I thought: do it once, right. However, it has not gone according to the script!

Here's the source code, header first.

```C++
class Timer
 {
public:
 Timer();
 void SetDuration(unsigned long duration);
 bool Expired();
 unsigned long Elapsed();
 unsigned long Remaining();
 void Repeat();
 bool Enabled();
 void Stop();
private:
 unsigned long startedAt;
 unsigned long interval;
 };
```

...and the implementation...

```C++
#include "Timer.h"

Timer::Timer()
 {
 startedAt = 0;
 interval = 0;
 }

/*
 * Sets the timer interval and establishes the reference datum as the instant when this method was called.
 */
void Timer::SetDuration(unsigned long duration)
 {
 startedAt = millis();
 interval = duration;
 }

unsigned long Timer::Elapsed()
 {
 if (!Enabled())
  return 0UL;
 unsigned long elapsed = millis() - startedAt;
 return elapsed;
 }

unsigned long Timer::Remaining()
{
 return interval - Elapsed();
}

bool Timer::Expired()
 {
 return Enabled() ? Elapsed() >= interval : false;
 }

/*
 * Repeats the timer interval but does not reset the reference datum.
 * This should be used when repeatedly timing the same interval, and it is
 * intended that the intervals be consistent _on average_.
 */
void Timer::Repeat()
 {
 startedAt += interval;
 }

bool Timer::Enabled()
{
 return interval > 0;
}

void Timer::Stop()
{
 interval = 0;
}
```

Now my problem is this. My sketch gets to a certain point then crashes (re-runs from the start). The behaviour seems a lot like an odd stack corruption that's causing the code to branch to Oblivion. I've spent several hours doing a binary-chop on the code to narrow down the cause (it's a big sketch) and much to my surprise, the culprit appears to be the `Repeat()` method in my timer class. I use it in just one place in my code. When I call the `Repeat()` method, it crashes my sketch; If I don't call `Repeat()` but instead call `SetDuration(n)`, the program doesn't crash and everything is fine. I've tried this in two different sketches with consistent results.

I've got spots before my eyes from trying to understand what's happening here. I'm a C# programmer most of the time although I'm not completely new to C and C++, but I've made dumb mistakes in Arduino code before. `Repeat()` could hardly be simpler or safer code - but is it? Is there anything wrong with my code that I'm just not seeing?

**UPDATE**: Stack Overflow effect (where you see the solution yourself as soon as you post a question) has kicked in and I've solved it. My implementation of Repeat() was moving startedAt ahead of millis() giving a negative amount of elapsed time (which in unsigned math means a very large positive amount of elapsed time). This was causing immediate time-out of the timer and causing the sketch to think the sky was falling in. So not a memory corruption, just some poorly implemented unsigned math.

title: Why would using the += operator on an unsigned long crash my sketch?

Answers: 0


body:
There is an IO expander [PCA9534PW][1], Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.

I found an [example][2], but here is the reading mode.

  [1]: https://datasheet.lcsc.com/szlcsc/NXP-Semicon-PCA9534PW-118_C161197.pdf
  [2]: http://diy-scib.org/content/pca9534-io-expander

What I need:
Set the IO0 pin to exit mode,
set the HIGH / LOW level to IO0.

In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03).
How can I do it?

title: Question on pin management using PCA9534PW IO Extender

Answers: 1

body:
You set the pin mode by setting the configuration register.

    Wire.beginTransmission(0x20);
    Wire.write(0x03);                   // Configuration Register
    Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
    Wire.endTransmission();

Then write the output port register with HIGH and LOW.

    Wire.beginTransmission(0x20);
    Wire.write(0x01);                   // Output Port Register
    Wire.write(0x01);                   // IO0 HIGH
    Wire.endTransmission();
    delay(500);
    Wire.beginTransmission(0x20);
    Wire.write(0x01);                   // Output Port Register
    Wire.write(0x00);                   // IO0 LOW
    Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.


body:
I'm working on an escape room for my university with an Arduino Mega.
The last part consists of a 7segment display representing a time countdown, and the participants have to introduce the correct number in a matrix keyboard before it reaches zero.

My problem comes when for representing the seconds in the countdown, I have to use a delay, and this stops the matrix keyboard from getting the numbers.

The code I have so far:

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

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

    int pinA = 26; //2
    int pinB = 34; //3
    int pinC = 31; //4
    int pinD = 27; //5
    int pinE = 25; //6
    int pinF = 28; //7
    int pinG = 33; //8
    int D1 = 24; //9
    int D2 = 30; //10
    int D3 = 32; //11
    int D4 = 35; //12

    Keypad mykeypad = Keypad( makeKeymap(keys), colPins, rowPins, 4, 4);

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

    pinMode(pinA, OUTPUT);
    pinMode(pinB, OUTPUT);
    pinMode(pinC, OUTPUT);
    pinMode(pinD, OUTPUT);
    pinMode(pinE, OUTPUT);
    pinMode(pinF, OUTPUT);
    pinMode(pinG, OUTPUT);
    pinMode(D1, OUTPUT);  //Turns the first digit on.
    pinMode(D2, OUTPUT);  //Turns the second digit on.
    pinMode(D3, OUTPUT);  //Turns the third digit on.
    pinMode(D4, OUTPUT);  //Turns the forth digit on.
    }

    //
    void showTime(){

      digitalWrite(D1, LOW);
      digitalWrite(D2, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(D4, LOW);

     //3
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      delay(1000);

    //2
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      delay(1000);

      //1
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      delay(1000);

      //0
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      delay(1000);

    }

    //Receives the chars from the matrix keyboard.
    void getCode(){
       char key = mykeypad.getKey();
      if(key){
         Serial.print(key);
      }
    }

    void loop()
    {

      showTime();

    }

Any idea on how can I archieve this combination? Have been trying to find something similiar to a Thread, but Arduino doesn't support it.

Thanks in advance.

title: Matrix keyboard and 7segment display countdown combination

Answers: 2

body:
Use the "blink without delay" examples in the IDE, whereby you perform an action and then basically watch the clock until and let the rest of the code run until the time elapes.  For example, this blinks the onboard LED on and off, you can add to it for your keypad reading and time outputs.

    unsigned long currentTime;
    unsigned long previousTime;
    unsigned long elapsedTime;
    const byte ledPin = 13;
    byte ledState = 0;

    void setup(){
    pinMode (ledPin, OUTPUT);
    previousTime = millis();
    }
    void loop(){
    currentTime = millis();  // capture the 'time' now
    elapsedTme = currentTime - previousTime; // how much 'time' has passed
    if (elapsedTime >= 1000){  // at least one second?
    ledState = 1 - ledState; // results in 1,0,1,0,1,0 ...
    digitalWrite (ledPin, ledState); // toddle the L led
    previousTime = currentTime;   // set up for the next pass thru loop
    // update the to display, and output it
    }
    // now add keypad reading stuff
    }

body:
Try using `millis()`, it returns the number of milliseconds passed since the Arduino board began running the current program.

When you start the countdown you set a variable for a beginning time

`int millisBegin = millis(); //put this at the end of your setup() {}`.

You will also need a "border" to know when one second is over, so

`int millisBorder = 1000; //one second border`

Every time your the `loop() {}` starts over you can check if one second has passed so far

    int millisNow = millis();
    if(millisNow - millisBegin >= millisBorder){} //if one second over, do {}

Now I would work on the segment showing thingy. In the `{}` I would put a new variable, let's call it `counter = 4; //4 because I found 3 numbers in your sketch`. Every time the `if() {}` is being executed, you go through more `if () {}` statements, checking what number to display next.

    if (counter == 3)
    {
      //show number 3
    }

    if (counter == 2)
    {
      //show number 2
    }

    if (counter == 1)
    {
      //show number 1
    }

    if (counter == 0)
    {
      //show number 0
    }
    counter = counter - 1;

At the end we take one off the counter, so the next time we enter the `if(one second over)` the number displayed will get lower

And well now there are multiple ways of doing the keyboard thingy. You can keep checking if there is a key available, and if so you can safe it as a String (most people hate strings, but I never had a problem with them to be honest).

After you've saved the key as a String you can use the `strcmp();` method to compare the string with the solution/answer `strcmp(key,answer);`. If the key and the answer are the same, it will return 1.

    if(strcmp(key,answer) == 1)
    {
      Serial.println("you made it");
    }


body:
I use an Arduino Uno for controlling one DC motor speed with PWM and one dimmer for control heater.
The dimmer and PWM control worked standalone, but when I want them to work together, the dimmer doesn't work.

    #include  <TimerOne.h>          /
    #include <Wire.h>

     //////////////                    //pin 2 zero kesmesi icin
    int isiticiPWM = 9;                //  Opto Triac isitici PWM icin
    int fanPWM=11;                     //motor pwm pini

    int hiz=0;

    volatile int i=0;               // Variable to use as a counter volatile as it is in an interrupt
    volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero

    char   data ;
    int dim = 255;                    // Dimming level (0-128)  0 = on, 128 = 0ff
    int inc=5;    // counting up or down, 1=up, -1=down
    int freqStep = 75;    // This is the delay-per-brightness step in microseconds.

    void zero_cross_detect() {
      zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
      i=0;
      digitalWrite(isiticiPWM, LOW);       // turn off TRIAC (and AC)
    }

    // Turn on the TRIAC at the appropriate time
    void dim_check() {
      if(zero_cross == true) {
        if(i>=dim) {
          digitalWrite(isiticiPWM, HIGH); // turn on light
          i=0;  // reset time step counter
          zero_cross = false; //reset zero cross detection
        }
        else {
          i++; // increment time step counter
        }
      }
    }
    ///////////////
    void setup() {

      pinMode(fanPWM,OUTPUT);
      pinMode(isiticiPWM, OUTPUT);

        attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to----------------------------------->  Pin 2 (interupt 0) for Zero Cross Detection <<------------------------------------------------
        Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
        Timer1.attachInterrupt(dim_check, freqStep);

    }

    void loop()
    {
    hiz=450;analogWrite(fanPWM,hiz);

    for(int k=0;k<=255;k++)
    {dim=k;
    }

      }

title: Use PWm and zero_cross_detect interrupt

Answers: 0