body:
The following code was from a [rejected suggested edit][1], by an anonymous user, to the original post. See also [Rejected edit results in loss of constructive code modification][2].

 I have reproduced the code here - it may be of some use to someone:

    #include "Adafruit_WS2801.h"
    #include "SPI.h" // Comment out this line if using Trinket or Gemma
    #ifdef __AVR_ATtiny85__
    #include <avr/power.h>
    #endif
    #include <time.h>
    #include <stdlib.h>

    #define MIN_TIME 150000
    #define MAX_TIME 1000000
    #define RADIUS 240
    #define MAGNETS_NUM 1
    uint8_t shwFg = 1;
    uint8_t dataPin1  = 2;    // White wire on Adafruit Pixels
    uint8_t dataPin2  = 3;    // Yellow wire on Adafruit Pixels
    uint8_t dataPin3  = 4;    // Yellow wire on Adafruit Pixels
    uint8_t dataPin4  = 5;    // Yellow wire on Adafruit Pixels
    uint8_t clockPin1 = 10;    // White wire on Adafruit Pixels
    uint8_t clockPin2 = 11;    // Green wire on Adafruit Pixels
    uint8_t clockPin3 = 12;    // Green wire on Adafruit Pixels
    uint8_t clockPin4 = 13;    // Green wire on Adafruit Pixels
    uint8_t hallPin  = 20;
    uint8_t pointer1 =0;
    uint8_t pointer2 =8;
    uint8_t pointer3 =16;
    uint8_t pointer4 =24;

    int addr = 0;

    uint8_t LED1R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED2R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED3R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED4R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED5R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED6R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED7R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8_t LED8R[32] = {128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    uint8_t LED1B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED2B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED3B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED4B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED5B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED6B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED7B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};
    uint8_t LED8B[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128};

    uint8_t LED1G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED2G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED3G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED4G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED5G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED6G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED7G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};
    uint8_t LED8G[32] = {1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0};

    long now = 0;
    long prev =0;
    int hallState = 0;
    unsigned long previous = 0;
    unsigned long dlyMic =123456;

    Adafruit_WS2801 strip = Adafruit_WS2801((uint16_t)8, dataPin1, clockPin1);
    Adafruit_WS2801 strip2 = Adafruit_WS2801((uint16_t)8, dataPin2, clockPin2);
    Adafruit_WS2801 strip3 = Adafruit_WS2801((uint16_t)8, dataPin3, clockPin3);
    Adafruit_WS2801 strip4 = Adafruit_WS2801((uint16_t)8, dataPin4, clockPin4);

    int a = 0;
    unsigned long current=0;
    unsigned long  delta=0;
    void GetDelay() {
      previous = current;
      current = micros();

    //  previous = micros();

    }

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif

     pinMode(hallPin, INPUT);
     Serial.begin(115200);

      strip.begin();
      strip2.begin();
      strip3.begin();
      strip4.begin();
      attachInterrupt(3, GetDelay, RISING);

    }
    void delayMicroseconds2(unsigned int us)
    {
            // calling avrlib's delay_us() function with low values (e.g. 1 or
            // 2 microseconds) gives delays longer than desired.
            //delay_us(us);
            // for the 16 MHz clock on most Arduino boards

            // for a one-microsecond delay, simply return.  the overhead
            // of the function call yields a delay of approximately 1 1/8 us.
            if (--us == 0)
                    return;

            // the following loop takes a quarter of a microsecond (4 cycles)
            // per iteration, so execute it four times for each microsecond of
            // delay requested.
            us <<= 2;

            // account for the time taken in the preceeding commands.
            us -= 2;

            // busy wait
            __asm__ __volatile__ (
                    "1: sbiw %0,1" "\n\t" // 2 cycles
                    "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
            );
    }
    void loop() {
     // prev = micros();
      //    noInterrupts();

      delta  = current - previous;

      if (delta > MAX_TIME) {
        shwFg = 0;
      }else{
        shwFg = 1;
      }

      shwFg = 1;
      delta<<1;
      delta-=650;

        if (shwFg == 0) {
            int i;
            for (i = 0; i < 8; i++){
              strip.setPixelColor(i, 0, 0, 0);
              strip2.setPixelColor(i, 0, 0, 0);
              strip3.setPixelColor(i, 0, 0, 0);
              strip4.setPixelColor(i, 0, 0, 0);
            }
        }
        else {

          strip.setPixelColor(0, LED1R[pointer1] ,(LED1B[pointer1] ) ,(LED1G[pointer1] ) );
          strip2.setPixelColor(0, LED1R[pointer2] ,(LED1B[pointer2] ) ,(LED1G[pointer2] ) );
          strip3.setPixelColor(0, LED1R[pointer3] ,(LED1B[pointer3] ) ,(LED1G[pointer3] ) );
          strip4.setPixelColor(0, LED1R[pointer4] ,(LED1B[pointer4] ) ,(LED1G[pointer4] ) );

          strip.setPixelColor(1, LED2R[pointer1] ,(LED2B[pointer1] ) ,(LED2G[pointer1] ) );
          strip2.setPixelColor(1, LED2R[pointer2] ,(LED2B[pointer2] ) ,(LED2G[pointer2] ) );
          strip3.setPixelColor(1, LED2R[pointer3] ,(LED2B[pointer3] ) ,(LED2G[pointer3] ) );
          strip4.setPixelColor(1, LED2R[pointer4] ,(LED2B[pointer4] ) ,(LED2G[pointer4] ) );

          strip.setPixelColor(2, LED3R[pointer1] ,(LED3B[pointer1] ) ,(LED3G[pointer1] ) );
          strip2.setPixelColor(2, LED3R[pointer2] ,(LED3B[pointer2] ) ,(LED3G[pointer2] ) );
          strip3.setPixelColor(2, LED3R[pointer3] ,(LED3B[pointer3] ) ,(LED3G[pointer3] ) );
          strip4.setPixelColor(2, LED3R[pointer4] ,(LED3B[pointer4] ) ,(LED3G[pointer4] ) );

          strip.setPixelColor(3, LED4R[pointer1] ,(LED4B[pointer1] ) ,(LED4G[pointer1] ) );
          strip2.setPixelColor(3, LED4R[pointer2] ,(LED4B[pointer2] ) ,(LED4G[pointer2] ) );
          strip3.setPixelColor(3, LED4R[pointer3] ,(LED4B[pointer3] ) ,(LED4G[pointer3] ) );
          strip4.setPixelColor(3, LED4R[pointer4] ,(LED4B[pointer4] ) ,(LED4G[pointer4] ) );

          strip.setPixelColor(4, LED5R[pointer1] ,(LED5B[pointer1] ) ,(LED5G[pointer1] ) );
          strip2.setPixelColor(4, LED5R[pointer2] ,(LED5B[pointer2] ) ,(LED5G[pointer2] ) );
          strip3.setPixelColor(4, LED5R[pointer3] ,(LED5B[pointer3] ) ,(LED5G[pointer3] ) );
          strip4.setPixelColor(4, LED5R[pointer4] ,(LED5B[pointer4] ) ,(LED5G[pointer4] ) );

          strip.setPixelColor(5, LED6R[pointer1] ,(LED6B[pointer1] ) ,(LED6G[pointer1] ) );
          strip2.setPixelColor(5, LED6R[pointer2] ,(LED6B[pointer2] ) ,(LED6G[pointer2] ) );
          strip3.setPixelColor(5, LED6R[pointer3] ,(LED6B[pointer3] ) ,(LED6G[pointer3] ) );
          strip4.setPixelColor(5, LED6R[pointer4] ,(LED6B[pointer4] ) ,(LED6G[pointer4] ) );

          strip.setPixelColor(6, LED7R[pointer1] ,(LED7B[pointer1] ) ,(LED7G[pointer1] ) );
          strip2.setPixelColor(6, LED7R[pointer2] ,(LED7B[pointer2] ) ,(LED7G[pointer2] ) );
          strip3.setPixelColor(6, LED7R[pointer3] ,(LED7B[pointer3] ) ,(LED7G[pointer3] ) );
          strip4.setPixelColor(6, LED7R[pointer4] ,(LED7B[pointer4] ) ,(LED7G[pointer4] ) );

          strip.setPixelColor(7, LED8R[pointer1] ,(LED8B[pointer1] ) ,(LED8G[pointer1] ) );
          strip2.setPixelColor(7, LED8R[pointer2] ,(LED8B[pointer2] ) ,(LED8G[pointer2] ) );
          strip3.setPixelColor(7, LED8R[pointer3] ,(LED8B[pointer3] ) ,(LED8G[pointer3] ) );
          strip4.setPixelColor(7, LED8R[pointer4] ,(LED8B[pointer4] ) ,(LED8G[pointer4] ) );
       }

        strip.show();
        strip2.show();
        strip3.show();
        strip4.show();
        //delay(10);
        pointer1++;
        pointer1&=31;

        pointer3++;
        pointer3&=31;

        pointer2++;
        pointer2&=31;

        pointer4++;
        pointer4&=31;
      //       interrupts();
       // now =micros();
        delayMicroseconds2(delta);

      //Serial.println(now - prev);

    }

  [1]: https://arduino.stackexchange.com/review/suggested-edits/22215
  [2]: https://arduino.meta.stackexchange.com/questions/2421/rejected-edit-results-in-loss-of-constructive-code-modification


sender: user

message:
How to choose a transmit pin in the IRremote library for an Arduino Uno?

I am looking for a way to choose a pin on the Arduino Uno. This pin will be used to send the signal of an IR LED. I am using the **[IRremote][1]** library.

e.g.

Below is the IR send demo which uses pulse width modulation pin 3 to send the IR signal. I want to change that pin to any other pin.

Any pointers will make me very happy thanks.

  [1]: https://github.com/z3t0/Arduino-IRremote

    /*
     * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
     * An IR LED must be connected to Arduino PWM pin 3.
     * Version 0.1 July, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     */

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
     for (int i = 0; i < 3; i++) {
      irsend.sendSony(0xa90, 12);
      delay(40);
     }
     delay(5000); //5 second delay between each signal burst
    }

sender: assistant

body:
As the pin does not appear to be able to be defined when creating an object from the `IRsend` class, it seems as if you will have to modify the [IRremote][1] library itself.

I recently had the same problem with the [USB Host library][3], see [Change select pin of USB Host library][2]. It *is* annoying when you can't define the pin(s), that a particular library uses, yourself... However, the authors of the library probably have their reasons for doing so.

Looking through the various headers of the library, I found in `boarddefs.h` on [lines 134-138][4]:

    // Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
    // ATmega48, ATmega88, ATmega168, ATmega328
    #else
     //#define IR_USE_TIMER1   // tx = pin 9
     #define IR_USE_TIMER2     // tx = pin 3

So, the line to change, for the Uno, would seem to be [line 138 in boarddefs.h][5]

     #define IR_USE_TIMER2     // tx = pin 3

However, it is not, as that merely states that for the Arduino Uno `IR_USE_TIMER2` is used...

Looking further down to where the Timers are defined, you will see the section for Timer 2, on [line 146][6]. In that section the transmit pin, for a number of versions of the Arduino, is defined as `TIMER_PWM_PIN` on [lines 189-197][7]:

    #elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \
    || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \
    || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \
    || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \
    || defined(__AVR_ATmega164P__)
    # define TIMER_PWM_PIN  14             // MightyCore
    #else
    # define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc
    #endif                      // ATmega48, ATmega88, ATmega168, ATmega328

You will have to change this line in the library, [Line 196 in boarddefs.h](https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L196):

    # define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc

You could try changing the `3` so that you can use another pin. It might work. For example to use pin 5, en lieu of pin 3, change the `3` to a `5`, like so:

    # define TIMER_PWM_PIN  5              // Arduino Duemilanove, Diecimila, LilyPad, etc

**Be careful** not to choose a pin that is used by something else, **AND** I think that the pin will need to be PWM capable.

Note that the definitions that are in `boarddefs.h` used to be in `RemoteInt.h`, in earlier versions of the library. See this comment at the very top:

    // This file contains all board specific information. It was previously contained within
    // IRremoteInt.h

 So, make sure that you have the latest version of the [IRremote library][1].

-----

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see [lines 68-71][8]:

    // Arduino Mega
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
     //#define IR_USE_TIMER1   // tx = pin 11
     #define IR_USE_TIMER2     // tx = pin 9

Other boards are also defined in this file. If you have another type of board, the timer may be different, but the process to find which line to change would be very similar...

  [1]: https://github.com/z3t0/Arduino-IRremote
  [2]: https://arduino.stackexchange.com/questions/33379/change-select-pin-of-usb-host-library
  [3]: https://github.com/felis/USB_Host_Shield_2.0
  [4]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L134
  [5]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L138
  [6]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L146
  [7]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L196
  [8]: https://github.com/z3t0/Arduino-IRremote/blob/master/boarddefs.h#L68


body:
I tried to find where the pin is defined and gave up, I ended up swapping to pin9 by commenting out timer2, like this:

    #define IR_USE_TIMER1   // tx = pin 9
    //#define IR_USE_TIMER2     // tx = pin 3

Not ideal since I needed 9 also and I will add how annoying this library is that although I only need to receive signals and never send...it still takes up a pin for sending.

ANyway, the posts above helped me at least get my motor shield working, thanks guys.


message:
Serial Getting Garbage Data with real data

I have made an app in VS2015 C#.Net which sends data to Serial port. The data i am sending is:

    stat>temp:39,38,;load:17,4,42,;fans>50,50,;

Where as I am receiving:

    ððððstat>temp:39,38,;load:17,4,42,;fans>50,50,;

**What I have tried:**

 - Set SerialPort Encoding to ASCII in C#
 - Set SerialPort Encoding to UTF8 in C#
 - Set SerialPort Encoding to Default in C#

All have no effect.

**Some observations:**

 - When I send the data via Serial Monitor of Arduino there is no garbage data.
 - When I send data via a USB to TTL converter via my App, no garbage. (This part confuses me more)

BAUD RATE IS: 115200.

This is the only thing I have not changed yet and I dont want to change this as the string length will increase over time. this is 43 bytes of data. It can grow to up-to around 64 or 100 bytes and that would take longer to send and even longer to read adding delays in functions that are already working before the serial interrupt.

Regards

body:
The Arduino should read only whole lines (non-newlines until a newline). Discard the line if it doesn't start with "stat>".

This will make your program more robust and less likely to fail with bad input. Fixing the transmitting app instead still leaves your Arduino vulnerable.

Consider the rule of thumb for serial communication: "Be restrictive in what you'll transmit; be lax in what you'll receive." Specify your communication protocol (e.g. "Packets will begin with 'stat>' and end with <newline>", maximum length of a packet, formats of variables and numbers, etc.). Then write your sender to hold as tightly to the spec as possible and write your receiver to accept whatever minor variations in otherwise good packets, that won't cause you to mistakenly accept bad ones. This principle will make your communications systems more robust and easier to get working in the first place.


message:
Increase Serial Rx buffer

I am working with an Arduino Due and I am having some issue with the serial Rx buffers size. I am using a GSM module and some of the replies to the Arduino exceed the number of bytes I can store in the buffer at once.

I have read about ways to increase the buffer size by modifying the Arduino default install files but I cannot take this route as my code may then be compiled on a machine with standard buffer sizes in the default install files and the module would not work correctly.

I am not sure if it is possible but I was hoping that someone might know how to increase the serial buffer size using the source code. If I can do it this way the buffer would always be the size I have specified.

body: Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.


message:
How to on/off light dimmer using another pin?

In recent project, I'm working with light dimmer.

Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer.

Here is my full code.

    int kPinPWM = 9; // This pin provides PWM values

    int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
    int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

    int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

    int i = 0;

    int temp = 0; // Flag

    void setup()
    {
      pinMode(kPinPWM, OUTPUT);

      pinMode(kPinSW1, INPUT);
      pinMode(kPinSW2, INPUT);

      digitalWrite(kPinSW1, HIGH);
      digitalWrite(kPinSW2, HIGH);

      pinMode(kPinSw, INPUT);

      digitalWrite(kPinSw, HIGH);
    }

    void loop()
    {
      if(digitalRead(kPinSw) == LOW && temp == 0) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 0
      {
        temp = 1; // Change value to 1 // temp = 1

        digitalWrite(kPinPWM, HIGH); // Turn ON PWM pin (PIN 9)

        if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
        {
          i++;

          if(i > 4)
          {
            i = 4;
          }

          while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON pressed
        }

        if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
        {
          i--;

          if(i < 0)
          {
            i = 0;
          }

          while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
        }

        switch (i)
        {
          case 0:
                  analogWrite(kPinPWM, 0); // When Button pressed not pressed send 0 value
          break;

          case 1:
                  analogWrite(kPinPWM, 64); // When Button pressed and i = 1 send 64 value
          break;

          case 2:
                  analogWrite(kPinPWM, 128); // When Button pressed and i = 2 send 128 value
          break;

          case 3:
                 analogWrite(kPinPWM, 192); // When Button pressed and i = 3 send 192 value
          break;

          case 4:
                 analogWrite(kPinPWM, 255); // When Button pressed and i = 4 send 255 value
          break;
        }
      }

      if(digitalRead(kPinSw) == LOW && temp == 1) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 1
      {
        temp = 0; // Change value to 0 // temp = 0

        digitalWrite(kPinPWM, LOW); Turn OFF PWM pin (PIN 9)
      }
    }

body:
Thank you for the clarification.

Here's some code which should do that:

    int kPinPWM = 9; // This pin provides PWM values

    int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
    int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

    int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

    // Startup settings:
    int level = 0;          // Lowest level
    boolean on = false;     // Off

    void setup()
    {
      pinMode(kPinPWM, OUTPUT);

      pinMode(kPinSW1, INPUT);
      pinMode(kPinSW2, INPUT);
      pinMode(kPinSw, INPUT);

      digitalWrite(kPinSW1, HIGH);
      digitalWrite(kPinSW2, HIGH);
    }

    void loop()
    {
        // Read each button in turn
        if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
        {
           level++;

           if(level > 4)
           {
             level = 4;
           }

           while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON released
        }

        if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
        {
           level--;

           if(level < 0)
           {
             level = 0;
           }

           while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
        }

        if(digitalRead(kPinSw) == LOW ) // Pressed PUSH BUTTON to switch on/off
        {
            // If we're already on, switch off.
            if (on) on=false;
            // If we're already off, switch on.
            else on=true;

            while(digitalRead(kPinSW1) == LOW); // Until button is released
        }

        // Now set the PWM output
        if (on)
        {
            // We're on, so set the level
            switch (level)
            {
                case 0:
                    // Maybe you don't want this "off" level..?
                    analogWrite(kPinPWM, 0);
                break;

                case 1:
                    analogWrite(kPinPWM, 64);
                break;

                case 2:
                    analogWrite(kPinPWM, 128);
                break;

                case 3:
                    analogWrite(kPinPWM, 192);
                break;

                case 4:
                    analogWrite(kPinPWM, 255);
                break;

                default:
                    // This should never happen but we should
                    // handle it "just in case"
                    analogWrite(kPinPWM, 255);
            }
        }
        else
        {
            // We're off, so stop the PWM
            analogWrite(kPinPWM, 0);
        }
    }

We hold two variables: the level, and on/off state.

Buttons 6 and 7 affect the level, and button 10 affects the on/off state.

As with a fan, this code lets us change the "level" even when it's switched off.  It has no immediate effect, but when you switch back on, the level will have changed.

---

Some things to say about the question in general:

 1. Try to explain more clearly exactly what you want to achieve.  For example, what *exactly* do you want button 10 to do?  Switch the PWM on?  On to what value?  I've chosen mid-way, but you could possibly want the highest value, or the lowest value, or the value it was last time you pressed button 10.
 2. There's no need to comment code so literally.  We know *literally* what `if(temp==0)` does.  What would be helpful is to give things proper names, and/or explain their *meaning*.  What are you trying to achieve with `temp`?  (It wasn't clear to me at all, so I removed it.)


body:
Finally I find out solution. Here, I detect when switch becomes pressed instead of  button is pressed. So, for that I used StateChangeDetection. So while loop just removed from code. And I made function to perform dimmer and vise versa operation.
k
So, now I'm able to ON/OFF the PWM pin. And also vary PWM pin. Thanks everyone for your effort.

Here, it's my full code.

    const int buttonPin1 = 2;
    const int buttonPin2 = 3;
    const int buttonPin3 = 4;

    const int pwmPin = 9;

    const int onOffPin = 10;

    int buttonState1 = 0;
    int lastButtonState1 = 0;

    int buttonState2 = 0;
    int lastButtonState2 = 0;

    int buttonState3 = 0;
    int lastButtonState3 = 0;

    int buttonPushCounter = 0;

    int onOffCounter = 0;

    void setup()
    {
       pinMode(buttonPin1, INPUT);
       pinMode(buttonPin1, INPUT);

       pinMode(pwmPin, OUTPUT);

       pinMode(onOffPin, OUTPUT);

       Serial.begin(9600);
    }

    void loop()
    {
       buttonState3 = digitalRead(buttonPin3);

       if(buttonState3 != lastButtonState3)
       {
         if(buttonState3 == HIGH)
         {
           onOffCounter++;
           Serial.println("Button 3 on");
           Serial.print("number of button 3 pushes:  ");
           Serial.println(onOffCounter);
         }
         else
         {
           Serial.println("Button 3 off");
         }
         delay(50);
       }

       lastButtonState3 = buttonState3;

       if(onOffCounter % 2 == 0)
       {
         Serial.println("Switch is OFF");

         analogWrite(pwmPin, 0);
       }
       else
       {
          PWM_fun();

          Serial.println("Switch is ON");
       }
    }

    void PWM_fun()
    {
      buttonState1 = digitalRead(buttonPin1);

      if (buttonState1 != lastButtonState1)
      {
        if (buttonState1 == HIGH)
        {
          buttonPushCounter++;
          Serial.println("Button 1 on");
          Serial.print("number of button 1 pushes:  ");
          Serial.println(buttonPushCounter);

          if(buttonPushCounter > 4)
          {
             buttonPushCounter = 4;
          }
        }
        else
        {
          Serial.println("Button 1 off");
        }
        delay(50);
      }

      lastButtonState1 = buttonState1;

      buttonState2 = digitalRead(buttonPin2);

      if(buttonState2 != lastButtonState2)
      {
        if(buttonState2 == HIGH)
        {
          buttonPushCounter--;
          Serial.println("Button 2 on");
          Serial.print("number of button 2 pushes:  ");
          Serial.println(buttonPushCounter);

          if(buttonPushCounter < 0)
          {
             buttonPushCounter = 0;
          }
        }
        else
        {
          Serial.println("Button 2 off");
        }
        delay(50);
      }

      lastButtonState2 = buttonState2;

      switch (buttonPushCounter)
      {
          case 0:
                  analogWrite(pwmPin, 0);
          break;

          case 1:
                  analogWrite(pwmPin, 64);
          break;

          case 2:
                  analogWrite(pwmPin, 128);
          break;

          case 3:
                  analogWrite(pwmPin, 192);
          break;

          case 4:
                  analogWrite(pwmPin, 255);
          break;
      }
    }


message:
How to run background music while the code for a game is executed

I have some background music. If I put it at the top of the `void loop()`, it'll first play the music and then execute the game code afterwards.

How do I have the code run while the background music is playing?

body: Run the music through a time Interrupt.


body:
It all depends on the architecture of your game. The first games probably interleaved their music and gameplay, as the comment above says. This is probably the level of complexity you are looking for, on an Arduino.

First you need to pick some "framerate" that the game advances with. You could, for example, play 4 frames of music for every video frame, or something like that. It also depends how you are playing music. If you are just playing notes with the analog out, this approach would work. Here is some pseudocode that updates the PWM output 4 times faster than the game code:

    set n = 0
    set quit = false

    // main game loop
    while !quit
        // set music output pwm here
        if n % 4 == 0
            // advance game here
        endif
        n++
    endwhile

If you are playing music from something like an SD card, you are constrained by the bit rate of the music.

Also, here is an article on Arduino **protothreading** that might interest you. https://create.arduino.cc/projecthub/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37. My suggestion is to look at how the old game systems implemented their state machines.


message:
Error: Cannot find module 'serialport'. node.js, Arduino Yun

I carefully followed [Andy Sigler's tutorial](http://andysigler.com/teaching/nodejs-arduino-yun/) on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc

body:
I solved the problem by following these steps:

Make a folder node_modules in mnt/sda1/

cd /mnt/sda1

wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1_mips-25-ubuntu.tar.gz -O serialport-1.6.1_mips-25-ubuntu.tar.gz

run $ tar xvf serialport-1.6.1_mips-25-ubuntu.tar.gz -C /mnt/sda1/node_modules


message:
Which Arduino is the most suitable for my project?

I've started to prototype something using an Arduino Mega and Yún Shield.

It's simple. It reads an ADC at 50Hz and sends data to a server through a socket. But because of that combination, I need to use Bridge to send data through the socket. It's very slow.

Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

Here is my code, maybe I did something wrong.

Arduino code:

    #include <Bridge.h>
    #include <Process.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <stdlib.h>

    boolean interruptFlag = 0;
    int HD = A0;
    int HG = A1;
    int CD = A2;
    int CG = A3;
    int ECG = A5;
    String analogSignals = "";
    static char outstr[15];
    int count = 0;
    float x = 0.0;

    void setup() {
      // Bridge startup.
      Bridge.begin();
      // Initialize Bridge values.
      Bridge.put("data", "");
      noInterrupts(); // Stop interrupts.
      TCCR1A = 0; // Set entire TCCR1A register to 0.
      TCCR1B = 0; // Same for TCCR1B.
      TCNT1  = 0; // Initialize counter value to 0.
      // Set compare match register for 50Hz increments.
      OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
      // Turn on CTC mode.
      TCCR1B |= (1 << WGM12);
      // Set CS12, CS11 and CS10 bits for 64 prescaler.
      TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
      // Enable timer compare interrupt.
      TIMSK1 |= (1 << OCIE1A);
      interrupts(); // Allow interrupts.
      // Launch Python script.
      /*Process p;
      p.begin("python");
      p.addParameter("/root/test/send.py");
      p.run();*/
    }

    ISR(TIMER1_COMPA_vect) {
      if (!interruptFlag) {
        interruptFlag = 1;
      }
    }

    void loop() {
      if (interruptFlag) {
        writeAnalogSignals();
        interruptFlag = 0;
      }
    }

    void writeAnalogSignals() {
      String HDReading = convertToVoltage(analogRead(HD));
      String HGReading = convertToVoltage(analogRead(HG));
      String CDReading = convertToVoltage(analogRead(CD));
      String CGReading = convertToVoltage(analogRead(CG));
      String ECGReading = convertToVoltage(analogRead(ECG));
      if (analogSignals.length() == 0) {
        analogSignals =  String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
      } else {
        analogSignals += "|" + String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
      }
      x += 0.02;
      count += 1;
      if (count >= 50) {
        Bridge.put("data", analogSignals);
        analogSignals = "";
        count = 0;
      }
    }
    // Convert the analog reading to voltage.
    String convertToVoltage(int analogSignal) {
      dtostrf(analogSignal * (5.0 / 1023),8, 6, outstr);
      return outstr;
    }

Python code:

    import socket
    import sys
    import getopt
    import time

    def main(argv):
     try:
      sys.path.insert(0, '/usr/lib/python2.7/bridge/')
      from bridgeclient import BridgeClient as bridgeclient
      # Create a UDP socket.
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      server_address = ('192.168.1.100', 9050)
      bridge = bridgeclient()
      previous = ""

      # Send data
      while 1:
       data = bridge.get("data")
       if data != previous:
        sent = sock.sendto(data, server_address)
        previous = data
       time.sleep(0.5)

     finally:
      sock.close()

body:
The Bridge running in Python in Linux is the biggest problem. Open a terminal (for example with putty) and run `top` to see the CPU usage. Try to keep it under 50%.

A few parameters at 5 times per second with `Bridge.put()` is possible, but I don't recommend it, because of the CPU load in Linux. The 50Hz is way too much. Beside that you have also a Python script to send them to a server.

There is about 30 MB of fast RAM storage in /tmp and more storage if you add an SD memory card. You could do a test to write the data to a file, and upload the file every few seconds.

If you really need 50Hz, then I suggest to try the Raspberry Pi (or the ESP8266, as mentioned).

The `dtostrf()` function does not return a String, but a buffer. You could easily get rid of the Strings, to have more time in the Arduino. A good use of` millis()` is just as accurate as a timer. I think you can do the same without the hardware timer and without the interrupt.

**ADDED:** Chris Stratton pointed out that the Bridge is not the problem, so I did a small test.

Using 4 values with short names (like: "temp"). Writing them with `Bridge.put()` every second, and reading them in a webpage via `zepto.min.js` every second is a CPU load of 6% for `python -u bridge.py`.

Writing them 50 times per second and reading 1 time per second is a CPU load of 25% for the bridge.

Writing them 50 times per second and reading them 50 times per second does not change a lot, it adds extra load for uhttpd, resulting in a total of about 60 to 70%. That is still okay to run commands from a terminal.

This 'clean' test is different from my previous tests. It is therefore indeed possible to send data through the Bridge at 50 times per second. Sorry for my wrong answer.


body:
> Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

You didn't quite say what kind of performance gains you had in mind. Looking at your code, it doesn't have any particular needs to justify a fancier Arduino.

With that said, I wanted to highlight one particular aspect of ATmega32u / Leonardo that in my view made it a particularly interesting chip for mixed signal application: its ADC unit features a PGA (1x, 10x, 200x) in differential mode with bipolar readings.

it can be quite handy for some applications.


body:
Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.

In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.

The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.

We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.

I can see a few design issues right away.

1. Don't use libraries for what one can do in just a few low level lines of code.
2. Don't place numbers in strings. Keep them as numbers.
3. Send the numbers as messages placed carefully into byte arrays using bitwise operations.
4. Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
5. Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.

It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.


body:
@JonathanAnctil, @ChrisStratton, I have done some more tests, and the Bridge.put takes an average of 7 milliseconds in the sketch. For 5 values at a rate of 50Hz, that alone takes 1.7 seconds. The Bridge can not keep up with that rate, but the overall cpu load in linux is still under 50%. Therefor the cpu load does not indicate if everything is running okay.

Because I was looking at the cpu load, I took the wrong assumption that it was possible. These tests confirm my previous experiences that the Bridge is too slow.

I have installed extra packages in linux, but I think they will not influence the slow Bridge.put.

With more tests with Bridge.put I learned that Bridge.put takes 4ms, plus 0.3ms per character for the key name and the value text, plus the delay caused by things running at the other side of the Bridge in linux.

The value must be a zero terminated string, it is not possible to send binary data. Suppose turning it into readable hex values, then 20 bytes are needed for the value.
With the key name as a single character, and a value of 20 bytes, it takes 10 ms. However, then the values have to be retrieved (and converted) at the other side of the Bridge. I assume that Python will also slow down the Bridge.put, just like Javascript does.

This is my test sketch.

    // Showing the webpage on the other side of the Bridge with zepto.min.js
    // and 50 updates per seconds slows down the sketch, because the Bridge.put
    // in the sketch will take a lot more time.
    // A Bridge.put takes about 7 to 260 ms when the webpage is in a browser
    // with 50Hz updates.
    // A Bridge.put takes about 7 ms when the webpage is not shown in a browser.
    // A itoa takes about 13 us.
    //
    // When showing the webpage with 50Hz updates:
    //     Only the counter : 43 seconds for 1000 counts = 23 Hz
    //     With 6 analog inputs and the free ram : 342 seconds for 1000 counts = 3 Hz
    // When showing the webpage with once per 5 seconds updates:
    //     Only the counter : 20 seconds for 974 counts = 49 Hz
    //     With 6 analog inputs and the free ram : 50 seconds for 985 counts = 20 Hz

    #include <Bridge.h>

    Process yunProcess;

    unsigned long previousMillis;

    #define NUM_PINS 6
    const int pins[NUM_PINS] = { A0, A1, A2, A3, A4, A5, };
    const char * names[NUM_PINS] = { "A0", "A1", "A2", "A3", "A4", "A5" };

    void setup()
    {
    //  SerialUSB.begin(115200);
    //  while(!SerialUSB);
    //  SerialUSB.println("Started");
      Bridge.begin();
    //  SerialUSB.println("Bridge is running");
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      // A software timer of 50Hz.
      if(currentMillis - previousMillis >= 20UL)
      {
        previousMillis = currentMillis;

        // The fastest way to turn an integer into text is with itoa.
        // The function itoa takes about 13us.
        // A buffer is used for itoa.
        char buffer[20];

        for(int i=0; i<NUM_PINS; i++)
        {
          int adc = analogRead(pins[i]);
          itoa(adc, buffer, 10);
          Bridge.put(names[i], buffer);
        }

        int freeram = freeRam();
        itoa(freeram, buffer, 10);
        Bridge.put("freeRam", buffer);

        // a counter.
        static int count;
        count++;
        itoa(count, buffer, 10);
    //    unsigned long t1 = micros();
        Bridge.put("counter", buffer);
    //    unsigned long t2 = micros();
    //    SerialUSB.println(t2 - t1);

    //    SerialUSB.println(count);
      }
    }

    int freeRam ()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

And my test webpage is:

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test</title>

    Show JSON data

    Analog Input A0 = ---

    Analog Input A1 = ---

    Analog Input A2 = ---

    Analog Input A3 = ---

    Analog Input A4 = ---

    Analog Input A5 = ---

    freeRam = ---

    counter = ---


message:
Arduino Countdown without using delay()

I am working on a project which requires countdown from 30sec to 0sec. I can't use delay() function because I am taking input from keyboard during countdown. millis() function wont help because my board will be active for more than 50 days. I require something like counter which I can reset after or before completion of 30sec.

body:
## Background

The function `millis ()` returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).

See: <http://arduino.cc/en/Reference/Millis>

Example:

    unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.

Computing this in terms of days we have:

    2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

---

## Is this bad?

No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.

Let's clear up some misconceptions:

* The processor does not reset when the timer overflows.
* The timer does not stop.
* Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

---

## How do I time an event?

There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, **subtracting** is the correct way.

---

## Example of adding - **not recommended**!

I want to detect a minute in the future...

    unsigned long startTime = millis ();
    unsigned long whenToStop = startTime + 60000;

    ...

    if (millis () >= whenToStop)
      {
      // do something
      }

This will work most of the time, but not when the timer overflows. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

    2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:

    2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

---

## Example of subtracting - recommended

I want to detect a minute in the future...

    unsigned long startTime = millis ();
    unsigned long interval = 60000;

    ...

    if (millis () - startTime >= interval)
      {
      // do something
      }

This will work **all the time**. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

    2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:

    // millis () - startTime   = elapsed interval
        0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of `0xFF0000C350`. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.

Demo using the Mac Calculator app:

[![millis() rollover][1]][1]

In 60 seconds the timer goes to 10000. Subtracting now gives us:

    // millis () - startTime   = elapsed interval
        10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.

Directly after we set up startTime and millis we will see a sequence like this:

    millis ()   -  startTime    =  difference
                                 (modulo 2^32)
    4294917296     4294917296               0  <-- we start timing here
    4294917297     4294917296               1
    4294917298     4294917296               2
    ...
    4294967295     4294917296           49999  <-- largest unsigned long value
             0     4294917296           50000  <-- wraps here back to zero
             1     4294917296           50001  <-- keeps counting up
    ...
          9999     4294917296           59999
         10000     4294917296           60000  <-- time's up!

---

## Recommended method

*  Use unsigned long (not just long) for "time" variables.
*  Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
*  Subtract the start time from the time now, giving a difference.
*  See if the difference exceeds the desired interval.

eg.

    startedFeedingFish = millis ();

    ...

    if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
      {
      // stop feeding the fish
      }

---

## Can't I just reset millis?

You can, but you **don't need to**. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

---

## What about micros?

The function `micros()` returns the number of **microseconds** since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.

     2^32 / 1000 / 1000 / 60  = 71.58 minutes

<http://arduino.cc/en/Reference/Micros>

However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.

Also be aware that the resolution of `micros()` is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

---

## Limitations

If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

---

## Reference

This answer taken from my page <http://www.gammon.com.au/millis>

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


message:
Arduino LCD is displaying gibberish, sometimes

Below is my code and a picture of the gibberish.  It's different every time.  If i pull out the temp sensor, i still get gibberish, sometimes.  I'm at a loss as to what to even be looking at now. Any ideas?

 [![gibberish][1]][1]

<!-- language: c -->

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    //set capacities
    int keg1_volume = 19;
    int keg2_volume = 19;
    const int temperaturePin = 0;

    void setup() {
      //initial delay
      delay(1000);

      //set contrast
      pinMode(9, OUTPUT);
      analogWrite(9, 100);

      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);

      // Print header to the LCD
      lcd.setCursor(6, 0);
      lcd.print("BeerView");
      lcd.setCursor(0,1);
      lcd.print("Keg (C)");
      lcd.setCursor(10,1);
      lcd.print("Keg (F)");

      //initialize serial for debugging
      Serial.begin(9600);

      //get voltage and calculate temp
      float voltage, degreesC, degreesF;
      voltage = getVoltage(temperaturePin);
      degreesC = (voltage - 0.5) * 100.0;
      degreesF = degreesC * (9.0/5.0) + 32.0;

      //display temp
      lcd.setCursor(0,2);
      lcd.print(degreesC);
      Serial.println(degreesC);
      lcd.setCursor(10,2);
      lcd.print(degreesF);
      Serial.println(degreesF);

    }

    void loop() {
    }

    float getVoltage(int pin)
    {
      return (analogRead(pin) * 0.004882814);
    }

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

body: Used a pot instead of the PWM from pin 9.  Thanks for the help!!


message:
Pattern detection in sensor data

I'm using a heart rate sensor along with an Arduino for a project of mine. I have to determine whether the heartbeat is following a particular pattern (eg: when when heartbeat regularizes a lot after a period of increased or largely varying, I need to trigger an alarm to show that it has regularized).

Can anyone give me suggestions on how I can go about doing this? Are there any libraries or software for doing basic statistical analysis on data like this?

body:
[This Arduino topic](http://forum.arduino.cc/index.php?topic=43713.0) is an over-simplification and not very robust, but it presents in code the basic principle of threshold detection and the subtraction of adjacent pulse times (period).  BPM = 60.0 / period in seconds.

If you want something that would work under a larger range of conditions, you can add the three primary missing features used by medical instrumentation.

 1. Automated zeroing, which can be accomplished with an analog filter and pull-up or with a digital high pass filter that attenuates frequencies below 0.3 Hz.  This can be done with a series capacitor leading to the analog input being sampled, with a pull up resistor to V+ and another resistor to ground to center the Voltage to an appropriate positive steady state value.
 2. Attenuation of frequencies above those representing a pulse to avoid false triggers from high frequency noise, cross-talk, or transients, which can be accomplished with an analog filter or with a higher sample rate and a digital low pass filter that attenuates frequencies above 100 Hz 1.
 3. [Dynamic range compression](https://en.wikipedia.org/wiki/Dynamic_range_compression), which detects the trend in pulse amplitude and continuously adapts the trigger threshold accordingly to avoid false indication of beats or the missing of weaker but legitimate beats.

To do the filtering digitally, you may want to read up on DSP (digital signal processing).  There are several great books on it, and you can search for simple algorithms for both low pass filters and high pass filters in GitHub or elsewhere in the open source community.

---

[1] [Wikipedia's article on low pass filters](https://en.wikipedia.org/wiki/Low-pass_filter)


message:
How to calculate air velocity from wire resistance?

I want to construct a constant current hot wire anemometer. For this, resistance is the input of the Arduino. There is a relationship between wire resistance and air velocity.

How can I calculate velocity from wire resistance?

body:
Its very simple really, all you need to do is code the equations on this page and then supply some heat and you will be able to do it.  Just remember integer division rounds down :)

http://www-g.eng.cam.ac.uk/whittle/current-research/hph/hot-wire/hot-wire.html


message:
Endless loop on boot after reflashing ESP-12E with AT firmware

I flashed the ESP-12E from AT firmware 2.0 (running ok) to NodeMCU (running ok). When I reflashed it back to the AT 2.0 it is stuck in endless loop on boot:

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

    load 0x40100000, len 2408, room 16
    tail 8
    chksum 0xe5
    load 0x3ffe8000, len 776, room 0
    tail 8
    chksum 0x84
    load 0x3ffe8310, len 632, room 0
    tail 8
    chksum 0xd8
    csum 0xd8

    2nd boot version : 1.6
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size & Map: 8Mbit(512KB+512KB)
    no GPIO select!
    jump to run user1 @ 1000

    rf_cal[0] !=0x05,is 0xFF

I am sure I flashed it correctly, it was not my first flashing of AT firmware. Just to be sure:

    esp_init_data_default.bin -> 0x3fc000
    blank.bin -> 0x3fe000
    boot_v1.6.bin -> 0x0000
    user1.1024.new.2.bin -> 0x1000
    blank.bin -> 0x7e000

I can even reflash it to the NodeMCU firmware and it works, but reflashing to the AT firmware ends in the same endless loop again.

I suspect the problem is in initialization data, but I'm at my wit's end with it.

body:
Full answer and writeup to the comments:

The error message is due to the bootloader trying to read the contents of its radio-frontend calibration data (hence the name `rf_cal`). It compares it with a magic number, `0x05`, but fails because it reads `0xFF` at that point. `0xff` is an indication that you read data from flash which was erased. After erasing a flash-sector, the data in it becomes `0xff 0xff 0xff..`. Hence it seems as if the bootloader is trying to access the data from the wrong address, thus only reading erased flash data. The RF-calibration data is stored in the file `esp_init_data_default.bin` and must be flashed to the correct address in order for the bootloader to be able to read it.

The [NodeMCU documentation][1]  tells us the needed address for `esp_init_data_default.bin` given the size of the flash of our ESP module:

[![flash addresses][2]][2]

The bootloader messages

    2nd boot version : 1.6
    SPI Speed      : 40MHz
    SPI Mode       : QIO
    SPI Flash Size & Map: 8Mbit(512KB+512KB)

indicate that the flashed firmware (or that what is overriden by `esptool.py`) uses the 8 MBit flash size. There should be two ways to fix this:

 - Put `esp_init_data_default.bin` to the address the 8Mbit (1 MByte) bootloader expects, which is `0xfc000`
 - Force the usage of the 32 MBit (4 MByte) Flash map by giving `esptool.py` the parameter `--flash_size 32m`. This makes `esptool.py` overwrite a few bytes in the firmware (at `0x000000`) to adapt the firmware.

By your comments, method one worked. If there are problems however with the flash or the firmware, consider also trying method 2.

  [1]: https://nodemcu.readthedocs.io/en/master/en/flash/#sdk-init-data
  [2]: https://i.stack.imgur.com/g7clM.png


message:
PWM doesn't work with my sketch

I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The `Fading` sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.

The code that works:

    int ledPin = 3;    // LED connected to digital pin 9

    void setup() {
      // nothing happens in setup
    }

    void loop() {
      for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
        analogWrite(ledPin, fadeValue);
        delay(30);
      }
      for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
        analogWrite(ledPin, fadeValue);
        delay(30);
      }
    }

The code that doesn't work.

    #define FAN1 3
    #define FAN2 5

    void setup() {
      //EMPTY
    }

    void loop() {
      int speed1 = 25;
      int speed2 = 127;
      analogWrite(5, speed1);
      analogWrite(3, speed2);
      delay(10000);
    }

Why doesn't the second code work?

**EDIT 1:**

By not working I meant **No output** on *Second Code* and **Expected Output** on *First one*. Currently I'm using `ISIS` for simulation and `Oscilloscope` to view the output along with a `L239D` with motors attached.

In the first code the motor starts and stops as expected, with the expected PWM Waveform.

In second code, nothing. No waveform, no motor movement.

body:
One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()

    #efine FAN1 3
    #define FAN2 5

    void setup() {
     pinMode(FAN1, OUTPUT);
     pinMode(FAN2, OUTPUT);
    }

    void loop() {
      int speed1 = 127;
      int speed2 = 25;
      analogWrite(FAN1, speed1);
      analogWrite(FAN2, speed2);
      delay(10000);
    }

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.

Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.


message:
How To Read Serial Data With NodeMCU

I am trying to change leds status via serial port screen. Here is my code but it's not reading anything from serial port screen. I got leds on D1 and D2 pins.

    void setup() {
    pinMode(5,OUTPUT);
    pinMode(4,OUTPUT);
    Serial.begin(115200);

    }

    void loop() {
    // put your main code here, to run repeatedly:
    int point = Serial.read();
     if(point == 1)
    {
    digitalWrite(5,!5);
    }
    else if(point == 2)
    {
     digitalWrite(4,!4);
    }

    }

body:
Your code isn't doing what you expect because of a few issues.  As echo_salik says you are only ever turning off the output pins.  If you want to toggle the values then its probably easiest to store the value in a bool and use that to control the LED.

I think - and I may be wrong - that you are pressing the one and two keys and expecting that to work.  When you press the 1 key `Serial.read()` will return 49 and 2 will return 50.  These are the ASCII values for the keys you are pressing.

Its advisable to test to see if there is any data available to read on the serial port.  `read()` will return -1 if there is no data.

    void loop()
    {
      if (Serial.available())
      {
        int point = Serial.read();
        switch (point)
        {
          case 1:
            digitalWrite(5,HIGH); // Not !5 use High and Low
            break;
          case 2:
            digitalWrite(4,HIGH);
            break;
          case 3:
            digitalWrite(5,LOW); // Not !5 use High and Low
            break;
          case 4:
            digitalWrite(5,LOW); // Not !5 use High and Low
            break;
        }  // End of switch
      }  // End of if
      delay(50);  // I have no idea why, but most programs of this sort have a delay in.  (Hope someone explains to me too)
    }  // End of function

(A switch statement is a more efficient way of doing a number of if elses)

One thing you might want to consider is the values you are checking against.  `Serial.read()` is returning a value between -1 and 255.  It is not returning the key you pressed.  If you want to change it to work with keys then you can do it by changing the case statements that are checking integers `case 1:` to ones that are checking characters i.e. `case '1':`.


message:
ISR and multiplexing- time required to execute the code in Arduino

Below is an Arduino sketch for a basic animation, taken from the book *Beginning Arduino* by Michael McRoberts. Also, the connections have been shown. From what I have read elsewhere, this is the standard kind of code used to drive a LED dot matrix using the 595 shift registry, or the like (for example the MAX7219). Regarding the functioning of the code, I have two questions.

1. **For what percentage of the time will the LED stay lit?** In the `screenupdate()` there are no set delays. Hence, each row will stay lit only for the time it takes for the Arduino to execute the remaining loop and come back with the updated row values. How do we know for what time will the LEDs be lit, and hence predict their brightness, or for what can we do to set a particular value for this?

2. As I understand from the code, it works assuming that the ISR will fire as the code is running and will include all stages of the `led[]`. Although in this case it is not much significant, but how do we know that the ISR will fire including all the stages?If say we are updating each row of the matrix, to give a scroll effect, we would need the ISR to fire after each modification. How do we ensure this? If the ISR is too frequent, it may not let the code run. Or if it is too dispersed, the code may skip lines giving a jagged animation. Also, since the code would have some periodicity, is it not possible that some LED rows are always skipped? How do we determine the time of ISR firing perfect for the code or modify the code to ensure these do not happen(except trial and error)?

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

    #include <TimerOne.h>

    int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
    int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
    int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
    byte led[8]; // 8 element unsigned integer array to hold the sprite

    void setup() {
      // set the 3 digital pins to outputs
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      // Load the binary representation of the image into the array
      led[0] = B11111111;
      led[1] = B10000001;
      led[2] = B10111101;
      led[3] = B10100101;
      led[4] = B10100101;
      led[5] = B10111101;
      led[6] = B10000001;
      led[7] = B11111111;
      // set a timer of length 10000 microseconds (1/100th of a second)
      // and attach the screenUpdate function to the interrupt timer
      Timer1.initialize(10000);
      Timer1.attachInterrupt(screenUpdate);
    }

    // invert each row of the binary image and wait 1/4 second
    void loop() {
      for (int i = 0; i < 8; i++) {
        led[i] = ~led[i];
      }
      delay (250);
    }

    // Display the image
    void screenUpdate() {
      byte row = B10000000; // row 1
      for (byte k = 0; k < 8; k++) {
        shiftOut(dataPin, clockPin, LSBFIRST, led[k] ); // LED array
        shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row binary number (active low)
        // latch low to high to output data
        digitalWrite(latchPin, LOW);
        digitalWrite(latchPin, HIGH);
        // bitshift right
        row = row >> 1;
      }
      // Turn all rows off until next interrupt
      shiftOut(dataPin, clockPin, LSBFIRST, 0);
      shiftOut(dataPin, clockPin, LSBFIRST, ~0);
      // latch low to high to output data
      digitalWrite(latchPin, LOW);
      digitalWrite(latchPin, HIGH);
    }

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

***ADDENDUM***

In the above code, I tried putting `Serial.println(micros())` in the `screenUpdate()` loop, but I git a very confusing results in which the time displayed seemed to increase and then decrease randomly. **I did not understand why**. Has it got to do something with ISRs? Sorry for the apparently clumsy question.

I executed the following code (from the same book) out, which includes a MAX7219 driver (with the usual setup) and creates scrollable text. It worked perfectly well. And I just want to understand how this ISR and multiplexing go together, and how do we make sure the frequency is appropriate. More of an academic question rather than a practical one.

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

    #include <avr/pgmspace.h>
    #include <TimerOne.h>
    int DataPin = 2; // Pin 1 on MAX
    int LoadPin = 3; // Pin 12 on MAX
    int ClockPin = 4; // Pin 13 on MAX
    byte buffer[8];
    #define SCAN_LIMIT_REG 0x0B
    #define DECODE_MODE_REG 0x09
    #define SHUTDOWN_REG 0x0C
    #define INTENSITY_REG 0x0A
    static byte font[][8] PROGMEM = {
    // The printable ASCII characters only (32-126)
    }
    void clearDisplay() {
    for (byte x=0; x<8; x++) {
    buffer[x] = B00000000;
    }
    screenUpdate();
    }
    void initMAX7219() {
    pinMode(DataPin, OUTPUT);
    pinMode(LoadPin, OUTPUT);
    pinMode(ClockPin, OUTPUT);
    clearDisplay();
    writeData(SCAN_LIMIT_REG, B00000111); // scan limit set to 0:7
    writeData(DECODE_MODE_REG, B00000000); // decode mode off
    writeData(SHUTDOWN_REG, B00000001); // Set shutdown register to normal operation
    intensity(15); // Values 0 to 15 only (4 bit)
    }
    void intensity(int intensity) {
    writeData(INTENSITY_REG, intensity); //B0001010 is the Intensity Register
    }
    void writeData(byte msb, byte lsb) {
    digitalWrite(LoadPin, LOW); // set loadpin ready to receive data
    shiftOut(DataPin, ClockPin, MSBFIRST, (msb));
    shiftOut(DataPin, ClockPin, MSBFIRST, (lsb));
    digitalWrite(LoadPin, HIGH); // latch the data
    }
    void scroll(char myString[], int rate) {
    byte firstChrRow, secondChrRow;
    byte ledOutput;
    byte chrIndex = 0; // Initialise the string position index
    byte Char1, Char2;
    byte scrollBit = 0;
    byte strLength = 0;
    unsigned long time;
    unsigned long counter;
    while (myString[strLength]) { // Increment count till we reach the end of the string
    strLength++;}
    counter = millis();
    while (chrIndex < (strLength)) {
    time = millis();
    if (time > (counter + rate)) {
    Char1 = constrain(myString[chrIndex],32,126);
    Char2 = constrain(myString[chrIndex+1],32,126);
    for (byte y= 0; y<8; y++) {
    firstChrRow = pgm_read_byte(&font[Char1 - 32][y]);
    secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1
    ledOutput = (firstChrRow << scrollBit)
    | (secondChrRow >> (8 - scrollBit) );
    buffer[y] = ledOutput;
    }
    scrollBit++;
    if (scrollBit > 6) {
    scrollBit = 0;
    chrIndex++;
    }
    counter = millis();
    }
    }
    }
    void screenUpdate() {
    for (byte row = 0; row < 8; row++) {
    writeData(row+1, buffer[row]);
    }
    }
    void setup() {
    initMAX7219();
    Timer1.initialize(10000); // initialize timer1 and set interrupt period
    Timer1.attachInterrupt(screenUpdate);
    Serial.begin(9600);
    }
    void loop() {
    clearDisplay();
    scroll(" BEGINNING ARDUINO ", 45);
    scroll(" Chapter 7 - LED Displays ", 45);
    scroll(" HELLO WORLD!!! :) ", 45);
    }

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

body:
I think the code is likely wrong.

the code is called every 10ms, each time refreshing all columns and all rows and then immediately overwriting them all. so you should just see a quick flicker.

the typical way to approach this is to have a static variable to remember the row (or column) to be lit, and then load up the corresponding data for that row + columns when the display routine is called.

blanking isn't necessary for hc595.

edit: 1/21/2017.

now that I have a little bit more time, I would just add to the comments above.

we know the issues, as outlined above. here is a confirmation of it, in a simulation.

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

I ran your original code on an arduino uno. U2 is the shift register connected to the led matrix's rows (active low), and U3 to the columns (active high).

two things are obvious:
1. the code is invoked every 10ms;
2. the code for the most part resets the display: other than when the code is updating all rows / columns (the first half of the screenUpdate()), rows are high (inactive) and the columns are low (inactive), thanks to the display being reset by the bottom of the screenUpdate() routine.

the net result is that you for the most part don't see anything being displayed on the led, other than very fast flickers.

here is the solution: rewrite screenUpdate(), as below:

    // Display the image - alternate routine
    void screenUpdate2(void) {
        static unsigned char row = 0; // start with row 0
        //for (byte k = 0; k < 8; k++) {
            shiftOut(dataPin, clockPin, LSBFIRST, led[row] ); // LED array
            shiftOut(dataPin, clockPin, LSBFIRST, ~(1<<row)); // row binary number (active low)
            // latch low to high to output data
            digitalWrite(latchPin, LOW);
            digitalWrite(latchPin, HIGH);
            // bitshift right
            //row = row >> 1;
            row = (row==7)?0:(row+1);
        //}
        // Turn all rows off until next interrupt
        //shiftOut(dataPin, clockPin, LSBFIRST, 0);
        //shiftOut(dataPin, clockPin, LSBFIRST, ~0);
        // latch low to high to output data
        //digitalWrite(latchPin, LOW);
        //digitalWrite(latchPin, HIGH);
    }

the updated routine, screenUpdate2(), utilizes a static variable, row, to remember the current row to be displayed. it shifts out the column data, and sets up the row to be activated, and then strikes out the display to the led matrix. after that, it updates row for the next invokation.

here is how it works in the simulation:
[![enter image description here][2]][2]

hope it helps.

post-it: if the main loop has good execution time (short, and fairly deterministic), you can run screenUpdate2() in the loop and it will work as well. running it through an interrupt provides better consistency.

edit: 1/21/2017 v2

short after posting the above, a couple sharp eyed individuals noticed that the output data seems to be flipped (more noticeable at 320ms in the simulation posted above). good catch.

that's due to the following lines in the main loop:

    for (int i=0; i<8; i++) {
        led[i]= ~led[i];
    }
    delay (250);

I'm not sure what its purpose was in the original code - creating a blinking effect? - but if you comment out those lines, you will see that the execution would be as you would have expected:

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

  [1]: https://i.stack.imgur.com/QvCYr.png
  [2]: https://i.stack.imgur.com/sbta2.png
  [3]: https://i.stack.imgur.com/LHqku.png

you will find that the values match exactly what's in the led[] array.

you can think of led[] as a ram display buffer that stores information to be displayed. all your application code needs to do is to manipulate / update it in the main loop. the display routine, when called by the timer isr, will update that for you periodically, in a fully transparent and carefree manner.

I tend to utilize this approach with a lot of things. Thus having a hook to a timer to execute a piece of code is a valuable tool for a programmer to have.

edit: 1/21/2017 v3

I was asked how long screenUpdate() and screenUpdate() will run on an arduino (16MIPS): screenUpdate() takes about 2.1ms to run, and screenUpdate2() about 0.2ms. those numbers will determine the upper-end of the display update frequency.


body:
*(In a comment the asker mentioned they're not sure of the "usual approach", so I've provided this answer to hopefully help clarify)*

Here is my code for using a single 595 to drive the columns, and hooking up the rows to the Arduino pins themselves. Here I demonstrate a clear delay in each row update, as well as another delay before the image changes. I hope this helps clear up your confusion, and I apologize for not have a 2 595 setup handy (though I have 2 595s so if this doesn't help you, I'd be more than happy to set it up...), but it should be easy to adapt for a second 595. This supports a variable amount of width and height.

I also answered this assuming you just want the dotmatrix display functioning correctly, and I didn't focus on ISR. On first glance I see no delay in the row updating on the ISR version, or a delay when setting the latch pin and the whole thing seems pretty confusing. Honestly I think it might work in a perfect universe but I'm not sure (it wouldn't, as the other answer said, you'll probably just maybe observe a flicker and one row being lit). If this isn't an X Y problem and you really need ISR, I can answer that too, it just seems like we're getting into a lot of questions at once here...

<!-- language: c -->

    // Pin connected to ST_CP of 74HC595
    const int latchPin = 8;
    // Pin connected to SH_CP of 74HC595
    const int clockPin = 12;
    // Pin connected to DS of 74HC595
    const int dataPin = 11;
    // The pin of the first row of your display
    const int row1Pin = 2; // WARNING: All future rows are assumed to be row1Pin + n
    // The amount of rows your display has
    const int HEIGHT = 3;
    // The amount of columns your display has
    const int WIDTH = 2;
    // The reset pin of 74HC595 (not required as it isn't used, but this pin is pulled low)
    const int resetPin = 9;
    // Variable used to keep track of currently lit up row
    int currentRow = 0;
    // Array of rows
    int rows[] = {0b11,
                  0b01,
                  0b11};
    unsigned long lastChange = 0;

    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(resetPin, OUTPUT);
      digitalWrite(resetPin, LOW);
    }

    /* I don't think this works, but it might with a much higher delay.
    void reset() {
      pinMode(resetPin, INPUT);
      delayMicroseconds(1);
      pinMode(resetPin, OUTPUT);
      digitalWrite(resetPin, LOW);
    }
    */

    // enableRow changes the currently enabled row for future calls, it also changes
    // the pinMode on the previous row to "INPUT", disabling all lights on that row.
    void enableRow(int row) {
      if (currentRow != 0) {
        pinMode(currentRow, INPUT);
      }
      currentRow = row;
    }

    // This is a quick function to test one single LED or row on your dotmatrix display (I should have documented this one better but pass an incremeneting number to it and you'll see what it does...).
    void lightOne(int pos) {
      enableRow(row1Pin + int(pos / (WIDTH+1)));
      shiftOut(dataPin, clockPin, MSBFIRST, 1 + pos % (WIDTH+1));
    }

    // This function draws the display stored in "rows".
    void displayRows() {
      for (int i = 0; i < HEIGHT; i++) {
        digitalWrite(latchPin, LOW);
        enableRow(row1Pin+i);
        // shift out the bits:
        shiftOut(dataPin, clockPin, MSBFIRST, rows[HEIGHT-i-1]);
        digitalWrite(latchPin, HIGH);
        pinMode(currentRow, OUTPUT);   // set the current row's pin as OUTPUT
        digitalWrite(currentRow, LOW); // output LOW on currentRow to complete light's circuit and display
        delay(3); // time in ms to hold each row lit
      }
    }

    void loop() {
      displayRows();
      if (lastChange+1000 /* 1000ms between changes */ < millis()) {
        for (int i = 0; i < HEIGHT; i++) {
          rows[i] = random(4);
        }
        lastChange = millis();
      }
    }


message:
How can I concatenate multiple byte Arrays into one Array

I have three byte arrays. I first change their values during runtime and after that I want to combine them into one bigger 4th array.

    byte a1[] = { 0x01, 0x00, 0x01 };
    byte a2[] = { 0x00, 0x11, 0x01 };
    byte a3[] = { 0x11, 0x00, 0x01 };

    byte c1[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I first tried this, but it did not compile.

    c1 = a1 + a2 + a3;

I also tried `strcat()` and I did got a error.

body:
    byte *src;
    byte *tgt;
    tgt=c1;
    src=a1;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);
    src=a2;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);
    src=a3;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);


body:
You can do it like this

    byte c1[] = {0x01, 0x00, 0x01, 0x00, 0x11, 0x01,0x11, 0x00, 0x01 };
    byte *a1 = c1;
    byte *a2 = c1+3;
    byte *a3 = c1+6;

Note that This does not make a copy byt you can access the C1 and a1 a2 and a3 as you liked.


body:
You can concatenate with `memcpy`. You just need to set the pointer at the right place inside the `c1` array.

 memcpy(c1, a1, sizeof(a1));
 memcpy(c1+sizeof(a1), a2, sizeof(a2));
 memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));


message:
Problem to convert rotary encoder output to angle

I'm using [this][1] incremental rotary encoder with a rotating disc.

Here is my system:

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

I will explain the system briefly and above is the illustration for that:

The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle.
The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface.
There is also a fixed red arrow on the disc.

Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface.
This adjustment each time at the beginning will provide the reference point.

After this adjustment I want to output the actual angles via Arduino.

I tried the following example code from Arduino website:

    #define encoder0PinA  2
    #define encoder0PinB  4

    volatile unsigned int encoder0Pos = 0;

    void setup() {

      pinMode(encoder0PinA, INPUT);
      digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
      pinMode(encoder0PinB, INPUT);
      digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

      attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
      Serial.begin (9600);
      Serial.println("start");                // a personal quirk

    }

    void loop(){
    // do some stuff here - the joy of interrupts is that they take care of themselves
    }

    void doEncoder() {
      /* If pinA and pinB are both high or both low, it is spinning
       * forward. If they're different, it's going backward.
       *
       * For more information on speeding up this process, see
       * [Reference/PortManipulation], specifically the PIND register.
       */
      if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
        encoder0Pos++;
      } else {
        encoder0Pos--;
      }

      Serial.println (encoder0Pos, DEC);
    }

    /* See this expanded function to get a better understanding of the
     * meanings of the four possible (pinA, pinB) value pairs:
     */
    void doEncoder_Expanded(){
      if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
        if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                                 // encoder is turning
          encoder0Pos = encoder0Pos - 1;         // CCW
        }
        else {
          encoder0Pos = encoder0Pos + 1;         // CW
        }
      }
      else                                        // found a high-to-low on channel A
      {
        if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                                  // encoder is turning
          encoder0Pos = encoder0Pos + 1;          // CW
        }
        else {
          encoder0Pos = encoder0Pos - 1;          // CCW
        }

      }
      Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                                  // before final program run
      // you don't want serial slowing down your program if not needed
    }

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction.
It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW.
I want to translate this code such that I can output the angle in degrees.

My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.

Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

  [1]: http://au.rs-online.com/web/p/mechanical-rotary-encoders/6234300/
  [2]: https://i.stack.imgur.com/Z1VHk.png

body:
Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:

    if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
     encoder0Pos += 24;
    } else {
     encoder0Pos -= 24;
    }
    encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

 1. "The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
 2. You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
 3. You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.

This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.

    #include <Bounce2.h>

    #define encoder0PinA  2
    #define encoder0PinB  4
    #define STEP_SIZE 12

    byte encoder0Pos = 0;

    Bounce debouncerA = Bounce();
    Bounce debouncerB = Bounce();

    void setup()
    {
     debouncerA.attach(encoder0PinA, INPUT_PULLUP);
     debouncerA.interval(5); // interval in ms
     debouncerB.attach(encoder0PinB, INPUT_PULLUP);
     debouncerB.interval(5); // interval in ms

     Serial.begin (9600);
     Serial.println("start");                // a personal quirk

    }

    void loop()
    {
     // Read the status of the inputs
     debouncerA.update();
     debouncerB.update();

     int8_t EncVariation = 0;

     if (debouncerA.rose())
     { // if input A changed from low to high, it was CW if B is high too
      EncVariation = (debouncerB.read()) ? 1 : -1;
     }
     else if (debouncerA.fell())
     { // if input A changed from high to low, it was CW if B is low too
      EncVariation = (debouncerB.read()) ? -1 : 1;
     }
     else if (debouncerB.rose())
     { // if input B changed from low to high, it was CCW if A is high too
      EncVariation = (debouncerA.read()) ? -1 : 1;
     }
     else if (debouncerB.fell())
     { // if input B changed from high to low, it was CCW if B is low too
      EncVariation = (debouncerA.read()) ? 1 : -1;
     }

     if (EncVariation != 0)
     {
      encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

      Serial.println (encoder0Pos, DEC);
     }
    }

Disclaimer: I haven't tested this, but I'm pretty confident this will work.

I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See [here](https://github.com/thomasfredericks/Bounce2) for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)


body:
As noted in a comment, treating the numbers modulo 360° will put results into the range you want.

Note, however, that you can (and should) avoid use of `long` arithmetic by taking the pulse count modulo 30 *before* multiplying by 12°.

To compensate for the reference point adjustment, have the program set your tick count to correspond to 0° when the arrows align.  If you set the base count to some value that's a multiple of 30, say 120, and store it in an unsigned byte, the code would look like so:

    angle = 12*(count0);

Since the base count 120 is a multiple of 30, it falls out automatically when the modulus is taken.  To make this work in the long run, you would set the encoder count to 120 whenever the arrows align (or to `(current0)+120` if required to adjust it at other times).

If your base count were 0 instead of 120 and the count an unsigned integer instead of a byte, when the rotor goes CCW the modulus counts would have 15 extra counts.  For example, a count of 0 correctly converts to 0°, but a count of 65535 is 15 modulo 30, so converts to 180° instead of 348°.

Note, there is no need to debounce rotary encoder inputs if a proper state machine is used; and debouncing slows processing to the point that ticks will be lost.  See [my answer to question 32572](https://arduino.stackexchange.com/a/32582/3917) which includes code for reading several encoders active at once.


message:
How can I switch a 1.5V buzzer with my Arduino?

I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.

I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.

I did some reading on transistors and this is what I came up with:

I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

[![Circuit that I came up with.][1]][1]

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

body: You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.


message:
Analog output doesn't work for just 2 LEDs [Arduino Mega]

I am having a problem with an Arduino Mega 2560.

Everything works fine, the ultrasonic sensors work fine, and the other LEDs work fine. Although there is 2 LEDs who do not work right and when I do `analogWrite()`, they actually do `digitalWrite()`. I have tried to attach these two LEDs to a potentiometer (potentiometer works fine, values are tested) but it always does `digitalWrite()` not `analogWrite()`.

I have tested the LEDs and potentiometer on an Arduino Uno in PWM pins and analog pin and yes it does work very well.

Please mind that these LEDs are attached to analog pins. Why is this? Because I do not have anymore PWM pins available to use and so I have to use analog pins. No way I can rearrange this.

Here is part of the code (only part otherwise it's too long, most of my pins are taken):

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

    //Leds//

    int led = A4;
    int ledUV = A3;

    //Potentiometer//

    int potReading;
    int potPin = A2;
    int lightDim;

    void setup(){

     Serial.begin(9600);

     pinMode(led, OUTPUT);
     pinMode(ledUV, OUTPUT);

     pinMode(potPin, INPUT);

    }

    void loop(){

     potReading = analogRead(potPin);
     lightDim = (255./1023.)*potReading;

     analogWrite(led, lightDim);
    //  analogWrite(ledUV, lightDim);
    // Serial.println("pot: ");
    // Serial.println(potReading);
    // Serial.println(" ");
     Serial.println("dim: ");
     Serial.println(lightDim);
    // analogWrite(led, 255);
    // analogWrite(ledUV, 255);

    }

body:
Analog pins an only *read* analog values, not *write* them.

`analogWrite()` is a deceptive name. It should really be `PWMWrite()` since all it does is PWM. And that, of course, needs PWM pins.


body:
Reference: [`analogWrite()`][1]

The pins 2 - 13 and 44 - 46 are the PWM pins for `analogWrite()`.

That means you have 15 PWM pins. Did you use them all?

You could add a module with more PWM outputs. Search for: Arduino 16 channel PWM

The Arduino Mega does not have analog outputs, only digital PWM outputs.

  [1]: https://www.arduino.cc/en/Reference/analogWrite


message:
Flash an ESC Through Serial USB without Arduino Interrupting the Signal

So I have four Electronic Speed Controllers (ESC's), each connected to a motor. I am building a drone with an Arduino UNO board as my flight controller. For convenience, I have soldered the signal wires on each of the four ESC's onto the bottom of the Arduino where the Arduino's pin headers are soldered on. The serial ground pins on the ESC's are soldered to the ground pins on the Arduino.

The ESC's I am using can be found [here.][1]

In order to change settings on my ESC's, I am trying to use this [Turnigy USB linker][2] to connected to the BLHeli software on my computer.
The linker has a signal and a ground wire for Serial Communication, as well as a positive wire (I think this is just to fit the connector on ESC's with a BEC, but mine are OPTO, and have none). To connect the USB Linker to an ESC, I should be able to plug it into appropriate female pin headers on the Arduino using some breadboard-type jumper cables.

At least that's what I thought...

Whenever I try to connect to an ESC with the BLHeli software, I get a message:
*Please Connect ESC and power up or cycle power.*

Earlier, I was able to make the connection and change the settings on my ESC's when they weren't connected to the Arduino board, but now that they are soldered and hot-glued on there, they won't work. So the question is: **What is the Arduino doing to the Serial connection, and how can I fix it without desoldering my ESC's whenever I need to change some settings?**

Now before you ask:

 - Yes, the ESC is powered up and connected to a motor. It gives me a happy beeping sound.
 - Yes, I definitely have the signal and ground wires connected correctly. I have been trying to figure this out for days, and have even tried switching them.
 - The Arduino is turned off when I try to connect an ESC to the USB Linker.
 - Only one ESC is powered on at a time.

Maybe the Arduino has some kind of protection circuit for the IC that is messing up the signal, or maybe the ESC's have something similar that's messing it up too, because some of the ground wires are connected together. I'm going to have a very difficult time figuring this out myself, so hopefully someone out there has an idea of what's going on.

Thanks for any help you have to offer.

-- Ember

  [1]: https://hobbyking.com/en_us/multistar-mini-blheli-multi-30a-opto.html
  [2]: https://hobbyking.com/en_us/turnigy-multistar-usb-blheli-programmer-for-v2-multistar-esc.html

body:
I can offer general advice without reference to specific implementations.

By driving the Arduino pins when it is powered off you are potentially exceeding it's maximum rated specifications for voltage on any ping, and possibly for current into a pin, and you risk damaging it.
When the Arduino is powered down its Vdd pin and power supply rail will be at about 0.0 volts and will be loaded to ground by power supply capacitors and various other items connected to Vdd - including the OUTPUT of the Vdd voltage regulator in many cases.
Each Arduino pin is connected to the Vdd rail by a body / protection diode. To drive the pin high you must also raise Vdd to high-1 diode drop and must drive the Vdd rail load from your signal line via the body diode.
If your programmer has the ability to do this there is a reasonable chance that you may damage the body diode. For extra points, a very capable signal input MIGHT damage the Arduino's voltage regulator and possibly other on board devices - but I'd think that to be unlikely.

The technically best solution is to disconnect the Arduino's relevant pins when programming. As you obviously would rather not do that, then ...

**Probable solution:** If you power on the Arduino and run a program which ensures that the relevant pins are set to input mode then it should work as required. IF the Arduino default program sets the relevant pins to inputs then just powering it on should suffice, but odds are that the serial port pins are not both configured as inputs.
If the Arduino has a USB to serial port IC or other devices connected to the pins in question then you will need to also ensure that they do not load the pin excessively and that they will not be damaged by programming signals. eg if you were trying to drive the Arduinos serial RX_in pin which was connected to the TX_out pin of a USB-Serial IC then the programmer would be attempting to drive the USB-serial output pin and this must be dealt with in some way.

**Checklist:**

- Is there something else connected to this pin.

If so

- What state is it in during ESC programming

- Will it be damaged by programming

- Will it affect programming.

- What action is thus needed.


body:
As far as I can tell, it is not possible to program a Turnigy Multistar ESC while it is connected in parallel to any pins on an Arduino. Whether the Arduino is off, or the pins are set to input, output, HIGH, or LOW, the signal is disrupted somehow.

**Solution:** Don't do what I did and solder the ESC's to your Arduino unless you want to de-solder them to change settings. Sticking some wires into the Arduino's pin headers will not make a strong connection, so I would recommend *soldering some sort of strong JST connectors to the pins on the Arduino.*

Hope this all helped, and good luck,

-- Ember


message:
ESP8266 as WiFi monitor

I'm about to buy two ESP8266 modules. I want them to use as an auto deauth device. The first module will monitor my WiFi router's packet transmission. If a certain device receive loads of packets from my router (which hogs my network) the second module will deauth that device or flood "forged" packets. There will be a threshold so a simple web browsing will not trigger the deauth process from the second module. Btw. My router doesn't support traffic shaping & QoS. Only a different kind of QoS (DHCP & IPP/TOS) which is useless because my ISP doesn't support it.

body:
You're going to face significant challenges with this.

The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.

I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack.  The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).

So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.

Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.


message:
5V power supply negative terminal connection

I am currently developing some basic led board using Arduino Uno R3. Basically,
the LEDs are connected in parallel so that 5V DC supply can light up about 3 LED. Each LED has its resistor and its connected to 3 Arduino digital pin where I ground it by using digitalWrite(pins, LOW). Each ground on the schematic is the Arduino digitalWrite(LOW). My question is where should the negative of the 5V should be connected?

Also, if I wanted to measure the voltage of the LED, where should I connect my probe so that analogRead() can read the voltage?

Thanks and sorry if my explanation is not correct since it's my first time using this site.

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

<!-- End schematic -->

body:
The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general **ALL** connections should have a common "ground".

You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)

If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.