message:
LED fade class strobes for unknown reason

**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

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
    }


sender: user

message:
Problem communicating with ENC28J60

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;
    }

sender: assistant

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;
}
```


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

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

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.


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

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

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.


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

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;
      }
    }

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.


message:
for loop running infinitely

void writereg() {
      digitalWrite(latchPin, LOW);
      for (int i = 7; i >= 0; i--) {
        digitalWrite(clockPin, LOW);
        Serial.print("wswitch&&&&&&");
        Serial.print(i);
        Serial.print("----------------------");
        digitalWrite(dataPin, switches[i].stat);
        Serial.println(switches[i].stat);
        digitalWrite(clockPin, HIGH);
      }
      digitalWrite(latchPin, HIGH);
      touched = false;
    }

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.

This is my switch class:

    struct Swtch
    {
      int num;
      bool stat;
      bool touched;
    };

    Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

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

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

body:
Like [jfpoilpret](https://arduino.stackexchange.com/questions/48311/for-loop-running-infinitely#comment96255_48311) said, it looks like `i` is being treated as an `unsigned char` or `uint8_t` causing it to never go below zero. Instead it wraps around to 255, the max value of an 8-bit unsigned integer, as you can see in line 9 of your output. The condition to remain in the loop is `i >= 0` which means the loop will never exit. A solution is to add a case for if `i` is above the starting value:

```for (int i = 7; i >= 0 && i <= 7; i--) {
```

I would recommend finding out why `int` is being treated as `uint8_t` for any future projects


body:
After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of `String` variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

1. Replace all `"..."` string literals with flash-stored strings with `F("...")`. That will reduce the initial SRAM size used.
2. Replace all `String` variables with pure C-string (`char*` and char arrays) and use standard C string functions such as `strcpy`, `strcat`, `strlen`, `strcmp`, `strchr`... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
3. Use `const` whenever possible (instead of variables that waste memory)
4. Use the smallest type needed for each variable, e.g. avoid `int` (2 bytes) when you need to store a boolean value, prefer `bool` type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.


message:
DAC using Arduino Leonardo

I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.

First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.

Am I going towards the correct direction? If not, please any suggestion would be helpful.

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

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

body:
Yes you are going in the right direction.

**Comparators**
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to this:

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

<!-- End schematic -->

In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The `value` column corresponds to the value needed for the [`analogWrite()`][1] function.

[![truth table][2]][2]

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a [unity gain][3] configuration at the output of the RC filter.

----------

**Examples To Read**
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:

[Dimmer][4]: Send serial values to change the brightness of an LED.
[Fading][5]: Use an analog output (PWM pin) to fade an LED.
[Analog In Out Serial][6]: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
[Read ASCII String][7]: Parse a comma-separated string of integers to fade an LED.

What all of these examples have in common is the [`analogWrite()`][1] function:

    // writes the analog value (range from 0 to 255):
    analogWrite(pin, value);

*Dimmer* is a simple example where a serial value is read and then output on one of the PWM pins.
*Fading* is probably the most basic example of using the [analogWrite()][1] function (PWM output).
I included *Analog In Out Serial* as it uses the [map()][8] command.
I included *Read ASCII String* as it shows how to parse multiple values on the serial string.

----------

**PWM Pins**
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the [`analogWrite()`][1] function.

----------

**Control**
I recommend the following tutorials for your control. You could either use the [if][9]-[else][10] command or the [switch-case][11] command.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
  [2]: https://i.stack.imgur.com/DNf0h.png
  [3]: https://en.wikipedia.org/wiki/Buffer_amplifier#Op-amp_implementation
  [4]: https://www.arduino.cc/en/Tutorial/Dimmer
  [5]: https://www.arduino.cc/en/Tutorial/Fading
  [6]: https://www.arduino.cc/en/Tutorial/AnalogInOutSerial
  [7]: https://www.arduino.cc/en/Tutorial/ReadASCIIString
  [8]: https://www.arduino.cc/reference/en/language/functions/math/map/
  [9]: https://www.arduino.cc/reference/en/language/structure/control-structure/if/
  [10]: https://www.arduino.cc/reference/en/language/structure/control-structure/else/
  [11]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/


message:
Conditional randomization gets stuck

First-time poster here...

I have the following code to randomize note values and store them in an array `loop1[i]`, where `i` is a specific step in the loop:

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

    nextNote = random(-2, 3);
    note = note + nextNote;

    loop1[i] = note;

    while (loop1[i] == loop1[i - 1] ||
           loop1[i] == loop1[i - 2] ||
           note > 6 ||
           note < 0) {
      nextNote = random(-2, 3);
      note = note + nextNote;
      loop1[i] = note;
    }

(I hope this is clear enough).

Now, it usually works to a certain point until the sketch loops forever in order to randomize an allowed number. Therefore, my questions are:

Running an ATmega 2560, is this actually a task too demanding for the processor or should I suspect that it's not working properly?

How can I optimize the code, but retain the conditions above in order to avoid the loop getting stuck?

body:
Some reasons why it will not work:

- My feeling is that `i` gets too big, i.e. it is higher than the length of the array you are using. That can cause crashes, or at least unpredicted results. You can easily check this by printing the value of `i` (and check against the maximum value).

- I don't see problems with the while loop (although I would use brackets around `note > 6` and around `note < 0`, but I don't think this is really needed.

- If the value gets below 0 or higher than 6, still random values are added, assume the value is +10... then it might take a lot of time (if ever) for that value to reach max 6 again. The same is true for values < 0. Maybe you should never allow values of less than 0 and higher than 6 anyway, or making the random values in such a way they tend to go towards the average (3).

Tip to debug:

However, the easiest way to debug this is to print all relevant variables (e.g. `nextNote`, `note`, `i`, the last two notes `loop[i-2]`, `loop[i-1]` and the current note `loop[i]`... Also print a line inside the while loop so you know when you skip it or not. This probably will give you enough information to see what is wrong.


body:
I think you have a problem with your math here, not with your code. What
you are simulating is very similar to a [1-dimensional random
walk](http://mathworld.wolfram.com/RandomWalk1-Dimensional.html).
According to the linked MathWorld page, for such a process “the most
probable number of sign changes in a walk is 0”.

If, at some point in your program, the loop starts with `note == 6`, and
then it starts randomly going up, there is a sizable probability for it
to never go back to values below 7.

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

**Edit**: One possible solution could be to avoid the random-walk notion
and instead repeat the random choice always from the same starting
point.

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

    int oldNote = note;  // starting point
    do
        note = oldNote + random(-2, 3);
    while (
        note == loop1[i - 1] ||
        note == loop1[i - 2] ||
        note > 6 ||
        note < 0);
    loop1[i] = note;


body:
The line `loop1[i] = note` doesn't belong in the loop (or above it); you're not changing `i` in the loop, so you're just rewriting the same location over and over again.

As for the loop itself, what sort of use case do you have for this, and what sort of distribution do you want? Waiting until it's between 0 and 6 is horribly inefficient. You need to decide what sort of distribution you want and implement it more directly. For instance, you could have a piecewise quadratic distribution by getting a random number between zero and sqrt(3), then squaring the result, and then randomly choosing whether to subtract the result from 6.


message:
Very Basic Arduino Uno Serial.readString() operation

I am very new to Arduino Programming.
I am trying to identify the input string from serial monitor and printing the output to the console accordingly

Code is :

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

    void loop() {

       while (Serial.available() > 0 ) {

         String str = Serial.readString();

         if (str.equals("send")) {
            Serial.println("identified");
         } else {
            Serial.println("unknown");
         }

       }

    }

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output.
Can anyone guide me here to achieve the result.

Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

body:
There are any number of reasons the *.equals test is false. Consider case difference or extra characters introduced from the source of your communications.  Even non printable characters may pose a problem and cause the test to fail.

Consider using [*.substring()][1] instead.  This method will return true if the substring is found.  For example:

      String stringOne = "12345 send 1234";

      // substring(index) looks for the substring from the index position to the end:
      if (stringOne.substring(0) == "send")
      {
        Serial.println("identified");
      }
      else
      {
        Serial.println("unknown");
      }

...should always return "identified" because the characters 's', 'e', 'n' and 'd' are found in the correct sequence within the string stringOne.

  [1]: https://www.arduino.cc/en/Tutorial/StringSubstring


body:
If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".

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

    void loop(){
      while(Serial.available() > 0 ){
        String str = Serial.readString();
        if(str.substring(0) == "send\r\n"){
          Serial.println("identified");}
        else{
          Serial.println("unknown");
        }
      }
    }

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();

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

    void loop(){
      while(Serial.available() > 0 ){
        String str = Serial.readString();
        if(str.indexOf("send") > -1){
          Serial.println("identified");}
        else{
          Serial.println("unknown");
        }
      }
    }


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

    void loop() {
       char inChar[5];

       if(Serial.available() > 0 )
       {
         for (int i=0; i<5; i++)
         {
          inChar[i] = Serial.read();
          delay(10);
         }

         if (inChar[0] == 's' && inChar[1] == 'e' \
                              && inChar[2] == 'n' \
                              && inChar[3] == 'd')
             {
              Serial.println("identified");
             }

         else
         {
           Serial.println("unknown");
         }
      }
    }


message:
Arduino keypad and RF 433MHz transmitter problem

So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter.
I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:

    #include <RH_ASK.h>
    #include <SPI.h> // Not actually used but needed to compile
    RH_ASK driver; //use this driver for transmitter

    #include <Keypad.h>
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

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

    void setup()
    {
        Serial.begin(9600);   // Debugging only
        if (!driver.init())
             Serial.println("init failed");
    }

    void loop()
    {

        char key = keypad.getKey();

        if (key){
          Serial.println(key);//outputs correct key
          //transmitter part
    //      const char *msg = "Hello World!";
          const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
          driver.send((uint8_t *)msg, strlen(msg));
          driver.waitPacketSent();
          Serial.println(key);//outputs correct key
          Serial.println("packet_sent");
        }
    }

body:
The problem is you send a character of type char, thus exactly one byte.
However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.

Also, you can get rid of the special msg pointer and instead of

      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg

use

      driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus

      driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.

Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.


message:
Arduino reads hc-05 device connecting status

Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

body:
In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.

`AT+BIND? ` gives you which device you currently paired.


body:
Different Bluetooth adapters (using the HC-05 module) provide different signals, besides its Rx and Tx. Most bring out a "key" input that puts the module into command mode where serial communication is between the external pins and the module itself - 'AT' commands & queries to the module's firmware. When the module is not in command mode, the firmware just passes serial data through the Bluetooth radio, ignoring the content. Some provide an LED- or State signal that you can read (or observe on an LED) to know whether the devices is paired (communicating) or unpaired (in command mode).

On some, this is a simple logic signal; on others it is a square wave of 1/2 to 1 Hz which means your code has to track the signal to know whether it is static (typically High when paired) or toggling (for unpaired/waiting to pair).

You need to read your module's datasheet to find out the behavior of this signal on your particular module. If you connect an LED to this signal, or your module has one on the board, you can often make a good enough guess by observing it with a stopwatch. Either way, you then need an Arduino function that samples the LED periodically, remembering what state it saw and for how long, to decide whether the LED is blinking or is steady.


message:
How to make a button work a second time in my code?

I am making a security system, and the alarm starts when the button gets pressed. If i turn the alarm off by the serial communication, and want to turn it on again using the button, it will only let the alarm go on for about 0.5 seconds. Does someone see the mistake i'm making, and can help me? Thanks in advance!

    const int ledrood = 11;
    const int ledgroen = 12;
    const int buttonPin = 2;
    int buttonState = LOW;

    int statePin = LOW;
    const int trigPin = 9;
    const int echoPin = 10;
    long duration;
    int distance;
    bool alarm = false;
    int speakerPin = 8;
    String Message = "";
    String NMessage = "";
    String Command = "";
    int index = 0;
    bool Bericht = true;

    void PlaySong()
    {
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
      tone(speakerPin, 4699, 500);
      delay(1000);
    }
    void alarmaan()
    {
     alarm = true;

      digitalWrite(ledrood, HIGH);
      digitalWrite(ledgroen, LOW);
      digitalWrite(trigPin, LOW);

     }

    void AlarmUit() {
      Serial.println("alarm uit");
      alarm = false;
      digitalWrite(ledgroen, HIGH);
      digitalWrite(ledrood, LOW);
      digitalWrite(trigPin, LOW);

     }
    void setup() {
      pinMode(ledrood, OUTPUT);
      pinMode(ledgroen, OUTPUT);
      pinMode(buttonPin, INPUT);
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600);
     }
    String Doorsturen() //Methode om te communiceren via de serial monitor
    {
     if (Serial.available() > 0)
      {
       char readChar = (char) Serial.read();
       NMessage = NMessage + readChar;
      }
      if (NMessage.startsWith("#") && NMessage.endsWith("%"))
      {
       index = NMessage.indexOf("%");
       NMessage = NMessage.substring(1, index);
       Serial.println(NMessage);
       Command = NMessage;
       NMessage = "";
       Bericht = true;
      }
      else if (NMessage.endsWith("%"))
     {
       NMessage = "";
     }
     return Command;
    }
    void loop() {
     Message = Doorsturen();
     int buttonState = digitalRead(buttonPin);
     digitalWrite(trigPin, HIGH);
     digitalWrite(trigPin, LOW);
     duration = pulseIn(echoPin, HIGH);
     distance = duration * 0.034 / 2;
     Serial.print("Distance: ");
     Serial.println(distance);

     if (alarm == false) {
       digitalWrite(ledgroen, HIGH);
     }

     if (Message == "alarm_off")
     {
       AlarmUit();
       Message = "";
     }
      if (Message == "1234")
      {
       AlarmUit();
       Message = "";
      }
      if (Message == "aan") {
       alarmaan();
       Message = "";
       }

      if (alarm == false) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        alarmaan();
        Serial.println("fout");
       }
      }

      if (distance < 10 && alarm == true) {
       PlaySong();
      }

     if (alarm == true) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        alarmaan();
        Serial.println("Test");
       }

     }
    }

body:
The problem is that `Message = "";` doesn't actually do anything, because the next time `doorsturen` is called, it will just load the previous command from the `command` variable. I'd suggest having the `doorsturen` function only return the command once, and not on consecutive calls.

    String Doorsturen() //Methode om te communiceren via de serial monitor
    {
      Command = "";
      if (Serial.available() > 0)
      {
        char readChar = (char) Serial.read();
        NMessage = NMessage + readChar;

        if (NMessage.startsWith("#") && NMessage.endsWith("%"))
        {
          index = NMessage.indexOf("%");
          NMessage = NMessage.substring(1, index);
          Serial.println(NMessage);
          Command = NMessage;
          NMessage = "";
          Bericht = true;
        }
        else if (NMessage.endsWith("%"))
        {
          NMessage = "";
        }
      }
      return Command;
    }

<strike>
see comment in the code

    if (alarm == false) {
      if (buttonState == HIGH) {
        //here you set alarm to true
      }
    }

    ...

    if (alarm == true) { //now this if statement is true
      if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

      }

to fix do this

    if (alarm == false) {
       if (buttonState == HIGH) {
        delay(50);
        while (digitalRead(buttonPin) == HIGH) {}
        delay(50);// this is to negate switch bounce, on release, from interfering
        buttonState = false;// add this line
        alarmaan();
        Serial.println("fout");
       }
      }

</strike>


message:
Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button

I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.

        #define led1 10 //10th,
        #define led2 11 //11th
        #define led3 12 //12th
        #define led4 13 //13th
        #define ButtonA 9

        int ButtonState;
        int ButtonState2;
        int state;
        int StateNow;
        int PreviousState = HIGH;

        void setup(){
          pinMode(led1,OUTPUT);
          pinMode(led2,OUTPUT);
          pinMode(led3,OUTPUT);
          pinMode(led4,OUTPUT);
          pinMode(ButtonA,INPUT_PULLUP);
          Serial.begin(9600);
          Serial.println("Enter ch a, b, c, or d:");
        }

        void loop() {
        if (Serial.available())
        {
          ButtonState = digitalRead(ButtonA);
          delay(10);
          ButtonState2 = digitalRead(ButtonA);  //debounce
          if (ButtonState != ButtonState2)
          {
            StateNow = ButtonState2;
          }
          else
          {
            StateNow = ButtonState;
          }
          if(StateNow == LOW && PreviousState == HIGH)
      {
        digitalWrite(led1,LOW);
        digitalWrite(led2,LOW);
        digitalWrite(led3,LOW);
        digitalWrite(led4,LOW);
        Serial.println("Turned off all LEDs");
        PreviousState = LOW;
      }
      else if(StateNow == HIGH && PreviousState == LOW)
      {
        PreviousState = HIGH;
      }
      state = Serial.read();
      if (state == 'a' || state == 'A')
      {
        digitalWrite(led1,HIGH);
        Serial.println("Turned on led 1");
      }
      else if (state == 'b' || state == 'B')
      {
        digitalWrite(led2,HIGH);
        Serial.println("Turned on led 2");
      }
      else if (state == 'c' || state == 'C')
      {
        digitalWrite(led3,HIGH);
        Serial.println("Turned on led 3");
      }
      else if (state == 'd' || state == 'D')
      {
        digitalWrite(led4,HIGH);
        Serial.println("Turned on led 4");
      }
    }

    }

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software

body:
To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

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

In your code you detect the change only if serial is available, but you should do it in the loop.

The simple way to detect the change is doing this in every loop:

    if (StateNow != PreviousState) {
      if (StateNow == LOW && PreviousState == HIGH) //button pushed
      {
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        digitalWrite(led3, LOW);
        digitalWrite(led4, LOW);
        Serial.println("Turned off all LEDs");
      }
      PreviousState = StateNow;
    }

I simplify your code and add some comments:

    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int state;
    int StateNow;
    int PreviousState;

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(ButtonA, INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
      PreviousState = digitalRead(ButtonA);
    }

    void loop() {
      //detect changes in button signal to turn off leds
      StateNow = digitalRead(ButtonA);
      if (StateNow != PreviousState) {
        if (StateNow == LOW && PreviousState == HIGH) //button pushed
        {
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
          digitalWrite(led3, LOW);
          digitalWrite(led4, LOW);
          Serial.println("Turned off all LEDs");
        }
        PreviousState = StateNow;
      }

      //check serial biffer to turn on leds
      if (Serial.available())
      {
        state = Serial.read();
        if (state == 'a' || state == 'A')
        {
          digitalWrite(led1, HIGH);
          Serial.println("Turned on led 1");
        }
        else if (state == 'b' || state == 'B')
        {
          digitalWrite(led2, HIGH);
          Serial.println("Turned on led 2");
        }
        else if (state == 'c' || state == 'C')
        {
          digitalWrite(led3, HIGH);
          Serial.println("Turned on led 3");
        }
        else if (state == 'd' || state == 'D')
        {
          digitalWrite(led4, HIGH);
          Serial.println("Turned on led 4");
        }
      }
    }

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


message:
ATMega328p (Arduino) Timer1 set-up

I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?

    volatile int sample_incremental = 0;

    void setup() {
          Serial.begin(115200);
          pinMode(voltagePin, INPUT);
          pinMode(currentPin, INPUT);
          set_sample_interrupt();
          sei();
        }

    void set_sample_interrupt() {
      //Count to 400us
      OCR1A = 99;
      //Mode 4, CTC
      TCCR1B |= (1 << WGM12);
      //Enable interrupt
      TIMSK1 |= (1 << OCIE1A);
      //Prescaler 64
      TCCR1B |= (1 << CS11) | (1 << CS10);
    }

    ISR (TIMER1_COMPA_vect) {
      // action to be done every 400 usec
      current_sample[sample_incremental] = analogRead(currentPin) - 504;
      voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
      if (sample_incremental < (SAMPLES * PERIODREADS))
        sample_incremental++;
      else {
        //Disable interrupt
        TIMSK1 &= ~(1 << OCIE1A);
        sample_incremental = 0;
        finishedReading = true;
      }
    }

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.

body:
The Arduino core library configures the Timer 1 for phase-correct PWM at
about 490 Hz. Then you are setting some configuration bits in the
timer's control registers without clearing the bits that had previously
been set by the Arduino core. If you want to use the timer for your own
purposes, and configure it by yourself, you should completely overwrite
the core's configuration with your own. For that, use the `=` operator
rather than `|=`, as in:

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

    OCR1A  = 99;                         //Count to 400us
    TIMSK1 = (1 << OCIE1A);              //Enable interrupt
    TCCR1A = 0;
    TCCR1B = (1 << WGM12)                //Mode 4, CTC
           | (1 << CS11) | (1 << CS10);  //Prescaler 64


message:
Why does void loop() stop after some samples?

I am not getting any compile time error. After some samples of data `void loop()` stops executing. Please let know what the problem is. Below is my code.

Thanks and regards
Thippeswamy

    #include<SPI.h>
    float amplitude=1.5;
    int freq1=20; int freq2=12;
    int k=20;float A= amplitude*k;
    int Fs=10550; float sine[5000]; float Fs1=3000;
    int i=0;int reg1=1; int reg2=0;
    int sample1=Fs/freq1; float sample2=Fs1/freq2;

    void setup() {
      int SS=10;
      pinMode(SS, OUTPUT);
      SPI.begin();
    }

    void data(int reg, int data) {
      digitalWrite(SS,LOW);
      SPI.transfer(reg);
      SPI.transfer(data);
      digitalWrite(SS,HIGH);
    }

    void loop() {
      for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
        float s=A*sin((2*3.14*freq1*j)/Fs);
        sine[j]=s+190;
        data(reg1,sine[j]);
        if(i<=sample2) {
          float s=A*sin((2*3.14*freq2*i)/Fs1);
          sine[i]=s+190;
          data(reg2,sine[i]);
          i++;
        } else if(i>sample2) {
          float s=A*sin((2*3.14*freq2*i)/Fs1);
          sine[i]=s+190;
          data(reg2,sine[i]);
          i++;
        }
      }
    }

body:
>     float sine[5000]
>     ...
>     sine[j]=s+190;

A float takes 4 bytes. You are allocating 5000 of them which is 20000 bytes. The Uno has 2048 bytes of RAM. Thus you are running out of RAM and overwriting something you shouldn't be.

---

As pointed out on [the Arduino forum](http://forum.arduino.cc/index.php?topic=520194), your `for` loop which tests for:

    i < sample2 || i >= sample2

will always be true. Of course `i` will be *either* **less than** or **greater than or equal to** `sample2`.


message:
What's the difference between DDRB and pinMode?

It's my understanding that the following lines are equivalent. They seem to be interchangeable in my sketch:

    DDRB = 1<<DDB0;

and

    pinMode(0, OUTPUT);

Is the first form (`DDRB...`) setting a micro-controller address directly? Is that assembler?

And is the second form (`pinMode`) using an included library? Maybe the `avr/io.h` library?

*On a Digispark ATTiny85*.

body:
> DDRB

is a register. Exactly: Port B Data Direction Register. See [datasheet][1] for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

> DDB0

 value was used.
Using this way of setting direction of a pin is much faster than  `pinMode(0, OUTPUT); `
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf


body:
Yes, on a simple microcontroller like the ATTiny the two lines of code are equivalent.  The function `pinMode(...)` just looks up what pins relate to what ports in a table and set the right registers.

Using `DDRB` instead of `pinMode(...)` is fine as long as you are never going to run your code on anything else (or give it to anyone else to run), since you have now hard coded into your sketch what pins are to be used. It is more efficient to use `DDRB` though. You sacrifice portability for efficiency.

However, for more complex microcontrollers that have many many functions on a single pin, just manipulating `DDRB` (or the equivalent on the target microcontroller) may not be enough. You may need to switch the pin into GPIO mode, disable analog inputs on the pin, or other operations as well. All that will be wrapped up in the `pinMode(...)` function for you by the Arduino API so you don't need to worry about it.

So, in short, if you don't care about portability, and you do care about efficiency and code size (which may well be the case on an ATTiny) then yes use `DDRB` and its friends.


message:
Serial communication between multiple devices (or Arduinos)

What I know from my search on the internet, for both **SPI** and **I2C** protocols, communication between multiple devices needs a master, which initiates the communication, and slaves, which respond to the master's request. Basically slaves can't initiate a transfer.

Is there any way to make different devices communicate on their will? I'm not sure about **UART**, but I think the story is the same here. But I know that it is possible to use a USB hub to connect multiple USB devices to one port on the computer. How can that be done? Can I use the same principle with Arduino?

To clarify what I want to do, consider that I have different modules (might be Arduinos) with different characteristics. I want to connect them on a bus line to a master Arduino. The module connections should be indifferent so that the user doesn't have to worry about which port should be used to connect the module. For this reason, using an Arduino Mega with more serial interfaces doesn't solve the problem, because we don't know which device is connected to which port.

body:
I2C protocol has Multi-master Arbitration Support, i.e. any I2C device can be master and slave. I2C is a multimaster bus
Master start communication, but master device can change. If one device wants to communicate, acts as a master. The problem is that before sending data you must be sure the bus is not busy with other master.

More information: https://www.i2c-bus.org/multimaster/

With UART is not possible to build a bus, only point to point communication.


body:
Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.

However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.

That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).

The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.

It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.

Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.

As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.


body:
Another option thats possible if you can control the firmware on each node, as in your case with multiple arduino's, is to create a ring bus using UART ports with multiple peers on it where each node would be responsible for forwarding packets to the next node.

The UART rx tz lines for nodes would have to be connected in a ring like this:

 - NodeA Tx => NodeB Rx
 - NodeB Tx => NodeC Rx
 - NodeC Tx => NodeA Rx

This would require design of a somewhat complicated protocol and controlling firmware on each node, and you would need to think through issues like:
1. how many devices can be supported on the ring
2. message size
3. how much memory is available to buffer messages on each node
3. how many message is each node allowed to send
etc.


message:
How to connect dual brushless motors to arduino

I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back.

This the motor I want to use :
http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

![motor specs](https://i.stack.imgur.com/HET7j.png)
![enter image description here](https://i.stack.imgur.com/9DhdD.png).                       ![enter image description here](https://i.stack.imgur.com/evklR.png).                         ![enter image description here](https://i.stack.imgur.com/x4AfR.png)

body:
It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.

You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.


message:
Converting (char*)variable to int

I have the following code:

          uint8_t buf[1];
          uint8_t buflen = 1;
          if (driver.recv(buf, &buflen)) // Non-blocking
             {
                int i;
                // Message with a good checksum received, dump it.
                Serial.print("Message: ");
                Serial.println((char*)buf);//this prints out okay
                highPins[(char*)buf] = 1;
             }
   The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

body:
The function you want is `atoi`.

    int pinno = atoi((char *)buf);

I would suggest checking that the result is in the right range before using it.


body:
I would suggest improving your code slightly as follows:

      uint8_t buf;
      uint8_t buflen = 1;
      if (driver.recv(&buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println(buf);//this prints out okay
            highPins[buf] = 1;
         }

The important point is that you do not need to declare `buf` as an array of just one element, but just declare the element itself (as `uint8_t`) and pass its address (`&buf`) to `driver.recv(...)`.

As @Majenko suggested, you should alos check `buf` before using it as an index to `highPins` array, in order to avoid using an index bigger than teh array size.


message:
I2C libraries for ATTiny85?

I want to transmit I2C data, using a Digispark ATTiny85 board:

 - http://digistump.com/products/1
 - http://digistump.com/wiki/digispark/tutorials/connecting

I've found the following I2C libraries. Which one is more lightweight, stable, bug-free, efficient, powerful, and easy to use?

 - Adafruit's [TinyWireM][1] has not been updated in 2 years.

 - felias-fogg's [SoftI2CMaster][2] has been updated within days of this post.

 - lucullusTheOnly's [TinyWire][3] represents some years of improvements, "based on the TinyWireM and TinyWireS libraries". This version is recommended by BroHogan, co-creator of TinyWireM:
https://playground.arduino.cc/Code/USIi2c

Wire seems under-featured:

> "the default Arduino Wire() library does not support changes in bus
> speed or feature proper clock stretching support. This makes the
> default library only marginally functional"
> https://www.maxbotix.com/articles/095.htm

What other I2C libs are available for ATTiny? In the IDE i see Digispark SoftSerial, OneWire, and VirtualWire.

How do they all compare?

---------

Note, these other answers do **not** seem relevant to my question:

 - https://arduino.stackexchange.com/questions/34126/whats-the-difference-between-all-the-software-serial-libraries-which-one-is-ar

 - https://arduino.stackexchange.com/questions/11689/alternatives-to-wire-library-for-i2c

  [1]: https://github.com/adafruit/TinyWireM
  [2]: https://github.com/felias-fogg/SoftI2CMaster
  [3]: https://github.com/lucullusTheOnly/TinyWire

body:
>  I want to transmit I2C data...

A little vague.

Transmit to what device? How fast is your data rate (100kHz, 400kHz)? Your only transmitting and not reading anything back? What is the idling voltage of your I2C bus (to then ask if you have chosen correct pull-up resistor values for your intended bus speed)?

You mention that the Wire library doesn't support core clock speed changes without some hacking, but don't talk about the speed you intend to run the microcontroller or how fast you intend to use the I2C. I can guess 400kHz, since you brought up speed, but that's not a great way to answer a question.

I have using the Wire library on an Arduino UNO at I2C bus rate of 100kHz and it's worked fine for my needs. I got bytes in and out.

At this point, the best suggestion I'd have is that if one of the above libraries you listed does not support a feature you'd like, fork it, and add support for your feature yourself. If you're only transmitting to one slave device, then you shouldn't need to worry about bus arbitration, like the [TinyWire][1] does. Adafruit is okay for the most part, but they seem (to me) slow to fix bugs and maintain code. But don't let the code's age get to you. I2C was [created back in 1982][2], and you're still using it... :-P

Here's how I would approach choosing a library:

- Define features you need
- Look for a library which has most of those features
- Add any new features you need
- Possibly share your added features with the community with a [Pull Request][3]

  [1]: https://github.com/lucullusTheOnly/TinyWire
  [2]: https://en.wikipedia.org/wiki/I²C#Revisions
  [3]: https://help.github.com/en/articles/github-glossary#pull-request


body:
[bHogan][1] seems to be the original developer of TinyWireM and TinyWireS.
[Andreas Spiess][2] ("The guy with the Swiss accent") used [rambo's implementation of the TinyWire library][3] for his I2C sensor, and rambo on GitHub and bHogan on arduino.cc seem to be the same person...

I've also used rambo's TinyWire library, and managed to make it work. Adafruits version of TinyWire seems to be a fork of rambo's code.

  [1]: https://playground.arduino.cc/Code/USIi2c/
  [2]: https://www.youtube.com/watch?v=vj0SUYo8f_A
  [3]: https://github.com/rambo/TinyWire


message:
Parsing serial port data

Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).

    char inData[82]; //create 82 char array
    byte index = 0; //index byte (0 - 255)
    String string_convert; //String
    int PCdata[20]; //int array

    void setup() {
      Serial.begin(9600); //init port
    }

    void loop() {
      parsing(); //loop the function
    }

    void parsing() {
      while (Serial.available() > 0) {
        //while there is data in serial buffer (128 bytes)
        char aChar = Serial.read(); //aChar - current symbol in buffer
        if (aChar != 'E') {
          //if aChar isnt the 'E' (End) symbol do:
          inData[index] = aChar;
          //(inData - array, index - loop № counter) write all Buffer to the array
          index++; //index + 1 - loop count
          inData[index] = '\0';
          //set the next position to '\0' or null symbol
        } else {
          //if aChar or current buffer symbol is 'E' (End) do:
          char *p = inData; //create inData address pointer
          char *str; //create pointer
          index = 0; //set counter to 0
          String value = ""; //create string
          while ((str = strtok_r(p, ";", &p)) != NULL) { //???
            string_convert = str; //???
            PCdata[index] = string_convert.toInt(); //???
            index++; //counter + 1 - loop count
          }
          index = 0; //counter to 0
        }
      }
    }

Thank you for help!

body:
It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.

`strtok_r` is the reentrant version of `strtok`. On Arduino you simply use `strtok`. Every time you have to parse a string having a list of values separated by some char, you use `strtok`.

# Name

strtok, strtok_r - extract tokens from strings

# Synopsis

    #include <string.h>

    char *strtok(char *str, const char *delim);

    char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in `str`. In each subsequent call that should parse the same string, `str` should be NULL.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.


message:
Why doesn't millis() use 1 µsec or 1 msec interrupt?

Arduino `millis()` does not make use of one millisecond interrupt. Instead they make use of 1,024 µsec interrupts and manipulate. Any specific reason why this was implemented this way?

In one case, we can go for timer0 without prescaler and use 1 µsec interrupts. In such case, we have to use CTC mode with `OCR0A=15`. Inside ISR, we could update the microsecond counter and if it reaches 1,000, we could update the msec timer count. Otherwise we could go for directly 1 msec interrupt (maybe using timer0).

I wrote this code to get `micros()` and `millis()`. But there is some issue and I'm not able to get it working correctly.

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

    #include <avr/io.h>
    #include <avr/interrupt.h>

    #ifndef F_CPU
    #define F_CPU 16000000UL
    #endif

    volatile uint32_t oneMilliCounter;
    volatile uint32_t oneMicroCounter;
    extern void initializeTimer0CTC_Mode (void);

    extern uint32_t millis(void);
    extern uint32_t micros(void);

    volatile uint32_t oneMilliCounter = 0;
    volatile uint32_t oneMicroCounter = 0;

    uint32_t millis(void) {
      uint32_t value;
      uint8_t sregCopy = SREG;
      cli();
      value = oneMilliCounter;
      SREG = sregCopy;
      sei();
      return (value);
    }

    uint32_t micros (void) {
      uint32_t value;
      uint8_t sregCopy = SREG;
      cli();
      value = oneMicroCounter;
      SREG = sregCopy;
      sei();
      return (value);
    }

    void initializeTimer0CTC_Mode (void) {
      OCR0A = 15; // Set for 1 usec.
      TCCR0A |= 1 << WGM01;  // CTC Mode
      TIMSK0 |= 1 << OCIE0A;
      TCCR0B |= (1 << CS00); // prescaler=1
    }

    ISR(TIMER0_COMPA_vect) {
      static uint32_t prevMicro;
      oneMicroCounter++;
      if (oneMicroCounter - prevMicro >= 1000)   {
        prevMicro = oneMicroCounter;
        oneMilliCounter++;
      }
    }

    int main(void) {
      DDRD |= 1 << PD3;
      initializeTimer0CTC_Mode();
      sei();
      uint32_t prevTime = micros();
      while (1) {
        uint32_t currentTime = micros();
        if (currentTime - prevTime >= 1000) {
          PORTD ^= (1 << PD3);
          prevTime = currentTime;
        }
      }
      return (0);
    }

body:
One microsecond is only 16 CPU cycles.

The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a `jmp` instruction that takes
2 cycles. When the ISR is done, it executes the `reti` instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

* saving the context, i.e. pushing to the stack any register your ISR
  may modify (2 cycles per `push`)
* doing the actual ISR work
* restoring the context (2 cycles per `pop`)
* doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

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

**Edit**: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.

In the first experiment, I used your `initializeTimer0CTC_Mode()`
function to interrupt every microsecond the following program:

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

    // This ISR consists of a sigle `reti' instruction.
    EMPTY_INTERRUPT(TIMER0_COMPA_vect);

    #include <util/delay.h>

    int main(void)
    {
        initializeTimer0CTC_Mode();
        DDRD |= _BV(PD2);       // PD2 = digital 2 as output
        sei();
        for (;;) {
            PIND |= _BV(PD2);   // toggle PD2
            _delay_us(499.75);  // 0.5 ms - 4 cycles
        }
    }

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the `sei();` statement is commented out.
With the `sei();` statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the `reti` instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.

The second experiment was to compile and disassemble your ISR. Here is
what I got:

<!-- language: lang-clj -->

    __vector_14:
        push r1
        push r0
        in   r0, 0x3f  ; 1 cycle
        push r0
        eor  r1, r1    ; 1 cycle
        push r18
        push r20
        push r21
        push r22
        push r23
        push r24
        push r25
        push r26
        push r27
    ; static uint32_t prevMicro;
    ; oneMicroCounter++;
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        adiw r24, 0x01
        adc  r26, r1    ; 1 cycle
        adc  r27, r1    ; 1 cycle
        sts  0x0104, r24
        sts  0x0105, r25
        sts  0x0106, r26
        sts  0x0107, r27
    ; if (oneMicroCounter - prevMicro >= 1000)   {
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        lds  r20, 0x0100
        lds  r21, 0x0101
        lds  r22, 0x0102
        lds  r23, 0x0103
        sub  r24, r20   ; 1 cycle
        sbc  r25, r21   ; 1 cycle
        sbc  r26, r22   ; 1 cycle
        sbc  r27, r23   ; 1 cycle
        cpi  r24, 0xE8  ; 1 cycle
        sbci r25, 0x03  ; 1 cycle
        cpc  r26, r1    ; 1 cycle
        cpc  r27, r1    ; 1 cycle
        brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
    ;   prevMicro = oneMicroCounter;
        lds  r24, 0x0104
        lds  r25, 0x0105
        lds  r26, 0x0106
        lds  r27, 0x0107
        sts  0x0100, r24
        sts  0x0101, r25
        sts  0x0102, r26
        sts  0x0103, r27
    ;   oneMilliCounter++;
        lds  r24, 0x0108
        lds  r25, 0x0109
        lds  r26, 0x010A
        lds  r27, 0x010B
        adiw r24, 0x01
        adc  r26, r1    ; 1 cycle
        adc  r27, r1    ; 1 cycle
        sts  0x0108, r24
        sts  0x0109, r25
        sts  0x010A, r26
        sts  0x010B, r27
    ; } }
    0:
        pop  r27
        pop  r26
        pop  r25
        pop  r24
        pop  r23
        pop  r22
        pop  r21
        pop  r20
        pop  r18
        pop  r0
        out  0x3f, r0  ; 1 cycle
        pop  r0
        pop  r1
        reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(`push`) and restored (`pop`), and the large number of SRAM accesses
(`lds` and `sts`): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.


body:
Using CTC mode would mean you can't use pin 9 as a PWM pin anymore.

Also, setting `OCR0A` to 15, would mean PWM on pin 10 could only have 15 different PWM values.

So, in essence, pins 9 and 10 can't be used for PWM.


body:
Even if you could do what you are proposing, which you can't (see Edgar Bonet's excellent answer), imagine the performance hit running an interrupt *every single microsecond* would have on your code.

Every interrupt takes time away from your code.

Let's crunch some more numbers. If you wanted the millis/micros interrupt to take no more than 1% of the processing time, so it has no noticeable impact on your running code it would have to execute for only 10ns.  That's 1% of 1000ns, or 0.000001 x 0.01.

Now assume it takes 50 clock cycles for a highly optimised version of your function to operate. That's a conservative estimate. That includes the time taken to prepare for, call and return from the interrupt.

For both those to hold true you would have to be able to execute 100 x 50 instructions in a microsecond. (To fill your 1uS you should be able to run your 1% interrupt 100 times, yes?) That's 5,000 x (1/0.000001) instructions per second, or 5,000,000,000 instructions per second.

Assuming a single clock cycle for each instruction, that means your chip would have to be running at 5GHz...!

Can you see the problem?

So we scale it back to something more realistic. Maybe a 10% performance hit instead of 1%. How would that be? Well, it's simple enough to say that it would require a chip running at 10% of the speed. 500 x (1/0.000001). So 500MHz.

Still a long long way away from the 16MHz that the Arduino's ATMega runs at.

So you can see the issue.

So we choose close to 1mS instead. That gives a much lower overhead and it's something that the 16MHz Arduino can cope with.

Why 1024 and not 1000? That's simple: 1000 is base 10. We, as humans, with two hands (usually) of (normally) 5 digits on each, love base 10. We thrive in base 10.  However, computers with their 1s and 0s hate base 10. They much prefer working in base 2. It makes arithmetic really easy for them. And in interrupts we want the arithmetic to be easy.

Let's take a quick look at the maths involved and expand out the macros in the code.

Every tick the millis value is increased by `MILLIS_INC`, and any extra is added to a "fractional" count.  What's `MILLIS_INC`? It's:

    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

So let's expand that out - what's `MICROSECONDS_PER_TIMER0_OVERFLOW`?

    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

And what's `clockCyclesToMicroseconds`?

    #define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )

What's `clockCyclesPerMicrosecond()`?

    #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

And, of course, `F_CPU` is (typically) 16,000,000.

So now we can put it all together.

    #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
    becomes:

    #define MILLIS_INC ((clockCyclesToMicroseconds(64 * 256)) / 1000)
    which becomes:

    #define MILLIS_INC (((64 * 256)/clocksPerMicrosecond()) / 1000)

    Which in turn becomes:
    #define MILLIS_INC (((64 * 256)/(F_CPU/1000000L)) / 1000)

    Which finally turns into:
    #define MILLIS_INC (((64 * 256)/(16000000/1000000L)) / 1000)

    So reduce those down a little:
    #define MILLIS_INC ((16384 / 16) / 1000)

    And finally:
    #define MILLIS_INC (1.024)

And since we're talking integers here that is automatically truncated (by the compiler, not at runtime, so it's essentially "free") to 1.

But what about the 0.024ms...? That's simple. The "Fractional" amount is added to another counter - but not as 0.024 - instead as a `FRACT_INC` amount, which is calculated as `((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)`. That's 1024 % 100, or just 24, but then that's right shifted 3 times.  That becomes 3. And when that count hits another limit it loops round and adds one to the millis count.  That limit is `FRACT_MAX`, which is `1000 >> 3` or 125.

All nice and simple and straight forward. Variables, like the fractional count, are kept to just 8 bits (which is what you want on an 8 bit CPU...) and the majority of calculations are done by the compiler, not at runtime by the CPU.  Everything else is simple addition / subtraction and comparisons. Very light. And it runs often enough to be good enough for the majority of uses. And given that, because it's just a timer interrupt and is subject to collision with other interrupts, and can't run when interrupts are disabled, it's only a rough figure anyway. Even the act of reading `millis()` can slow down the counting of milliseconds, since it disables interrupts while the value of the count is retreived (a so called "critical section").

And yes, it could be tweaked to run at precisely 1000uS intervals and do away with the fractional component - but why bother when it's never going to be that accurate anyway? Also the added complexity of calculating what 1000uS is for a timer configuration when you consider the vast array of speeds that Arduinos could potentially run at (16MHz for an Uno, 8MHz for the 3.3V boards, 1MHz for the default internal oscillator...) it's far simpler to say "This is what it ticks at, and this is the number of milliseconds per tick, with this bit left over" which is calculated at compile time, instead of having to work out prescalers and overflow counts, etc.