text:
Arduino time between interrupts in POV led display
I'm making a POV display (4 spokes) on a bike wheel using a Hall effect sensor to measure how long the last revolution took and based on that I calculate delays in the display. By pedalling at a constant rate I should get roughly a nice image but all I got is an unsynchronized mess. It seems like it is going and image is stable but after around half of a turn it scrambles.
I divided the wheel into 32 even parts which uses the same LED colour. Any advice how to achieve full synchronization. Any thoughts?
Here is my code:
#include "Adafruit_WS2801.h"
#include "SPI.h"
#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;
uint8_t LED1R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED2R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED3R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED4R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED5R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED6R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED7R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED8R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
uint8_t LED1B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED2B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED3B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED4B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED5B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED6B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED7B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
uint8_t LED8B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
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();
}

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, HIGH);
}

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() {
delta  = current - previous;
delta<<5;
delta-=6800; //time required for loop

  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();

  pointer1++;
  pointer1 &= 31;
  pointer3++;
  pointer3 &= 31;
  pointer2++;
  pointer2 &= 31;
  pointer4++;
  pointer4 &= 31;
  delayMicroseconds2(delta);

}

Pardon me, it was late in the night and I put wrong code. Of course delay should depend on delta. Changed to newest code with less job in delay. Still yields similar results.

dlyMic Should be defined as "volatile". Your delays don't take into account that all the code inside the loop takes some time to ru   Especially strip.show.

How much memory (RAM) does this sketch require?

@Gerben Nice found I think it is fixed now but still a bit still doesn't work properly.

@MikaelPatel Not much about 1024 bytes, 12% of megas dynamic memory and 2% od program memory.

To the "anonymous user" who continually attempts to make edits to this question. Please create an account on Arduino SE, so that we can see who is making the edits. If you are the OP, who posted the question on SE Electronics, please login to SE Arduino, using your SE Electronics ID (SE Arduino will simply be added to your existing account) - that way your edits will no longer keep on being rejected.

@Herioz - if you want to modify your question please do it as yourself (Herioz) and not as an anonymous user (ie. not logged in). That way the changes are recognized as yours and not someone else trying to change the sense of the question.

As noted in a comment, dlyMic should be declared as a volatile variable.  This is true of any variables where loop() gets a value changed by an interrupt service routine, or where it puts a value for the ISR to use.  In either case, if the variable is multibyte, you may wish to surround the get or put by code to turn interrupts off and on, to avoid race conditions where the ISR is reading or changing a value coincidentally with loop() changing or reading it.  For example:
byte statusReg = SREG; // Save interrupt status
cli();                 // Turn off interrupts
++somethingimportant;  // Need interrupts off for atomicity
SREG = statusReg;      // Restore old status

Aside from that, your treatment of dlyMic resembles a bad random number generator.  It consists of a declaration line; a couple of lines in the ISR; and use as a delay parameter in loop():
unsigned long dlyMic =123456;
...

  dlyMic<<5;
  dlyMic-=6500;
...
delayMicroseconds2(dlyMic);

The following two lines of Python compute the series of numbers that will result as values of dlyMic.
dlyMic=123456; mk = 2**32-1
for i in range(14): print dlyMic; dlyMic=(dlyMic*32-6500)&mk

They produce:
123456
3944092
126204444
4038535708
384117276
3701811740
2493852188
2493852188
2493852188
...

You may wish to connect up your dlyMic calculations with your measurement, delta.

The following code was from a rejected suggested edit, by an anonymous user, to the original post. See also Rejected edit results in loss of constructive code modification.
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);

}

There is another rejected edit here.


text:
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 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.
/*
 * 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
}

Is the pin hardcoded into the library then? I recently had the same problem with the USB Host library. It is annoying when you can't define the pin yourself, although the authours of the library probably have their reasons for doing so. The line to change, for the Uno, seems to be line 138 in boarddefs.h, but I'm trying to find where IR_USE_TIMER2 is defined...

Line 195 in boarddefs.h you could try changing the 3 to another pin. It might work. I'll compose an answer out of these two comments.

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 library itself.
I recently had the same problem with the USB Host library, see Change select pin of USB Host library. 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:
// 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
    #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. In that section the transmit pin, for a number of versions of the Arduino, is defined as TIMER_PWM_PIN on lines 189-197:
#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:
#   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.

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see lines 68-71:
// 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...

Note that I have not tried this, so I would be interested to hear if it works or not.

Thanks for your answer. I have two questions: How do I know when a pin is being used by something else? Will I be able to choose more than one pin to do a task? e.g at the moment only pin 3 sends IR signal however, I would like pin3, pin 5 and pin6 to send IR signals.

Your code will tell you if a pin is being used. W.R.T. the IRremote library, the documentation will tell you which pins it is using. 2) Looking at the library it seems that you can not, or at least not without further modification. Maybe you could activate another Timer, by uncommenting out another line, and then use the pin of that timer (as each timer, appears to use its own separate pin - from looking at that header file). I am not sure. If you really want to do that, then ask/post a separate (related) question, as it is significantly different from your original question.. :-)

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
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

The garbage is just that, it is noise sent and stored in the buffer before your application starts. You need to clear buffer, implement a delay or use a defined signal to identify the start of valid data. No amount of fiddling with encoding will change this.

oh... how would i clear the buffer? I can implement the identification thing, but still a clear buffer should be implemented just for, well, clean buffers. hehe @Milliways

@Milliways i should google before asking, but i though it wouldn't be that simple. Serial.flush()

C# Serial.DiscardOutBuffer() after opening the port in C# and before sending data.

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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.

Here are some good suggestions on this topic; https://groups.google.com/a/arduino.cc/forum/#!topic/developers/AEA8LniThTA

Just read from the serial port faster. Don't rely on the buffer for storing your data, read it from the buffer and store it yourself.

@Mikael, thank you for the link I am reading through them now.

@Majenko My issue isn't with the speed that I read the serial at but more so with how often I can perform the reads. I am working on code written by someone else so I have limitations on how often I can read the data on the serial. One work around I am looking into is actually reducing my baud rate so that I will read that data slower and thus have more attempts to read and clear the bytes from the rx buffer before it has a change to fill.

Maybe hook into yield() to pull data into your own buffer then?

good suggestion, I will have a look into that, again the code runs various threads that already each use yield() so it might be tricky but definitely worth a look. I am also working on trying to get the headers stripped from the response which is sent to me so that I do not need to process unwanted data. thanks again

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.


text:
Working on Binary code with arduino
i have a BGM113 bluetooth module that sends messages as binary form. I have to work on each bit separately. i am not sure about Serial.read() gets it as binary but when i am trying to see at on the serial port screen with Serial.println(Serial.read(), BIN) it shows me as string something like []...[]
What should i do ?

A byte is 8 bits. You can use "bit manipulation" to extract or set single bits. A very good tutorial here: (http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all)

There is a difference between binary form and base 2 (BIN) number conversion.

Serial.read() reads a byte (8 bits) so you should receive 8 bits at a time.  If there is some form of flow control then you might just get 1 bit.  It looks like you are not getting any bits so check your code is waiting until data is available.


text:
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)
  }
}

Do you mean you want pins 9 and 10 to BOTH be able to dim and switch on/off a light?  If so you just need to wrap you code in a function and take the pin number as a parameter.

Do you mean you want to use pin 10 as an input to control the PWM output, or do you want to use pin 10 as an output to control if the PWM signal gets to the light or not?

@Matt Yes, exactly. Ok, I will try.

@Majenko I want to make pin 10 as input pin which just ON/OFF pwm pin 9. Not controlling the PWM just control PWM pin. Means using pin 10 just ON/OFF PWM pin 9. Suppose, I pressed PIN 10 then it's ON PWM pin 9 and I can able to dim and vise verse of my light. And when I pressed PIN 10 again then it's OFF PWM pin 9 and then no operation performed.

@Hasan - The way I read it, your answer to me and to Majenko say two different things.  I still have no idea what you want, sorry.

Please explain what you want the three buttons to do. Also explain what the code is doing. What the code is not doing. Or what the code is doing wrong. Also, the first if statement inside the loop function seems very odd. It looks like you need to keep the button pressed for any of the other buttons or code to work at all.

@matt Ok, let me explain some things.

@Gerben Ok, understand your things. Let me clear the things.

I've give you an upvote for the comments.  In future enum may help you right even clearer code (rather than using ints to define states).  I'm still looking into the code.

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

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:

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.
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.)

Ok, Let me explain more. Let me update my question more clearly with brief description. I hope that's may be clear your all doubt.

Thanks for the edits, but again we can see what the code does. Please try to explain, clearly and without lots of unnecessary detail, what you want it to do - the behaviour you want. I think you should be able to explain it in 5 lines of text.

Ok, get your point. 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. I hope you understand.

I tried out your code. But it's not working as I want. Thank you again for your effort. I find out the solution. I will upload code and explanation.

Feel free to explain how it differs from what you want.


text:
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?

Interleave the music and game code. Do not delay when playing music or in the game code. Alternatively use threads.

Use a couple of Finite State Machines to play both the music an the game together.

I would set time to minimal note lenght and set PWM to play next tone/pause from music array inside the iterrupt. It would be so fast, that the game probabelly would not notice, it is interrupted on the background each beat time (few per sec) for just couple of cycles (1/16.000.000 sec each)

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.

Run the music through a time Interrupt.


text:
Error: Cannot find module 'serialport'. node.js, Arduino Yun
I carefully followed Andy Sigler's tutorial 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

Did you check that post "cannot find module 'serialport' using Node.js and Johnny-Five" ?

@J. Piquard I'm trying to use node.js in Arduino Yun. The post you mentioned is regarding installing node.js on a computer. It's not helpful..Thanks anyways.

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


text:
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()

I'm not very much into Yùns, but I think that the problem is that time.sleep(0.5) that you put. Try lowering it to e.g. 0.01 to perform a check every 10 milliseconds... If this doesn't work, maybe the problem is the overhead added; to limit this store on the arduino or the Yùn some data (e.g. 50 acquisitions) and then send them all at once.

I've changed the time.sleep(0.01) and I stored 50 acquisitions, but It's slow to get 1 sec of datas.

You'll have to figure out where the bottleneck is. The Arduino sending the data, the yun receiving the data and/or transmitting the data over UDP.

What do you mean by "slow"? How much is "slow" for you? And is it just delayed or you are losing packets?

You shouldn't be sleeping in the python code, you should be doing a blocking wait (or select) on the data, since it is merely proxying readings timed at the source.  Also without sequence numbers in your UDP traffic you can't know if samples have been dropped or misordered.  Just swapping components in the existing software/communication architecture won't meaningfully help, as you are far below the capability of your current ones, but getting rid of the bridge would clean things up substantially - perhaps consider if an ESP8266's ADC input is suitable?

Hi @JonathanAnctil, could you please clarify your question. Are you asking if the other Arduinos are suitable or are you asking us to tell you why your coms are slow?

Hi @se_leinad, I'm asking if other Arduinos are more suitable for what I am trying to do. But I also put the code because I'm not an Arduino expert (I know the base) and maybe I did something wrong. One problem that I'm almost sure about using the Mega + Yùn Shield, is that I need to use the Bridge and that seems pretty slow.

@ChrisStratton yes I read about ESP8266 but my knowledge stops there.

Well, read more.  That, or figuring out how to use an ADC directly on a Linux wifi module is your best bet on getting rid of the bridge.  But you also need to fix the conceptual problems in your design - data sources time things, data conduits shouldn't have program delays as that will only make timing problems worse.

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.

Don't use libraries for what one can do in just a few low level lines of code.
Don't place numbers in strings. Keep them as numbers.
Send the numbers as messages placed carefully into byte arrays using bitwise operations.
Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
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.

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 ofmillis() 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.

The original suggestions here are highly mistaken and would be best ignored - following would just trade the problems of one set of fundamental misunderstandings for those of another, equally mistaken set.

You are right. However, code can be improved. It can be very informative to make changes to the code and see the result for the cpu load. The 50Hz is too much for an Arduino Yún Bridge anyway.

This is where you are fundamentally wrong - the issue is not CPU load at all, and 50 Hz is not too much if done right.  The issue is with the implementation not taking the bridge into account.  Getting rid of the bridge would make things simpler, but it can be done through the bridge by someone who understands communication between systems.  What your proposal does is trade the asker's mistakes for your own, different set of mistakes, which put them no closer to a solution.

Thank you for correcting me. I learned something and I have added it to my answer after "ADDED".
I hope you still agree with the 30Mbyte ram in /tmp and the unnecessary use of the timer, interrrupt and String object.

Hi @Jot, could you provide me the code you did to test it? What did you do different from my implementation?

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.

@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 = ---

Great demonstration, thanks a lot. This confirm a lot what I saw about the Bridge!


text:
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.

millis wrap around isn't a problem as long as you only use time difference. So timediff = endtime - starttime.

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:

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


text:
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?

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

Does problem still occur if you substitute a fixed voltage (eg use a voltage divider or pot) for the PWM'd contrast input?  The PWM's sharp-cornered waveform might be introducing a lot of noise into the LCD.  If fixed voltage fixes the problem, and you still want to use PWM, put a good low-pass filter between PWM and LCD pin 3 or whatever

that was it.  i had originally tried to use the pot, but couldn't get it to work (no clue why, hence using the PWM).  just changed back to pot, and it's all beautiful now.  thank you so much for the help!!!!

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


text:
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?

I think you might be better looking at 'generic' C or C++ libraries for stats and then porting them to an Arduino.  Not sure how complete the Maths lib is on Arduinso though

Seems like you only need to calculate the BMP, or beat per minute. Measure the time between e.g. 5 beats. Then divide 300000 (5601000) by this time in milliseconds. You use the average of 5 beats to get a more stable number.

This Arduino topic 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.

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

Great answer! I would add that the first thing to do is to get a few sample waveforms from the same hardware setup in order to test the algorithms and choose the parameters (e.g. cutoff frequencies) on the computer, before porting to the Arduino.


text:
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?

This is a very interesting question, but I am not sure how Arduino related this is, apart for you are using an Arduino. I think that you would get a better  response by asking a separate, non-Arduino related question on SE Physics first, to get an equation to use. Once you have that, then, maybe, come back here to ask how to put that equation/formula into an Arduino sketch.

Do you already have an equation? If so, edit your question to include it. What research have you done so far? What code do you already have? What is not working, exactly?

OK You have a theory, test it.  Its not going to take much to hook a wire up to an analog port and measure the changes in resistance.  You are probably only going to get minute changes so you will need to alter the other parameters to cater for it, and its possible that they might be outside the limits of what an Arduino can handle.

I think that, for this to work, you also need to measure the ambient temperature. You also need the temperature to resistance curve of the wire you are using.

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


text:
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.

rf_cal is radio-frontend calibration data. The bootloader sees that this is erased flash data (after erasing a flash sector, the data in it becomes  0xff 0xff 0xff ...). Can you do a esptool.py erase_flash and reflash? It may be that you're flashing esp_init_data_default.bin to the wrong address thus only reading erased flash contents. The 8 mbit (1 MByte) message seems like it's not using your flash fully. This value is set by esptool.py during flashing (--flash_size). What exactly is your flash command? Can you flash default data to 0xfc000?

Maximilian, thanks for you reply. I did erasing of the flash in past. I made some new tests, read the whole 4M flash and compared it with one in a functional module and finally got it working. The critical is your last sentence.
The solution: I had to flash esp_init_data_default.bin to the address 0xfc000. I found nothing about it in the documentation but this is the way I got the ESP12 to work again.
Thanks!

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  tells us the needed address for esp_init_data_default.bin given the size of the flash of our ESP module:

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.

authors: Роман Кушнір


text:
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.

Could you clarify what you mean by "doesn't work", please? What does happen, and how are you determining this?

@MarkSmith edited the question. Thanks for pointing out the lacking.

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.

Yeah. I meant to use it but didn't to check it out if it was to blame. I was just checking. Let me post a result of this change, btw the code that does work also doesn't set the pins as outputs.

just checked it. still the same.

I think there is something wrong with the Arduino Library of ISIS. I just got back my arduino back from a friend an it works.

You don't need pinMode with analogWrite. Check the first couple of lines of the source for analogWrite to see why. It takes care of pinMode itself.


text:
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);
}

}

!4 means 0 and so does !5

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':.

authors: ميثم الشهابي


text:
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.

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?
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)?

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

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.
#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);
}

You also might want to add some transitors, instead of resistors for the row. Otherwise, the more leds are lid in a single row, the dimmer they appear.

@Gerben, I always hear this advice but I put together a dotmatrix display and yanked out all the LEDs but one for a row and found them to be the same brightness. What I'd suggest is use one resistor per column, and use one transistor per row, which should ensure the LEDs get even power but my multimeter isn't in yet so I'm not sure (I know my LEDs aren't variable brightness though). This actually makes sense when you remember the lights are actually in a parallel circuit, they shouldn't change brightness when you have less lights.

This setup also ensures (because the display isn't all lit at once) that one transistor is active for a row of LEDs, and each LED would still have one resistor limiting current. (I should note I also haven't tested powering an entire row of LEDs on an 8x8 dotmatrix display from just one pin without a transistor as I was afraid of drawing more than 40mA).

@redstarcoder you're suggesting the same thing I was trying (and maybe failing) to say.

@Gerben oh probably! I read your suggestion as saying to not use any resistors are all, which alarmed me :).

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.

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:

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:

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.

Sorry, but being a beginner, I am not aware if the usual approach. Can you expand a bit? And also, I want to know whenever an ISR is set, how to determine the firing frequency.

I checked another one, with the MAX7219 based on the same principles (added in the question), which worked perfectly well. I actually do not want to know another way to do multiplexing, but rather understanding the general principles of IRS and the time taken for execution.

Okay, so a slight confirmation. The small flickers that were visible in the original code, that were the time it took the loop of the screenUpdate() function to complete one round, right?

Also, what software/instrument is the one you used for analysis?

(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...
// 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();
  }
}