body:
My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.

I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.

My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?

What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.

EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

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

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

title: Arduino Due not executing code after power on

Answers: 1

body:
After some more research I found out that

a) the issue applies to some Due boards only, not all

b) newer boards seem to have fixed the issue

c) there's a software (firmware update) and hardware (10k resistor) solution

I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/

I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

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

addendum:

The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.

The fix is simple: you just solder a 10K resistor across the top of this mosfet:

resistor about to be soldered on

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

resistor designated as R99

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/gywtn.jpg
  [2]: https://i.stack.imgur.com/FX8a7.jpg
  [3]: https://i.stack.imgur.com/ZeWgn.png


body:
Where is the definition of [`uint16 system_adc_read(void)`][1] in the [esp8266 Arduino code][2]?

I can see it being declared in `Arduino/tools/sdk/include/user_interface.h`, however there seems to be no definition of this. `system_adc_read()` gets called in [`analogRead()`][3] in `Arduino/cores/esp8266/core_esp8266_wiring_analog.c`

I suspect `system_adc_read()` calls [`system_adc_read_fast()`][4] to read the ADC, but can't actually find it in the code! Could somebody please point me to this? I've been struggling for quite some time.

***Purpose:** To manipulate the system_adc_read() in ESP8266 to get higher ADC sampling rates. Right now ADC sampling rate is 10ksps. I want it to be more than 30-40ksps.*

  [1]: https://github.com/esp8266/Arduino/blob/d24a358817f0c11f7087b3c8acbf24629b15998f/tools/sdk/include/user_interface.h#L119
  [2]: https://github.com/esp8266/Arduino
  [3]: https://github.com/esp8266/Arduino/blob/4897e0006b5b0123a2fa31f67b14a3fff65ce561/cores/esp8266/core_esp8266_wiring_analog.c#L33
  [4]: https://github.com/esp8266/Arduino/blob/d24a358817f0c11f7087b3c8acbf24629b15998f/tools/sdk/include/user_interface.h#L120

title: Where is the definition of system_adc_read() in the esp8266 Arduino code?

Answers: 1

body:
The "definition" of `uint16 system_adc_read(void)` is inside the compiled archive/object file `libmain.a` inside one of the `NONOSDK` folders which is located in `/tools/sdk/lib/` . The version is selected in `platform.txt`. For example in my platform.txt:

    # default SDK for all boards
    # (generic board overrides this variable)
    build.sdk=NONOSDK22x_190703
    #build.sdk=NONOSDK22x_191024
    #build.sdk=NONOSDK22x_191105

Running the `xtensa-lx106-elf-objdump.exe -d` on this file I can find this section inside:

    00000258 <system_adc_read>:
         258: 020c                 movi.n a2, 0
         25a: f0c112                addi a1, a1, -16
         25d: 0109                 s32i.n a0, a1, 0
         25f: fffc01                l32r a0, 250 <system_pp_recycle_rx_pkt+0x18>
         262: 0000c0                callx0 a0
         265: fff901                l32r a0, 24c <system_pp_recycle_rx_pkt+0x14>
         268: f42020                extui a2, a2, 0, 16
         26b: 1b1207                beq a2, a0, 28a <system_adc_read+0x32>
         26e: b30c                 movi.n a3, 11
         270: 902220                addx2 a2, a2, a2
         273: 1122e0                slli a2, a2, 2
         276: fff701                l32r a0, 254 <system_pp_recycle_rx_pkt+0x1c>
         279: 0000c0                callx0 a0
         27c: f42020                extui a2, a2, 0, 16
         27f: 00a402                movi a0, 0x400
         282: 013027                bltu a0, a2, 287 <system_adc_read+0x2f>
         285: 020d                 mov.n a0, a2
         287: f42000                extui a2, a0, 0, 16
         28a: 0108                 l32i.n a0, a1, 0
         28c: 10c112                addi a1, a1, 16
         28f: f00d                 ret.n
         291: 00                       .byte 00
         292: 00                       .byte 00
         293: 00                       .byte 00
         294: ff ff 00 00
     ...

    000002a0 <system_adc_read_fast>:
         2a0: e0c112                addi a1, a1, -32
         2a3: 11c9                 s32i.n a12, a1, 4
         2a5: 21d9                 s32i.n a13, a1, 8
         2a7: 31e9                 s32i.n a14, a1, 12
         2a9: 5129                 s32i.n a2, a1, 20
         2ab: 41f9                 s32i.n a15, a1, 16
         2ad: 0109                 s32i.n a0, a1, 0
         2af: 03fd                 mov.n a15, a3
         2b1: fff901                l32r a0, 298 <system_adc_read+0x40>
         2b4: 0000c0                callx0 a0
         2b7: 4fbc                 beqz.n a15, 2ef <system_adc_read_fast+0x4f>
         2b9: fff6e1                l32r a14, 294 <system_adc_read+0x3c>
         2bc: 0c0c                 movi.n a12, 0
         2be: 51d8                 l32i.n a13, a1, 20
         2c0: 90dcd0                addx2 a13, a12, a13
         2c3: 001d32                l16ui a3, a13, 0
         2c6: 1a13e7                beq a3, a14, 2e4 <system_adc_read_fast+0x44>
         2c9: 902330                addx2 a2, a3, a3
         2cc: 1122e0                slli a2, a2, 2
         2cf: b30c                 movi.n a3, 11
         2d1: fff201                l32r a0, 29c <system_adc_read+0x44>
         2d4: 0000c0                callx0 a0
         2d7: f44020                extui a4, a2, 0, 16
         2da: 00a402                movi a0, 0x400
         2dd: 003d                 mov.n a3, a0
         2df: 013047                bltu a0, a4, 2e4 <system_adc_read_fast+0x44>
         2e2: 043d                 mov.n a3, a4
         2e4: 005d32                s16i a3, a13, 0
         2e7: cc1b                 addi.n a12, a12, 1
         2e9: f4c0c0                extui a12, a12, 0, 16
         2ec: ce9fc7                bne a15, a12, 2be <system_adc_read_fast+0x1e>
         2ef: 11c8                 l32i.n a12, a1, 4
         2f1: 21d8                 l32i.n a13, a1, 8
         2f3: 31e8                 l32i.n a14, a1, 12
         2f5: 41f8                 l32i.n a15, a1, 16
         2f7: 0108                 l32i.n a0, a1, 0
         2f9: 20c112                addi a1, a1, 32
         2fc: f00d                 ret.n
         2fe: 00                       .byte 00
         2ff: 00                       .byte 00
         300: ff ff 00 00
     ...


body:
I'm a day 1 beginner to Arduino, and I am trying to obtain input from a USB keyboard. I've connected the USB keyboard to an Arduino USB host shield attached to an Arduino Uno r3, and I am using the example HID sketch (USBHIDBootKeyboard.ino) provided with the USB Host Shield libraries : https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino

I am powering the Arduino Uno r3 + USB Host Shield via USB. Upon init, only Start is written to the Serial Monitor. Tests show that SetReportParser exits with 0. Yet the keyboards are silent. I've tried three keyboards, all of which work properly when connected to the computer.

When using USBHidBootMouse.ino with a mouse, movements & buttons are perceived and print messages as intended.

https://www.circuitsathome.com/mcu/hid-support-for-usb-host-shield-library-2-0-released/ states that

> Also, it is recommended to use external power supply while working with HID devices – I’ve seen many devices which would refuse to function when Arduino receives power from its USB port only.

EDIT : I tried to test if the power was the issue, so I used a 5V generator with intensity measurement. The results are : the Arduino Uno r3 uses 60mA, the keyboard uses 60 mA, connecting to the serial port uses 40 mA (much to my surprise).

This means the keyboard's power requirements shouldn't be the problem.

Then what would the problem be ? I'm helpless here. If the library linked on the official Arduino site doesn't work, then it should mean i'm using it wrong.

title: Uno r3 - Can't get USB Keyboards to work with an USB Host Shield

Answers: 2

body:
I looked for the difference between USBHIDBootMouse & USBHIDBootKbd, and noticed line 100,

>USBHub     Hub(&Usb);

was commented in the BootKbd side. Uncommenting it got the code to work.

I'm quite unsure how what interpretation to have from this. There should be a reason this line is commented in the library github.

Or maybe it is simply an error. In any case, uncommenting it got the code to work here.

body:
see last paragraph of this page https://github.com/felis/USB_Host_Shield_2.0

it says this:

> FAQ
>
>
> When I plug my device into the USB connector nothing happens?
>
>
> Try to connect a external power supply to the Arduino - this solves
> the problem in most cases.
>
>
> You can also use a powered hub between the device and the USB Host
> Shield.
>
>
> You should then include the USB hub library: `#include <usbhub.h>`
>
>
> and create the instance like so: `USBHub Hub1(&Usb);`.

your keyboard may be multiple HID devices with a USB hub to connect them


body:
I'm trying to light up 81 on a 4-digit 7-segment display, but when I try to upload the code to my Uno R3 it gives me this error: "a function-definition is not allowed here before '{' token". I'm new to Arduino and this is my second day using it, so I would like to get help and know how to fix this problem. Here is my code:

    int isej1 = 2;
    int isej2 = 3;
    int vienetas[] = { 12, 11 };
    int astuonetas[] = { 13, 12, 11, 10, 9, 8, 7 };

    void setup() {
      pinMode (vienetas[2], OUTPUT);
      pinMode (astuonetas[8], OUTPUT);
      pinMode (isej1, OUTPUT);
      pinMode (isej2, OUTPUT);
    }

    void uz_vien() {
      digitalWrite (vienetas[0], HIGH);
      digitalWrite (vienetas[1], HIGH);
    }

    void uz_astuon() {
      digitalWrite (astuonetas[0], HIGH);
      digitalWrite (astuonetas[1], HIGH);
      digitalWrite (astuonetas[2], HIGH);
      digitalWrite (astuonetas[3], HIGH);
      digitalWrite (astuonetas[4], HIGH);
      digitalWrite (astuonetas[5], HIGH);
      digitalWrite (astuonetas[6], HIGH);
    }

    void is_vien() {
      digitalWrite (vienetas[0], LOW);
      digitalWrite (vienetas[1], LOW);
    }

    void is_astuon() {
      digitalWrite (astuonetas[0], LOW);
      digitalWrite (astuonetas[1], LOW);
      digitalWrite (astuonetas[2], LOW);
      digitalWrite (astuonetas[3], LOW);
      digitalWrite (astuonetas[4], LOW);
      digitalWrite (astuonetas[5], LOW);
      digitalWrite (astuonetas[6], LOW);

    void loop() {
      digitalWrite (isej1, LOW);
      digitalWrite (isej2, HIGH);
      void uz_vien();
      delay(5);
      void is_vien();
      digitalWrite (isej1, HIGH);
      digitalWrite (isej2, LOW);
      void uz_astuon();
      delay(5);
      void is_astuon();
    }

title: A function-definition is not allowed here before '{' token

Answers: 2

body:
You are missing a "}" just before `loop`

      void is_astuon() {
        digitalWrite (astuonetas[0], LOW);
        digitalWrite (astuonetas[1], LOW);
        digitalWrite (astuonetas[2], LOW);
        digitalWrite (astuonetas[3], LOW);
        digitalWrite (astuonetas[4], LOW);
        digitalWrite (astuonetas[5], LOW);
        digitalWrite (astuonetas[6], LOW);
       } // <- missing here.
      void loop() {

body:
The importance of proper indentation is clear here...

I thought you were missing a closing curly braces. When you type code, press regularly cmd/ctrl-T to ident your code -- it helps catching mistakes. You are indeed missing one, for `is_astuon()`.

Moreover these lines are wrong too:

    **void** uz_vien();
    delay(5);
    **void** is_vien();
    digitalWrite (isej1, HIGH);
    digitalWrite (isej2, LOW);
    **void** uz_astuon();

The `void` part is not needed and creates the error.


body:
I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor.  I am using the HC-SR04 with the Elegoo Mega2560 Arduino board.  A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly.  I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place.  No matter what, the distance stayed between 90 and 120, mainly staying in the 110s.  These numbers seemed to have no correlation with the actual distance.  I even tried to calculate the distance myself in case there was something wrong with the library.

I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino.  The Arduino is connected to my computer through USB.

Here is my sketch for printing out the distance without a library:

    const int triggerPIN = 50;  //these are digital pins on the Arduino board
    const int echoPIN = 52;     //I'm sure these pins aren't broken because I never used them before now

    long duration;
    int distance;

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

        pinMode (triggerPIN, OUTPUT);
        pinMode (echoPIN, INPUT);

        delay(1000);
    }

    int getDistance () {
        digitalWrite (triggerPIN, LOW);
        delayMicroseconds (2);

        digitalWrite (triggerPIN, HIGH);
        delayMicroseconds (10);
        digitalWrite (triggerPIN, LOW);

        duration = pulseIn (echoPIN, HIGH);
        distance = duration * 0.034 / 2;

        Serial.println (distance);
    }

    void loop() {
        getDistance ();  //I tried putting the code directly in the loop function with the same result
    }

I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries.  Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor?  If so, how should I prevent this in the future?  I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V?  I wanted to know for sure that it was broken and not an error on my part before I bought a new one.    Thanks in advance!

title: Is my HC-SR04 sensor broken?

Answers: 3

body:
The code that you have provided for the distance calculation is fine according to me. There is a high chance that you might have damaged your HC-SR04, Ultrasonic sensor.

As you have asked about how to prevent this from happening in the future, I would suggest that you should use a voltage regulator in the circuit, LM7805, it restricts the output voltage to 5V - just matching your ultrasonic sensor's operating voltage as it works perfectly at 5 Volts.

body: I guess the main problem is a serial printing. It always bother the system mainly the analog reading. It's quiet good for check some sub result while you programing (what the return value from a method etc) but not good to test your project result. In this case the distance measurement. Try a different way, put some led into the circuit and if the distance over 10cm switch on first, if over 20 cm switch on the second and so on. Or write the result  on an lcd panel, or 8x8 led.

body:
A major functional difference between the code in your question and the usual ping sensor example is that your code repetitively measures as fast as it or the output stream will allow.

In contrast, the normal example has a `delay(100)` after each measurement cycle.  This allows 1/10th of a second time for any longer room echoes to die out, and thus avoid confusing new measurements.

While that might not be your immediate or only problem, it is generally a good idea not to try to take sonar measurements so closely spaced in time that they could overlap.

Should your sketch also need to do other things, instead of a blocking `delay()` you can check the elapsed time and only take a new sonar measurement once a certain amount of time has passed; in the meantime your program can continue with any other critical operations.


body:
I have both an Arduino Uno and an Arduino Nano but I can't decide which one to use for my project. My aim is to maximize battery lifetime. I have also implemented an 8-second watchdog timer to periodically sleep and wake up the ATMega328P.

 - Option 1: Arduino Uno R3 + DHT11 sensor: The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Uno specification** DC Current per I/O Pin 40 mA, DC Current for 3.3V Pin 50 mA).

 - Option 2: Arduino Nano + DHT11 sensor. The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Nano specification**: DC Current per I/O Pin: 40 mA but **NO** information for DC current for 3.3V or 5V).

I would like to know which one will be more power-efficient.

title: Arduino Uno versus Arduino Nano power consumption

Answers: 2

body:
Don't use either use something with no USB, regulator - e.g. Pro Mini (run from 3.3V)

Just running the Arduino (or indeed most digital circuitry) from a lower voltage will already reduce power consumption - admittedly at a slight cost in processor speed. The Atmega328P will run at 12MHz on 3.3V, although the Pro Mini uses the more conservative 8MHz.

body:
A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.

If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.

You can save a considerable amount of power by using sleep modes as I describe on [my page about power](http://www.gammon.com.au/power). It also helps to use a bare processor (no voltage regulator, no LEDs).

I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for **over a year** without needing new batteries.

---

> I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

---

It's *not that hard* to make a minimal board. I have a [page about doing that](http://www.gammon.com.au/breadboard). Example of all you need:

[![Minimal Arduino][1]][1]

---

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.

My temperature sensor uses an average of 42 µA which is a **lot** less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)

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


body:
I decided to try out my servo on my Arduino. I'm pretty new to this and I can't seem to figure out why this is happening. My servo will spin for about 5 seconds in one direction and then it will spin the opposite way for less than a second and pause for about 3 seconds. This is the code I uploaded to my Arduino:

    # include <Servo.h>
    const int servopin = 8;
    Servo servo;

    void setup() {
      Serial.begin(9600);
      servo.attach(servopin);
      servo.write(0);
    }

    void loop() {
      servo.write(0);
      delay(5000);
      servo.write(180);
      delay(5000);
    }

I believe the servo is a Tower Pro Micro Servo 99 (either 9 might be a g) SG90.

title: Why is my servo spinning over 360 degrees?

Answers: 2

body:
I might want to try decreasing the range, e.g. start from 10 instead of 0, or finish at 170 instead of 180. Here is an example:

    # include <Servo.h>
    const int servopin = 8;
    Servo servo;

    void setup() {
      Serial.begin(9600);
      servo.attach(servopin);
      servo.write(0);
    }

    void loop() {
      servo.write(10);
      delay(5000);
      servo.write(170);
      delay(5000);
    }

After checking it works, try experimenting with different ranges to see how your servo reacts.

**For me starting at 7 instead of 0 did the job.**

body:
When I am getting started with my Servo motor SG90, I have experience the same issue, and finally I have solved the issue. I have used external power supply for Servo and my Arduino with laptop USB port and control signal from Arduino to Servo motor make my Servo motor to spinning continuously.

Make sure ground reference of power supply of Servo motor and Arduino are same.


body:
I'm working on a project to send ultrasonic sensor data to my webserver. For that I'm using ESP8266  WiFi module, 3.3V regulator IC by giving input volt of 5v from aduino uno.

I successfully uploaded a code but in serial monitor I got an error

    ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset.

Please, tell what does it mean?

Here is my code. Guide me if I made something wrong. Thanks in  advance.

**Note:**
Before sending sensor values I successfully send a raw data  manually to webserver, i.e string data, but when I try to send sensor values, I got an error.

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    const char* ssid = "VENTURE 11";
    const char* pass = "12345678";

    WiFiClient clientx;
    const int trigPin = 8;  //Digital port D5
    const int echoPin = 9;  //Digital port D6

    long duration;
    float distance;
    float Mdistance;
    float MAX_HEIGHT = 0;

    void setup() {

      Serial.begin(115200);                                  //Serial connection
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT);

      WiFi.begin("VENTURE 11", "12345678");   //WiFi connection
      Serial.println("Setup iniated");
      while (WiFi.status() != 3) {  //Wait for the WiFI connection completion
        delay(500);
        Serial.println("Waiting for connection");
        Serial.print("WIFI STATUS : ");
        Serial.println(String(WiFi.status()));
      }
      Serial.println(String(WiFi.status()));
    }

    void loop() {
      Serial.println(String(WiFi.status()));
      if (WiFi.status() != 3)
      {
        WiFi.begin("VENTURE", "12345678");   //WiFi connection
        while (WiFi.status() != 3)
        {
          Serial.println("Waiting for connection");
        }
      }
      else
      {
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);

        // Sets the trigPin on HIGH state for 10 micro seconds
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);

        // Reads the echoPin, returns the sound wave travel time in microseconds
        duration = pulseIn(echoPin, HIGH);

        // Calculating the distance
        distance = (duration * 0.034) / 2;

        if (MAX_HEIGHT == 0) {
          //MAX_HEIGHT = distance;
          Serial.print("Max height has been set to ");
          //Serial.print(distance);
          Serial.println(" cm");
          Serial.println("Waiting for 5 seconds...");
          delay(5000);
        } else {
          Serial.print("Distance:\n");
          Serial.print(distance);
          Serial.print("cm\n");
          Serial.print("Distance:\n");
          Serial.print(distance / 100);
          Serial.print("m\n");
          delay(1000);

        }

        HTTPClient http;
        String Data = "x=" + (String)distance + "&y=" + (String)MAX_HEIGHT + "&z=0";
        //String Data = "x=Finally&y=Did&z=it;)";
        http.begin("http://testingblahblah.000webhostapp.com/IOTCON.php");
        http.addHeader("Content-Type", "application/x-www-form-urlencoded");
        int sent = http.POST(Data);
        Serial.println(sent);
        String httpPayload = http.getString();
        Serial.println(httpPayload);
        if (sent > 0)
        {
          Serial.println("Message has been sent");
        } else {
          Serial.println("unable to send data");
        }
        delay(20000);

      }
    }`

title: Getting error ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset

Answers: 2

body:
Your `loop()`:

    void loop() {
      Serial.println(String(WiFi.status()));
      if (WiFi.status() != 3)
      {
        WiFi.begin("VENTURE", "12345678");   //WiFi connection
        while (WiFi.status() != 3)
        {
          Serial.println("Waiting for connection");
        }
      }
      else
      {
        // Other code...
      }
    }

While waiting for the connection, you are creating `String` objects at a very high rate, since your `delay(20000)` is in the `else` clause.

This means you are possibly running out of memory, as you are creating the `String` objects with every iteration, which is in the Megahertz range.

You likely don't need the `String(...)` wrappers, as the `Serial.println()` function can work with C-style strings returned by the `WiFi` library. Then, your program won't be allocating memory to hold the result of `WiFi.status()` millions of times per second, which you don't use later on in your program.

body:
Found a possible solution.
I was facing with the same problem.
Apparently this is a hardware stack overflow watch dog preventing malfunction. This may not apply to every possible scenario but I discovered that the allocated pin number on the board itself is incorrect.
What is numbered 03 is in fact D15 for example. So assigning the pin to D15 worked but 3 created this error.
I hope this helps others.


body:
I'm working on an automotive project that uses an Arduino Mega 2560.

What I need is a circuit that allows the unit to sense when the external power feed drops (triggering an interrupt?) so that the software can preserve state to the non-volatile memory and then shut down.

I was thinking some sort of capacitor/battery to run it once the eternal feed drops, but the hardware side of things is not my strong skillset - I'm more of a software kinda person.

title: Controlled power-down for automotive application

Answers: 1

body:
Consider a battery backup for low power devices.  [This article][1] from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.

In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs.  When the 12 volts shuts off, the signal to the processor's digital input will go low.  Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.

The [ATmega2560][2] processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.

  [1]: https://www.allaboutcircuits.com/projects/battery-backup-power-supplies/
  [2]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


body:
I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from [this site][1].

    #include ESP8266WiFi.h>
    #include SPI.h>
    #include MFRC522.h>

    const char* AP_SSID ="IoT4143" ;
    const char* AP_PASSWORD ="iot4143";

    #define RST_PIN D3
    #define SS_PIN D4

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    WiFiServer server(80);
    WiFiClient client;

    void wifiConnect() {
      WiFi.disconnect();
      WiFi.softAP(AP_SSID, AP_PASSWORD);

      int watchDog = 0;
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        watchDog++;
        if(watchDog == 60) {
          WiFi.disconnect();
          WiFi.printDiag(Serial);
          watchDog = 0;
          return;
        }
      }
      server.begin();
    }

    void setup() {
      Serial.begin(115200);
      SPI.begin();      // Init SPI bus
      mfrc522.PCD_Init();   // Init MFRC522
      mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
      Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
      wifiConnect();
    }

    void loop() {
      //Are we connected to WiFi?
      if(WiFi.status() != WL_CONNECTED) {
        wifiConnect();
      }

      //Wait for a connection attempt
      client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      int watchDog = 0;
      while(!client.available()) {
        delay(1);
        if(watchDog == 10000) {
          watchDog = 0;
          return;
        }
        watchDog++;
      }
      sendData();
    }

    void sendData() {
      // Read the first line of the request
      String request = client.readStringUntil('\r');
      client.flush();

      // Match the request
      while(request=="READSTOP") {
        Serial.println("RFID READING STARTED..."); //Forward to C# App
        if (!mfrc522.PICC_IsNewCardPresent()) {
          return;
        }
        // Select one of the cards
        if (!mfrc522.PICC_ReadCardSerial()) {
          return;
        }
        // Dump debug info about the card; PICC_HaltA() is automatically called
        client.print(mfrc522.uid));
      }
      Serial.println("RFID READING STOPPED"); //Stop server
      delay(1);
      client.stop();
    }

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.

When I verified the code in the Arduino IDE, there was an error on this line of code:

    client.print(mfrc522.uid));

>error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.

Please help!

  [1]: http://tdmts.net/2017/02/04/controlling-an-arduino-with-a-wifi-esp8266-adapter-using-a-windows-10-universal-app/

title: How to send MFRC522 data to a C# app using a NodeMCU TCP server?

Answers: 1

body:
MFRC522::uid is a struct ([see source code][1]). There's no defined way to print it.

If you want to write the raw bytes over the TCP connection, you can just use

    client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

If you want to write it as ASCII text, you can use the following:

    void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
      buff[0] = nibble_to_hex(val >> 4);
      buff[1] = nibble_to_hex(val);
    }

    char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
      nibble &= 0xF;
      return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
    }

    void printHEX(Stream &s, uint8_t *data, size_t length) {
      char *buffer = new char[length*2];
      for (size_t i = 0; i < length; i++) {
        byte_to_str(&buffer[i*2], data[i]);
      }
      s.write(buffer, length*2);
      delete[] buffer;
    }

Then use it like this:

      printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.

(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '<'.)

  [1]: https://github.com/miguelbalboa/rfid/blob/19461b34d38871ba2722dab7a3a76028eddebaa1/src/MFRC522.h#L315-L320


body:
I want to detect if a push button was pressed and released again. So I thought the right approach would be to first wait while the pin yields `LOW` and then wait while the pin yields `HIGH`:

    void push(int pin) {
      // wait until button was pushed down...
      while (digitalRead(pin) == LOW);
      // ... and released again
      while (digitalRead(pin) == HIGH);
    }

That function can be easily reused. The code works fine, but I am just wondering if that solution is considered clean and a good practice.

title: Detecting if a push button was pressed and released

Answers: 3

body:
No, I wouldn't consider that good practice - for one good reason: it's blocking.

Your system can't be doing anything else at all while you're waiting on the button. That may be fine for some situations, but far from ideal for 99% of others.

It is better to remember the state of the button and detect that change of state.

Personally, to make it properly portable, I would implement a class to contain all the state information.  Something like:

    class Button {
        private:
            bool _state;
            uint8_t _pin;

        public:
            Button(uint8_t pin) : _pin(pin) {}

            void begin() {
                pinMode(_pin, INPUT_PULLUP);
                _state = digitalRead(_pin);
            }

            bool isReleased() {
                bool v = digitalRead(_pin);
                if (v != _state) {
                    _state = v;
                    if (_state) {
                        return true;
                    }
                }
                return false;
            }
    };

Then you can do something like:

    Button myButton(3);

    void setup() {
        myButton.begin();
        Serial.begin(115200);
    }

    void loop() {
        if (myButton.isReleased()) {
            Serial.println(F("Released"));
        }
    }

Every time `myButton.isReleased()` is called the current button state is compared against the state it was last time it was called. If it's changed then the button must either have been pressed or released. So you remember that change. If it's been released then you return a `true`, otherwise return a `false`.

You can now easily have it work with many buttons:

    Button myButton(3);
    Button myOtherButton(4);

    void setup() {
        myButton.begin();
        myOtherButton.begin();
        Serial.begin(115200);
    }

    void loop() {
        if (myButton.isReleased()) {
            Serial.println(F("Released 1"));
        }
        if (myOtherButton.isReleased()) {
            Serial.println(F("Released 2"));
        }
    }

body:
I concur with [Majenko][1], although your code would work, the code is blocking, meaning that your code stops at that point until the button is released again. The remaining code in your loop does not execute until the button is resolved.

A much better method is to check the state of the button in each passing of the loop. If the state changes (ie goes low) you can set a flag. Then when you read that the button is high again and the flag has been set then you execute the appropriate code. For example:

    const int buttonPin = 2;     // the number of the pushbutton pin
    boolean buttonWasLow = false;         // variable flag for when the pushbutton goes low

    void setup() {
        pinMode(buttonPin, INPUT);    // initialize the pushbutton pin as an input:
    }

    void loop() {
        // read the state of the pushbutton and set a flag if it is low:
        if (digitalRead(buttonPin) == LOW)  {
            buttonWasLow = true;
        }

        // This if statement will only fire on the rising edge of the button input
        if (digitalRead(buttonPin) == HIGH && buttonWasLow)  {
            // reset the button low flag
            buttonWasLow = false;

            // Button event here
        }
    }

My favorite way to detect a rising edge of an input is actually much simpler:

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

        // If the button is pressed
        if (button && !buttonLast)
        {
            // Button event here
        }

        // Update button flag
        buttonLast = button;
    }

[user8886193][2] brings up the very good point about [button debounce][3].

>Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple signals as the contacts close or open; debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact.

I prefer to debounce the pushbutton inputs through hardware by adding a 100nF (or larger) from the input pin to ground. Note that this requires a 10K (or larger) resistance in series with the button circuit in order for the capacitor to charge/discharge.

Alternatively, in software, the most common debounce for beginners is adding a delay such as `delay(100);`, which would look something like this:

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

        // If the button is pressed
        if (button && !buttonLast)
        {
            // Button event here
            delay(100);  // <---- Delay inserted after the button event
        }

        // Update button flag
        buttonLast = button;
    }

This has the downside that it is blocking for 100ms while the delay executes. A better method is to debounce without a delay. One of the built in examples demonstrates [button debounce][4]. The main loop is shown below:

    void loop() {
        // read the state of the switch into a local variable:
        int reading = digitalRead(buttonPin);

        // check to see if you just pressed the button
        // (i.e. the input went from LOW to HIGH), and you've waited long enough
        // since the last press to ignore any noise:

        // If the switch changed, due to noise or pressing:
        if (reading != lastButtonState) {
            // reset the debouncing timer
            lastDebounceTime = millis();
        }

        if ((millis() - lastDebounceTime) > debounceDelay) {
            // whatever the reading is at, it's been there for longer than the debounce
            // delay, so take it as the actual current state:

            // if the button state has changed:
            if (reading != buttonState) {
                buttonState = reading;

                // only toggle the LED if the new button state is HIGH
                if (buttonState == HIGH) {
                    ledState = !ledState;
                }
            }
        }

        // set the LED:
        digitalWrite(ledPin, ledState);

        // save the reading. Next time through the loop, it'll be the lastButtonState:
        lastButtonState = reading;
    }

  [1]: https://arduino.stackexchange.com/a/48244/19409
  [2]: https://arduino.stackexchange.com/a/48250/19409
  [3]: http://whatis.techtarget.com/definition/debouncing
  [4]: https://www.arduino.cc/en/Tutorial/Debounce

body:
> "I usually put a capacitor next to my push button"

A 1uF capacitor across the button is easy, cheap and means no need to fiddle with debouncing codes. See Nick Gammon's [excellent switch tutorial][1] that covers almost any conceivable situation when using switches with Arduinos and clones (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.). In any case, Nick Gammon has many great explanatory examples on his site and where else he comments online.

  [1]: http://www.gammon.com.au/switches


body:
As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:

ICSP is used for programming with a bootloader in MCU.

The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.

Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

title: Purpose of USB (FTDI) and ICSP connectors

Answers: 1

body:
The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.

The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.

The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.


body:
I'm dabbling in a project and would like to add a feature, but I need some help from the community.

My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.

If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.

Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.

Is this a pie in the sky proposition, or something that could be implemented?

Thanks for your input.

title: Is there GUI to flash a sketch with new variables?

Answers: 1

body:
The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.

Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.

The configuration parameters are written to EEPROM so that they will be preserved.

In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.

Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.


body:
What is the best method or retrieving information such as temperature from multiple wifi clients with a ESP8266-01 ?
I have one server and five client running with ESP8266.
I have seen post ang Get method. JSON files. client-server transfers.
What is the best method to do that ?
I am reading temperature so I do not need the clients to be all connected at the same time. So reading the client one after another in a loop would be great.
thanks in advance

Ken

title: Connecting multiple clients to a server in Wifi

Answers: 1

body:
you do not need http for this. use plain socket communication. create a WiFiServer on every 'sensor' and ask from the main esp8266 over WiFiClient object. the WiFiServer creates a WiFiClient object and the Clients can exchange what you want.

snippet from my code:

    void loop() {
      WiFiClient client = telnetServer.available();
      if (!client) {
        delay(100);
        return;
      }
      if (client.status() != 4) {
        client.stop();
        delay(1000);
        return;
      }
      while (client.connected()) {
        if (!client.available())
          continue;
        char c = client.read();
        if (c == '\n') {
          long v = s.toInt();
          s = "";
          analogWrite(PWM_PIN, v);
          v = readElSens();
          client.println(v);
        } else {
          s += c;
        }
      }
      delay(100);
    }


body:
i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:

    int led=13;
    void setup() {
      pinMode(led,OUTPUT);
    }
    void loop() {
        digitalWrite(led,HIGH);
        delay (5000);
        digitalWrite (led,LOW);
    }

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us  delay (5000)  then it should turn off with  digitalWrite (led,LOW).
but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

title: prgramming arduino led on then off

Answers: 3

body: It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.

body:
That delay does not do anything but wasting 5 seconds...you need to do like:

    void loop() {
        digitalWrite(led,HIGH);
        delay (2500);
        digitalWrite (led,LOW);
        delay (2500);
    }

The code runs sequentially...in your code after turning off the led it immediately turns it on again and waits 5 seconds...this is so fat that you do not notice it.

body:
The "loop()" will keep repeating itself, turning the led on and off forever.
If you want turn the led on just once, put the commands for turn the led on in "setup()" section:

void setup() {
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}
void loop() {
}

Other method would be add a variable to count how much times the led should light. I copied the following sketch from [here][1]

int ledPin =  13;    // LED connected to digital pin 13
int alreadyBlinked = 0;

// The setup() method runs once, when the sketch starts
void setup()   {
pinMode(ledPin, OUTPUT);    // initialize the digital pin as an output:
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
     if(alreadyBlinked == 0)
     {
            digitalWrite(ledPin, HIGH);   // set the LED on
            delay(5000);                  // wait for five seconds
            digitalWrite(ledPin, LOW);    // set the LED off
            alreadyBlinked = 1;
      }
}

When the variable "alreadyBlinked" is set to 1, the led will not turn on again.

  [1]: http://forum.arduino.cc/index.php?topic=47983.0


body:
I have a sketch with multiple functions in it. The 2 main functions in that sketch are `get_data` and `post_data`.

Now these functions are called from `loop()`. The thing is I want these functions to run at different times. Basically I want the `get_data` function to run once every 4 minutes and the `post_data` function to run once every hour. How can I achieve that?

As far as I know, you can't run multiple programs together on an Arduino Mega.

P.S: I'm new to Arduino programming.

title: Multiple delays

Answers: 4

body:
I think you can use timer for it. In microcontroller with c you can use interrupts. You will need one timer and two compare interrupts. In the interrupts you can set different flags.

For example in first interrupt:

    ....
    getSomething = true;
    ....

For example in second interrupt:

    ....
    postSomething = true;
    ....

For example in your loop:

    ....
    if(postSomething){
    //your code to post something
    postSomething = false;
    }

    if(getSomething){
    //your code to get something
    getSomething = false;
    }

These functions are only called when the timer interrupt is called (the time reached). In the Handler you set the flag (do not execute big code). In loop you can check if a flag is set and execute than the code. I think in Arduino you can do the same.

body:
If you don't need absolute precision, I've written a timer class that doesn't use an interrupt: [TimerAction][1]. Usage to simply subclass the base object, define an `action()` method in the subclass, construct your subclass defining the time interval to run, and place a call to the object's `loop()` method in your main `loop()` function in every sketch.

In your case, you'd create a subclass for each of your `get_data` and `post_data` actions. This would require two objects to be constructed, and both of them having their `loop()` method called in the main `loop()` function.

  [1]: https://github.com/michaelkamprath/ShiftRegisterLEDMatrixLib/blob/master/src/TimerAction.h

body:
I imagine that you tried to figure out how to do it whit the `delay()` function (if it's not your case, it is for most Arduino beginners). Well... you can't use `delay()` in this case (and in most other cases) because it completely blocks the program for a given time (1) (except for interrupts, but i won't treat interrupts here). In general it is better not to use delays, except for very simple programs or in initialisation routines (i.e. in stuff you usually put in `setup()`).

---
Since your delays are quite long I imagine that you don't need much precision (i.e. you don't need to be more precise than a millisecond). So you could do like that:

<!-- language: lang-c++ -->

    void setup() {}

    // Times at which we last called the functions
    // (These are global variables, which are in general best avoided)
    unsigned long lastGetData = 0;
    unsigned long lastPostData = 0;

    void loop() {

        //                           min.  sec.  milliseconds
        if(millis() - lastGetData >= 4   * 60  * 1000) {

            lastGetData = millis();
            get_Data();
        }

        //                            min.  sec.  milliseconds
        if(millis() - lastPostData >= 60  * 60  * 1000) {

            lastPostData = millis();
            post_Data();
        }
    }

    void get_Data() {
        // ...
    }

    void post_Data() {
        // ...
    }

**Notes:**

* millis() returns the time since the startup of the Arduino in millisecond. To get more precision you could also use micros() which returns the same but in microseconds (then you would need to multiply the number in the if condition by 1000).
* you can add as much functions as you want whit different execution delays. But you must keep every function as short as possible, i.e. you must not use `delay()`s, because while executing a function if the time to execute another function comes that function will only be called after the end of the current one.
* I used the `=>` sign, and not `==`, so that even if the loop doesn't evaluates one if condition in the very milliseconds in which it becomes true it can positively evaluate it some milliseconds later (e.g. after the end of another running function).

body:
If it works in your situation:

    void loop() {
      static int n;

      delay(4 * 60000);
      get_data();

      if (n-- == 0) {
        post_data();
        n = 14;
      }
    }

You may need to adjust the 14 and post-decrement to fit your needs.


body:
I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick).
Is it possible to access the digital pins of the UNO from the ATmega16U2?

title: Accessing digital pins from the Atmega 16u2 on the Uno

Answers: 2

body: No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.

body:
There is a 4-pin header JP2 on the board that brings out the following pins from the '16U2

    PB4, PB5, PB6, PB7

and the ICSP connector

    PB1, PB2, PB3


body:
I have two sparkfun redboards. Neither board will allow a sketch to be uploaded from the Arduino IDE.

I plug in a board and it powers on. In the Arduino software I select Tools->Port->COM4 (the only option) and Tools->Board->Arduino/Genuino Uno. Then compile and upload the Blink example. I get the following errors:

    Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\andy\AppData\Local\Temp\arduino_build_463875/Blink.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x5f
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x5f

    avrdude done.  Thank you.

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

I understand that this is a fairly generic error indicating failure to communicate with the board, but I don't know what to do about it. I have various Arduino Unos and Arduino Megas and can upload sketches to them without a problem. Since it seems unlikely that both redboards are faulty (different batch numbers), I suspect a software problem relating to the ftdi-based serial comms used by the redboards.

I'm using Windows 10 x64 with Arduino IDE v1.8.5 and FTDI drivers v2.12.28.0 x64 (all latest). I've also tried another windows 10 machine and a different usb cable, with the same results.

I'd appreciate any suggestions.

**Update**

I've tried using an ftdi cable to connect to the boards on pins 0 and 1. I get the same error message.

I've also tried running `avrdude` manually and varying some of the parameters. No luck with that either.

title: Unable to upload sketches to Sparkfun Redboard

Answers: 0


body:
I would like to make use of some sort of event bus on Arduino.
Lately I have been making use [Reactive Extensions][1] on a number of different platforms, Android, Angular, iOS, etc, and found them very useful.

I tried to install the library and compile something (just including the headers in the example) and I got the following error.

    /home/john/Arduino/libraries/rxcpp/rx-trace.hpp:97:57: error: 'exception_ptr' in namespace 'std' does not name a type
         inline void on_error_enter(const Subscriber&, const std::exception_ptr&) {}
                                                         ^

Before I spend too much time trying to force something that will not work, does anyone know if this will work on Arduino, or of any other event bus library that works well on the platform?

  [1]: https://github.com/Reactive-Extensions/RxCpp

title: RxCpp on Arduino?

Answers: 0


body:
This works but I would like to have a timed failsafe...

If the `FLOAT_PIN` goes `LOW` for more than 3 seconds, it will turn `SOLENOID_PIN` to `LOW`.

I can't figure out how to incorporate it into my loop. I tried `delay()` and started playing with `millis()` but all I keep finding is LED blinking samples...

I'm not very good with C++ - still learning.

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

    const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
    const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

    void setup() {
      Serial.begin(9600);
      // Since the other end of the FLOAT switch is connected to ground, we need
      // to pull-up the FLOAT switch pin internally.
      pinMode(FLOAT_PIN, INPUT_PULLUP);
      pinMode(SOLENOID_PIN, OUTPUT);
    }

    void loop() {
      int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

      if (floatswitch == HIGH) {
        // If the pin reads high, water is OFF.
        Serial.println("Switch closed");
        digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
      } else {
        digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
      }
    }

title: Need to set a FAILSAFE in an if else loop

Answers: 1

body:
This is one of those cases when thinking in terms of a [finite state
machine][fsm] makes the programming quite straightforward. Here I would
use three states:

* In the `OFF` state, the switch is `LOW` and the solenoid is off
* in the `ON` state, the switch is `HIGH` and the solenoid is on
* in the `DELAYING` state, the switch is `LOW`, but the program is
  keeping the switch `HIGH` for three seconds.

The possible transitions are:

* `OFF` → `ON` when the switch goes `HIGH`
* `ON` → `DELAYING` when the switch goes `LOW`
* `DELAYING` → `OFF` after three second in this state
* `DELAYING` → `ON` when the switch goes `HIGH`.

The last transition is meant to ensure that `LOW` states of the switch
that last less than three seconds do not turn the solenoid off.

And here is a tentative implementation. Keep your constants and your
`setup()`, and replace your `loop()` with this:

    const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

    void loop() {
        static enum {OFF, ON, DELAYING} state;
        static uint32_t start_delay;
        int floatswitch = digitalRead(FLOAT_PIN);

        switch (state) {
            case OFF:
                if (floatswitch == HIGH) {
                    Serial.println("Switch closed");
                    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                    state = ON;
                }
                break;
            case ON:
                if (floatswitch == LOW) {
                    start_delay = millis();
                    state = DELAYING;
                }
                break;
            case DELAYING:
                if (floatswitch == HIGH) {
                    state = ON;
                }
                else if (millis() - start_delay >= DELAY_TIME) {
                    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                    state = OFF;
                }
                break;
        }
    }

[fsm]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


body:
**Okay, so here is what I'm trying to accomplish:**

I have four LEDs, under my fish tank, that I want to fade in and out.  I want each LED to fade at a different rate, start at a different "brightness" with PWM, and get a "new" fade-rate every once in a while.  Ultimately, it'll make the bottom of the fish tank "pulse" in a "natural" way.

The code I'm using to accomplish this can be found in my [GIT repo][1].  There is also a GIF of it "working," there.

----------

**Now, here is my problem:**

Every once in a while, one of the LEDs (not a specific one) will stop fading and start blinking like a strobe light.  I'm not sure what's causing this blinking, since it seems to happen randomly.

The other three LEDs seem to continue to fade in/out while the "bad" LED is spaz-ing out, and it doesn't seem to be isolated to a specific LED.  It also doesn't seem to affect only one LED at a time, although it's usually only one LED "blinking" and any given time... but I have seen two going at the same time.

It also doesn't seem to be specific to the "high" or "low" PWM levels, either... it can happen at "bright" levels, "dim" levels, or even in the middle of the fading transition.

----------

**Here's what I've tried:**

I've tried different Arduino boards, and I've taken the LED count down to a single LED.  I've changed variable types from bytes to ints, and back and forth with that tactic.  I've been combing through this sketch all day, and I don't see anything that stands out to me as causing the problem.

So, now I'm turning to you all, hoping that someone will be able to see where I've screwed up my code.

Thank you, in advance!

----------

**EDIT:**  Since I've been asked for direct posting of my code, instead of just a link to the source code:

Here is the main .ino file:

    #include "led_controller.h"

    // Set pin numbers for each LED
    byte led1 = 3,
               led2 = 6,
               led3 = 9,
               led4 = 11;

    void setup(){
        pinMode( led1, OUTPUT );
        pinMode( led2, OUTPUT );
        pinMode( led3, OUTPUT );
        pinMode( led4, OUTPUT );
    }

    // Initialize our four classes for our four LEDs
    LED a( led1 ),
        b( led2 ),
        c( led3 ),
        d( led4 );

    void loop(){
        a.ledChange();
        b.ledChange();
        c.ledChange();
        d.ledChange();

        delay( 60 );
    }

And the header file with the class:

    // Create our custom LED class
    class LED{
        private:
            // Set higest and lowest brightnesses for LEDs
            byte highest = 250,
                 lowest = 5;
            byte pin, brightness, isNeg; // Random necessary variables
            int change; // Set the inc/decrement rate for the LED
            int checkNeg(); // See if our change rate is negative, or not
            void changeChange(); // Get a new change rate
        public:
            LED( byte led ); // Define our constructor
            void ledChange ();
    };

    // Define our constructor
    LED::LED( byte led ){
        pin = led;
        changeChange();

        // Set the initial LED brightness by random
        brightness = random( lowest, highest );

        // Randomly determine if the LED will start brightening or darkening
        if( random( 1, 2 ) == 1 )
            change *= -1;
    }

    // Get a new change rate
    void LED::changeChange(){
        change = random( 1, 4 );

        if( isNeg )
            change *= -1;
    }

    int LED::checkNeg(){
        if( change < 0 )
            return 1; // If `change` is negative, return true
        return 0;
    }

    void LED::ledChange(){
        // Flip LED change value between brightening and darkening
        if( brightness <= lowest || brightness >= highest ){
            change *= -1;

            isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

            // A 1-in-25 chance to change the fade-rate
            if( random( 25 ) == 13 )
                changeChange();
        }

        brightness += change; // Adjust the LEDs brightness

        analogWrite( pin, brightness ); // Brighten/darken the LED
    }

  [1]: https://bitbucket.org/mdill/arduino_fish_tank

title: LED fade class strobes for unknown reason

Answers: 1

body:
I added some `Serial.print()` statements to your code to point out the bug:

This is the modified `LED::changeLed()` function I used:

    void LED::ledChange() {

      /**/Serial.print(brightness);

      // Flip LED change value between brightening and darkening
      if ( brightness <= lowest || brightness >= highest ) {
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if ( random (25) == 13 )
          changeChange();

      }

      brightness += change; // Adjust the LEDs brightness

      analogWrite( pin, brightness ); // Brighten/darken the LED

      /**/Serial.print("\t+ ");
      /**/Serial.print(change);
      /**/Serial.print("\t= ");
      /**/Serial.print(brightness);
      /**/Serial.print("\t");
      /**/for (int i = 0; i < (brightness / 5); i++) Serial.print("*");
      /**/Serial.print("\n");
    }

I marked the additional lines with `/**/`.

Here is a piece of the serial monitor output, where the bug occurred.  The columns are organised as follows: brightness before the function changed it + `change` = brightness at the end of this function. The `*` lines graphically represent the LED brightness (i.e. the last number); this allowed me to run your sketch without a physical LED, at much higher speed (I deleted the `delay(60)` in `loop()`).

    183        +    3         =    186  *************************************
    186        +    3         =    189  *************************************
    189        +    3         =    192  **************************************
    192        +    3         =    195  ***************************************
    195        +    3         =    198  ***************************************
    198        +    3         =    201  ****************************************
    201        +    3         =    204  ****************************************
    204        +    3         =    207  *****************************************
    207        +    3         =    210  ******************************************
    210        +    3         =    213  ******************************************
    213        +    3         =    216  *******************************************
    216        +    3         =    219  *******************************************
    219        +    3         =    222  ********************************************
    222        +    3         =    225  *********************************************
    225        +    3         =    228  *********************************************
    228        +    3         =    231  **********************************************
    231        +    3         =    234  **********************************************
    234        +    3         =    237  ***********************************************
    237        +    3         =    240  ************************************************
    240        +    3         =    243  ************************************************
    243        +    3         =    246  *************************************************
    246        +    3         =    249  *************************************************
    249        +    3         =    252  ************************************************** #####
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    1         =    252  **************************************************
    252        +    -1          =    251  **************************************************
    251        +    3         =    254  **************************************************
    254        +    -3          =    251  **************************************************
    251        +    3         =    254  **************************************************
    254        +    -3          =    251  **************************************************
    251        +    3         =    254  **************************************************
    254        +    -3          =    251  **************************************************
    251        +    3         =    254  **************************************************
    254        +    -1          =    253  **************************************************
    253        +    1         =    254  **************************************************
    254        +    -1          =    253  **************************************************
    253        +    1         =    254  **************************************************
    254        +    -1          =    253  **************************************************
    253        +    1         =    254  **************************************************
    254        +    -1          =    253  **************************************************
    253        +    1         =    254  **************************************************
    254        +    -1          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -2          =    253  **************************************************
    253        +    2         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    1         =    255  ***************************************************
    255        +    -1          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************
    254        +    2         =    0
    0        +    -2          =    254  **************************************************

The bug begins at the line I marked with `####`. I'll try to narrate the events from the point of view of your function, starting from line #### (1):

1. Is brightness 249 in range? yes -> don't invert sign | add 3 | return
2. Is brightness 252 in range? no -> invert | change fade rate? yes, new fade rate = ±1 | add -1 (we just inverted the sign) | return
3. Is brightness 251 in range? no -> **invert (here's the bug!)** | change fade rate? no | add +1 (ve should subtract, but we just inverted the sign...) | return
4. It continues like that until a fade rate change occurs, oscillating between 251 and 252. That looks out like a constant brightness.
5. The fade rate increases and the oscillation values change, maybe approaching 255 (if the smaller value goes below 250 the led will continue to behave properly, but that's not our case).
6. Another fader rathe change causes the program to make brightness greater than 255 (in our case 254 + 2). And if you add 2 to a one-byte unsigned variable holding a value of 254 you won't get 256 (the variable can't hold that value) but 0. That's something called "integer wraparound", as Majenko pointed out in his comment to your question.

---

So, that was a long description of a very simple problem.
To solve it you cold for instance prevent the brightness value to be greater than 250 and smaller than 5 adding two lines to your ledChange function:

    void LED::ledChange(){
        // Flip LED change value between brightening and darkening
        if( brightness <= lowest || brightness >= highest ){
            change *= -1;

            isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

            // A 1-in-25 chance to change the fade-rate
            if( random( 25 ) == 13 )
                changeChange();
        }

        /**/ if(brightness > highest) brightness = highest;
        /**/ else if (brightness < lowest) brightness = lowest;

        brightness += change; // Adjust the LEDs brightness

        analogWrite( pin, brightness ); // Brighten/darken the LED
    }


body:
I want to send/receive strings to/from an ENC28J60 via a C# application. I used my own "protocol" to do this. For example I send "<GETTEMPVALUES>" to Arduino and it replies with a string containing temperature values. This method works fine in Serial communication mode, but freezes in Network mode. What am I missing here? Is there a better method to do this? I'm new to socket programming. I'm using UIPEthernet.h by ntruchsess.

My server-side (Arduino) code:
<!-- language-all: lang-cpp -->

    void checkAndReceiveFromTCPClients(){
      size_t size;
      if (EClient = EServer.available()){
        char* strIn;
        if(size = EClient.available() > 0){
          strIn = (char*)malloc(size + 1);
          memset(strIn, 0, size + 1);
          EClient.read(strIn, size);
        }
        strIn[size] = 0;
        String strInput = String(strIn);
        strInput.trim();
        //This replies to client (sends string) with a string (EClient.write(answer)):
        InterpretInputString(strInput);
        //EClient.stop();
        EClient.flush();
      }
    }

C# code:

    string SendAndReceiveOverNet(string Command) {
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
        NetworkStream stream = TClient.GetStream();
        stream.Write(data, 0, data.Length);
        data = new Byte[256];
        String responseData = String.Empty;
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        return responseData;
    }

title: Problem communicating with ENC28J60

Answers: 1

body:
Something like this is needed here. If you use stream.Read without TClient.Available, the program will freeze or crash.

C# code:
```
string SendAndReceiveOverNet(string Command) {
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
    NetworkStream stream = TClient.GetStream();
    stream.Write(data, 0, data.Length);
    String responseData = String.Empty;
    Int32 size = TClient.Available;
    if (size > 0)
    {
        data = new Byte[size];
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    }
    return responseData;
}
```


body:
For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).

I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).

Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

[![signalexample][1]][1]

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.

I looked at monostable circuits but they only detect (generate a pulse) on rising.

Does anyone have a solution (which only costs a few uAmps) for this?

Thanks.

*Addendum:*

*Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...*

*Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep >10mA (too much for battery).*

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

title: Low-power detect rise and fall of input signal

Answers: 1

body:
You can generate a pulse on any edge of a signal using some logic gates. For instance combining a rising edge detector with a falling edge detector and adding a time delay would probably achieve what you want:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Wabfq.png)

<!-- End schematic -->

[Simulate it here.](http://tinyurl.com/y7ln7tks)

The length of time the pulse is on for is (roughly) defined by the time constant of R1 and C1.  That's T=RC, so in this instance 100 x 0.0000001 =  10uS.

for a time of (say) 30 seconds, you will want to massively increase those values. For example, 470uF and 80K would give you around 32 seconds.

Power consumption? Well, that's all dependent on the logic gates and how you build the circuit.  74HC chips are pretty efficient now (far better than the old 74LS ones), but you will want to reduce it down to as few chips and gates as possible. That means converting the circuit to just one gate type (for example NAND) and reducing redundancy in the circuit to minimise power consumption.


body:
I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.

After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.

Code for my basic program, which should display "0123" on my display.

    int A = 2;
    int B = 3;
    int C = 4;
    int D = 5;
    int E = 6;
    int f = 7;
    int G = 8;
    int P = 9;

    int D4 = 10;
    int D3 = 11;
    int D2 = 12;
    int D1 = 13;

    void setup() {
      pinMode(A, OUTPUT);
      pinMode(B, OUTPUT);
      pinMode(C, OUTPUT);
      pinMode(D, OUTPUT);
      pinMode(E, OUTPUT);
      pinMode(f, OUTPUT);
      pinMode(G, OUTPUT);
      pinMode(P, OUTPUT);
      pinMode(D1, OUTPUT);
      pinMode(D2, OUTPUT);
      pinMode(D3, OUTPUT);
      pinMode(D4, OUTPUT);

      digitalWrite(D1, LOW);
      digitalWrite(D2, HIGH);
      digitalWrite(D3, HIGH);
      digitalWrite(D4, HIGH);
      delay(5);

      //0
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, HIGH);
      digitalWrite(E, HIGH);
      digitalWrite(f, HIGH);
      digitalWrite(G, LOW);

      digitalWrite(D1, HIGH);
      digitalWrite(D2, LOW);
      digitalWrite(D3, HIGH);
      digitalWrite(D4, HIGH);
      delay(5);

      //1
      digitalWrite(A, LOW);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, LOW);
      digitalWrite(E, LOW);
      digitalWrite(f, LOW);
      digitalWrite(G, LOW);

      digitalWrite(D1, HIGH);
      digitalWrite(D2, HIGH);
      digitalWrite(D3, LOW);
      digitalWrite(D4, HIGH);
      delay(5);

      //2
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, LOW);
      digitalWrite(D, HIGH);
      digitalWrite(E, HIGH);
      digitalWrite(f, LOW);
      digitalWrite(G, HIGH);

      digitalWrite(D1, HIGH);
      digitalWrite(D2, HIGH);
      digitalWrite(D3, HIGH);
      digitalWrite(D4, LOW);
      delay(5);

      //3
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, HIGH);
      digitalWrite(E, LOW);
      digitalWrite(f, LOW);
      digitalWrite(G, HIGH);

    }

    void loop() {
    }

But all the display shows is a 3 on the rightmost digit. I followed the video in [this][1] guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?

  [1]: https://create.arduino.cc/projecthub/SAnwandter1/programming-4-digit-7-segment-led-display-2d33f8

title: 4-digit 7-segment display resets when common pin set to HIGH

Answers: 2

body:
This should work (sort of). It will be flickery, but it should give you a starting place to work from.

    int A = 2;
    int B = 3;
    int C = 4;
    int D = 5;
    int E = 6;
    int f = 7;
    int G = 8;
    int P = 9;

    int D4 = 10;
    int D3 = 11;
    int D2 = 12;
    int D1 = 13;

    void setup() {

      // put your setup code here, to run once:
      pinMode(A, OUTPUT);
      pinMode(B, OUTPUT);
      pinMode(C, OUTPUT);
      pinMode(D, OUTPUT);
      pinMode(E, OUTPUT);
      pinMode(f, OUTPUT);
      pinMode(G, OUTPUT);
      pinMode(P, OUTPUT);
      pinMode(D1, OUTPUT);
      pinMode(D2, OUTPUT);
      pinMode(D3, OUTPUT);
      pinMode(D4, OUTPUT);

    }

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

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

      //0
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, HIGH);
      digitalWrite(E, HIGH);
      digitalWrite(f, HIGH);
      digitalWrite(G, LOW);

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

      //1
      digitalWrite(A, LOW);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, LOW);
      digitalWrite(E, LOW);
      digitalWrite(f, LOW);
      digitalWrite(G, LOW);

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

      //2
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, LOW);
      digitalWrite(D, HIGH);
      digitalWrite(E, HIGH);
      digitalWrite(f, LOW);
      digitalWrite(G, HIGH);

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

      //3
      digitalWrite(A, HIGH);
      digitalWrite(B, HIGH);
      digitalWrite(C, HIGH);
      digitalWrite(D, HIGH);
      digitalWrite(E, LOW);
      digitalWrite(f, LOW);
      digitalWrite(G, HIGH);
    }

body:
These 4-digit LED displays use *multiplexing* which means that (to keep the pin count down) you only display each digit for a brief time. Because of the eye's persistence of vision, if you repeatedly display the 4 digits they all appear to be lit up.

I have [a video](https://vimeo.com/80312101) that illustrates this effect with a LED sign. There are a lot more than 4 digits, but the video gradually shows what happens if the delay between each digit is reduced. Watch it through to the end or you won't get the effect. It is about 45 seconds long.

In your case, as jsotola suggested in their answer, if you move the code which displays the digits out of `setup` and into `loop` then the code is done repeatedly, which means that the digits are now displayed repeatedly, and you should see all of them.

Since, in your original code, you had the display code in `setup` then it was done once, and the final digit was the only one you saw.


body:
I thought the code below would toggle an LED every 500 milliseconds. But it does not work. I'm not able to catch the mistake, which must be very silly.

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

    void loop() {
      unsigned long cnt=millis();
      if(!(cnt % 500)) {
        PORTD^= (1<<PD3);
      }
    }

Anyhow the code below works. But why not the previous code?

    void loop() {
      static unsigned long prev=0;
      // Note: First time case is not handled. As soon as we want to toggle,
      // we must store millis() in prev. In this case this happens after reset and may not be an issue.
      unsigned long current = millis();
      if((unsigned long)(current - prev) >= 500) {
        PORTD^= (1<<PD3);
        prev = current;
      }
    }

title: Using millis() to toggle an LED every 500 milliseconds

Answers: 4

body:
Your timing doesn't work, because it has a low probability to read a millisecond that is an exact multiple of 500.

Do it this way:

      static unsigned long next = millis();
      if (millis() - next > 500) {
        next += 500;

body:
    void loop() {
      unsigned long cnt=millis();
      if(!(cnt % 500)) {
        PORTD^= (1<<PD3);
      }
    }

At every iteration, `cnt` is set with the number of milliseconds elapsed **since you turned on the Arduino...** So this is not gonna work. At all. What you need is two variables. One that holds the last `millis()` count when you blinked the LED, and for the current `millis()` count:

    unsigned long lastCount;
    void setup() {
      pinMode(3, OUTPUT);
      lastCount=millis();
    }

    void loop() {
      unsigned long cnt=millis();
      if((cnt-lastCount)>499) {
        PORTD^= (1<<PD3);
        lastCount=cnt;
      }
    }

body:
> `if (!(millis() % 500)) ...`

There are two issues with this. The first, and most obvious, is that the
condition will be true for a full millisecond. During that millisecond
you will be toggling the LED on and off very fast. Whether you end up
doing an odd or even number of toggles is anyone's guess.

The second and less obvious problem is that `millis()` skips some
values. Roughly one integer every 42 is skipped over. This is because
the `millis()` counter is incremented once every 1024 µs, getting
24 µs late on each increment. Once all those delays add up to a
full millisecond, `millis()` catches up by incrementing the counter by
two milliseconds instead of one. This is why you should never condition
something on `millis()` having one specific value.

The almost correct solution to this problem is shown in Juraj's answer:

> `if (millis() > next) ...`

This is not quite correct because it fails each time `millis()` rolls
over back to zero. The correct solution is

<!-- language: lang-c++ -->

    static unsigned long last;
    if (millis() - last >= 500) {
        last += 500;
        ...
    }

Because the subtraction follows the rules of modular arithmetic, this is
guaranteed to work across the rollover events.

body:
I always use this

    if((millis()/500)%2==0))
    {
        PORTD |= (1<<PD3);
    }
    else
    {
        PORTD &= ~(1<<PD3);
    }

It first divides millis by 500ms. So you get the number of 500ms chucks (since the Arduino started). Then you check to see if this number is even. If so, turn the led pin on. Else turn the led pin off.