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:
GSM 900A modem not responding to AT commands
I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:
/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}

I am getting this output on Serial Monitor for 9600 baud rate:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Resetting modem...Modem is functioning properly

The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield

Thats for GSM Shield by arduino but I am working with SIM900A

Yes, but the library is using pins 2 and 3.

But still its not working

Mikael Patel pls help on this issue

Check the power supply. Measure the voltage when the modem is connected. Does the voltage drop?

If you connect a GSM modem to the Arduino's Hardware Serial pins (1/0) then you cannot also use those pins to communicate with a host PC.
Your question is tagged "Arduino Uno" therefore the status reporting messages to the PC will be sent over these pins, and become hopellesly confused with the traffic to the GSM modem.
You must place the modem on pins distinct from the PC interface - either using a software serial interface on different pins of an Uno, using a Leonardo-type board where the PC interface does not involve the hardware UART pins, or by using a board with multiple hardware UARTs.

This answer may be totally misleading because I can't find a "GSM 900A" but I can find lots of "SIM900A GSM" results.  One thing I did notice is they require a 1A+ supply to cater for transmissions so I think running of an Arduino may mean you are not giving it enough power, you should use a 1.5A supply and make sure the grounds are connected.

source: Stack Exchange

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

sort: votes


text:
Arduino as a real device to computer
Suppose we have a computer mouse , now when we connect it to a computer then  computer understands it is a mouse which is been connected to it. Same thing happens for keyboard and many other devices. As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.
Let me to talk about one of my projects where I build a device driver for my own device. Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.
As we all know that the arduino library provides support for Mouse and keyboard which works fine. Mouse operations are performed without a custom driver.
Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.
I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.
Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.
Or if I think of building my own library then how I should start?
One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?
I know it is a out of the box question but still if you help me, I will be grateful to you.

Try Google - look for something like Arduino zero HID - I know I have seen people do such things.  (HID is Human Input Device)

Yes, I know there are several headers including HID for usb interfacing in library but without proper documents difficult to understand. But still I will give a try. If you have any useful links regarding this please mention those in comment

https://www.google.com/search?q=arduino+zero+hid

As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.

No, the mouse's microcontroller is a USB device.

Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.

No, that is the application you are talking about. The driver is what you install in Windows to make COM3 appear (that is, in any version of Windows before windows 10. Every other operating system, and Windows 10, has the driver built in already).

Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.

There is no support for that in the Arduino API.

I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.

Even with proper documentation and understanding of how USB works it's hard to understand.

Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.
Or if I think of building my own library then how I should start?

Don't. Trying to do what you want without an in-depth understanding of how USB works is nigh on impossible.  I understand how USB works and struggle with writing USB driver code for microcontrollers.
Instead invest in a device that already does what you want (such as a Teensy 3.x), or move away from Arduino and use a professional environment with professional tools and examples to work with.

One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?

From the USB Implementer's Forum Inc.

http://www.usb.org/developers/docs/devclass_docs/

Mouse or pendrive have a special type of microcontroller which are capable of direct communication to pc ? if so then is their any programmable microcontroller in market?

Yes, and there are plenty. Any of the Arduino boards based around the ATMega32U4 (such as the Leonardo) are that kind of microcontroller. The "serial" interface chip on the Uno is that kind of microcontroller (it is capable of being reprogrammed so it looks like a completely different device, and if you google around you will find people that have done it).

What is the difference between actual driver and my java program which reads COM port?

The driver is what makes the COM port. Your program is what uses the COM port.
[USB device]---->[USB)- Driver -(COM3]<-----[Your program]

Thank you for your valuable advice. Couple of more thing to clarify...

Mouse or pendrive have a special type of microcontroller which are capable of direct communication to pc ? if so then is their any programmable microcontroller in market? 2) What is the difference between actual driver and my java program which reads COM port?

See my edits...

you talked about teensy. just guide me whether I am going in right the direction or not. In teensy there is one method namely USB: Raw HID, now if I know how mouse does request and respond and code the teensy as per the mouse communication protocol then I am done

Raw HID is the basis of the mouse protocol. Over that is laid a "HID Report" that describes the data. The same thing is done for both keyboard and joystick as well. Teensyduino (the Teensy 3.x API) has Mouse, Keyboard, Joystick, etc objects to use: https://www.pjrc.com/teensy/td_mouse.html

On top of Raw HID teensy library provide different device support. can you suggest me a web site where I can find communication protocols of different devices. Actually my intention is to design a device which apply brute-force attack for fingerprint devices. Like what we do with keyboard. Computer understand it is a keyboard and the device generates and send different keystrokes.

I linked it in my answer already.

Let us continue this discussion in chat.

There's always someone who doesn't like answers to questions like "I want to do X incredibly complex thing and I have absolutely no knowledge of understanding of what it is or how it works" that consist mainly of "Don't waste your time, use something more suitable that already does it". I do wish they wouldn't downvote because of that. It really gets my goat (and I have a lot of goat to get...). To whoever downvoted: if you think USB is a simple enough system to just "hack in" some extra functionality without knowing what USB really is (I mean, the OP didn't even know what a driver was) ...

... then by all means go ahead and show us how it's done. Don't just go around downvoting answers because you don't agree with the fact that they say not to do something. I have spent years studying USB and still know next to nothing about it. By now I know enough to debug the protocol and trace what is happening, craft descriptors, HID reports, choose endpoint types, etc. Writing the state machines to handle it at the low level required is another matter. It's a nightmare. I am an "expert". This kind of thing is not something a beginner can possibly even begin to ...

... contemplate attempting. Especially when there are already Arduino-compatible devices that already do what the OP wants.

sorry but i didn't get your point

@SiddharthaSadhukhan It's not aimed at you - it's aimed at the n00b that downvoted a perfectly reasonable answer.

I appreciate your help and like to thank you for that. And I am asking you to send me some other useful links regarding this if you have such.

You could start here: http://www.usbmadesimple.co.uk/index.html

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


text:
OOP vs procedural programming on arduino
It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?

Please note that "functional programming" is not what you think it is, I guess you wanted to say "procedural programming".

Functional programming usually involves the use of closures, in languages that support them. C++ doesn't, and you would probably use functors instead.

Check out this article. It explains the neglegable performance effect of using classes.

Your assumption is quite wrong:

The majority of libraries use OOP.
The majority of in-built device drivers use OOP.
The core is filled with many OOP helper objects and classes.
99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

There is no point
The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time.  In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.
The moment you do Serial.begin(9600); you are using OOP.

Is there more than one Serial object? If not, what's the difference between Serial.begin and (hypothetically) Serial_begin?

On some boards yes there are multiple Serial objects.

If OOP is using C++ classes for implementation then this answer is fine. A more detailed answer may be found by first reading Peter Wegner's paper; http://www.cse.msu.edu/~stire/cse891/wegner.pdf. Arduino would be OOP if interfaces/classes would be more encapsulated, reused and extended.

You mean like Cosa? ;)

Hard to miss :)


text:
Do (cheap) SD modules support file I/O?
I noticed there are cheap SD modules and complete SD shields.
I assume the last are used for a 'final' product and not for bread-boarding (?)
However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition  to SPI interface)?
E.g. can I use the file I/O and the SD library with the This SD module?

i don't know weather any shields does not support file IO.

@PrashanthBenny and would the SD module I mention support file I/O with the sd library?

this module supports SPI interface, it is likely to work with the arduino SD library.

I have not seen one not work myself!

Thanks (going to try it ... after I do some basic experiments getting the Arduino today).

I have never managed to get an SD card reader to work, and yes I have tried one that looks like it might be that one.

There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.
The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.
What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).
The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.
So to answer your question

If you use a module and shield that use the same IC (chip) to access
the SD card and the same library then they will almost always behave
the same.
If you use two different shield (different ICs) which
need different libraries then they MIGHT have different
functionality.
If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)
If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.
==== Edit ===
When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.
When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.
Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.
There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.
So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call WriteFile().  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that WriteFile() is actually storing it on the hard disk of a PC somewhere in the world?
Your call to WriteFile() is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling read() and write() but it isn't.

Thanks for this detailed answer (although I have to find some more info about what are all consequences ... like you talk about a 'controller' but on a SD module, does it contain the controller already ?
For example, can I use the SD library (and thus file I/O) with the module I mention above (in my updated question)?

Sorry - By 'Controller' I mean the Arduino.  The SD Module/Shield needs to be controlled by an Arduino (or similar).  It will have an IC (silicon chip) on the SD module that accesses the hardware but this provides the lowest level of commands, much lower than you want to worry about.

Thanks again ... yes of course I should have known (that the Controller is the Arduino). Just getting into it (getting my first Arduino tomorrow).

Short answer. Yes, it will work.
I have used the same MicroSD Card Adapter module [it is marked MOSO instead of MISO on one of the pins] for a few projects.  I found no problems or special considerations doing so [except for getting the pin mapping correct].
In contrast, I've used one shield that worked sporadically, because of intermittent header contact.  It would work for a while, then stop until I "massaged" it properly.  It was probably just a bad assembly, though.
Many people prefer working with shields, while I do not, and would rather build on PCB board once I have a working version of my project.  It's cheaper as well.


text:
SIM800L change default baud rate
I am using an ATmega328P with internal clock (8 MHz) with a SIM800L module. The default baud rate of the SIM800L is 115,200 baud and I can't make them talk to each other correctly. Although I was able to make them talk very easily at a baud rate of 9600 baud. But now, with a new SIM800L I can't.
Question:
How to change the default baud rate of a SIM800L?
Is it possible to run an ATmega328P at a baud rate of 115,200 baud?
Thanks in advance!
EDIT:
I know that I can run atmega328p at baud rate of 115200 with different crystal, but is it possible to it using internal crystal.

Default baud rate of SIM800L is 0 (auto-bauding). Maybe you have saved it before.

According to Adafruit's pdf specsheet SIM800+Series_Serial+Port_Application+Note_V1.01.pdf, the SIM800 is set up to auto-baud when it starts out:

SIM800 series is designed in autobauding mode by default. Autobauding allows SIM800 series to automatically detect the baud rate of the host device. In application, host device must to synchronize the baud rate with SIM800 series. Host device must firstly send characters "AT" or "at" to synchronize the baud rate. It is recommended to send "AT" until host device receives the "OK" response, which means host device and SIM800 series are correctly synchronized. Once the baud rate is synchronized, it is suggested to use AT command "AT+IPR" to set SIM800 series baud rate according the host baud rate. ...

So, you might arrange your software to keep trying at 9600 bps.  If you get an ok connection at that rate, you can either keep using it or shift to a higher frequency via "AT+IPR".  [I haven't read the spec sheet enough to know whether that default autobauding is always on, or might be turned off somehow.]
As serial-data bps goes up, required clock accuracy becomes tighter.  Where a couple of percent error may be ok at 9600 bps, under a percent probably is needed at 115200 bps.
On several boards I've measured RC oscillator frequency errors of about 2%, which according to question How critical are UART frequencies? might or might not be good enough to allow high-speed serial communications.
If you can measure your ATmega328P's RC oscillator frequency, you can then apply a correction factor at startup.  In the spec sheet (eg Atmel-8271J-AVR-ATmega-Datasheet_11/2015), see §9.12.1, OSCCAL – Oscillator Calibration Register.
Your program can start out with the RC oscillator using the factory-set value, and then can load your own calibration value into the Oscillator Calibration Register to shift RC frequency as needed to make the board work ok for 115200 bps serial data.  Or, you can overwrite (in EEPROM fuse or signature area) the factory-set value with your own number.
Figure 32-37, ATmega48PA: Calibrated 8MHz RC Oscillator Frequency vs. OSCCAL Value, shows typical frequencies for various Oscillator Calibration Register values.  It is possible to tune clock frequency close enough that serial communications should work ok.
High-range byte values 144 through 160 typically move frequency from around 7.4 MHz to 8 MHz (at 85℃).  In this range, each count shifts clock frequency by about 0.5%.  See the figure for details.  For example, if value 158 gives an RC frequency of about 7820 KHz, then value 159 might raise the RC frequency to about 7860 KHz.
Low-range entries 96 through 112 move frequency from around 7.5 MHz to 8.5 MHz.  This overlap makes it necessary to try both low-range and high-range values when looking for the best Calibration Register value.
Note, there are inexpensive cymometers (frequency counters) on ebay, which can measure oscillator frequencies accurately enough to enable the calibration suggested above.

Well I do not think that the default baud rate is 115200. The default setting is autobaud which does not support 115200 baudrate. From the datasheet.

You can change it with the already mentioned AT+IPR command. From the AT manual you can also check that the default setting is autobaud, and also the selectable baud rates.

Note:  User  can  use  AT  command  “AT+IPR=x”  to  set  a  fixed  baud  rate  and  the  setting  will  be  saved  to  non-volatile  flash  memory  automatically.

If you use 57600 you will probably alright and you do not even have to change the baud rate settings as this value is supported.

You have mentioned an important rule about auto-bauding (Auto-bauding limited rates). Thanks man

As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.
You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(115200);      // Set your buad rate
}

And you can also do without this library.
void setup()
{
  Serial.begin(115200);        // Set your baud rate
}

Sorry but not true, you can change the SIM800's baud rate with the appropriate AT command, AT+IPR (as already mentioned in an other answer).

@BenceKaulics Thank you for this information.

You can change the baud rate to 9600 on the SIM800L with the command:
AT+IPR=9600

Then to save this (to last between boot cycles), give the command:
AT&W

To see the saved settings, give the following command:
AT&V

From what I have read so far, the problem is that there is no good divisor from an 8 MHz oscillator to get a within-spec baud rate above 57,600. Using the internal oscillator is also susceptible to variation with temperature, so that appears to be bad solution as well in many applications. The problem being that it may work on one MPU, but not with the next one.
As far as I can tell, the best solution is to use a 7.372800 MHz oscillator. This results in the processor running a bit slower, but it also results in the baud rate divisors being spot-on for almost all the standard and popular baud rates, meaning you should be able to run to at least 921,000 baud.
If anyone has a better solution, I would love to hear it, as I am dealing with a similar issue in something I intend to take into production that will be in a variety of environments.

authors: Антон Войлоков

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


text:
NodeMCU espcomm_sync failed
I have a NodeMCU ESP12E DevKit V2 from Geekcreit. I had it working some months ago, but now I cannot upload to it. I am using the arduino IDE and I've set the "Additional Boards Manager URLs" to:

http://arduino.esp8266.com/stable/package_esp8266com_index.json

The error I get:

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

What I've tried so far:

Applying 3.3v to the VIN
Uploading from 3 different PCs and one Ubuntu
Uploading using Arduino IDEs: 1.6.18, 1.6.2, 1.6.9, 1.6.11
Using the esptool.exe to upload to it from the cmd prompt.
Using following board configurations from the Arduino IDE:

"NodeMCU 1.0 (ESP-12E Module)"
"NodeMCU 0.9 (ESP-12 Module)"
"Generic ESP8266 Module"
"NodeMCU 1.0 (ESP-12E Module)"

Uploading with different upload speeds.
Uploading with different flash sizes.
Uploading with different USB cables.
Tried erasing flash, read flash.

All of the above has still resulted in the error stated in the top of this post.
Verbose output from upload:
Arduino: 1.6.11 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Build options changed, rebuilding all

Sketch uses 222,213 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,588 bytes (38%) of dynamic memory, leaving 50,332 bytes for local variables. Maximum is 81,920 bytes.

C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM1 -ca 0x00000 -cf C:\Users\xxx\AppData\Local\Temp\build48b2fca13fb12d7c15d8dce627beccb2.tmp/Blink.ino.bin
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM1
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
An error occurred while uploading the sketch
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

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

https://pastebin.com/GCq6aZsR
I was beginning to suspect that my NodeMCU board is broken somehow, but the old file is still uploaded on the device is active on my network, so if it is broken, it might just be the usb port.
EDIT: Just received a new module that gives the same error, so it is not due to faulty hardware.
However, I have found people facing the same issues when googling, but no real solution has worked for me, and the above list of what I've tried is mostly suggestions found in this process.
I'm running low on ideas and I am thinking to order a new NodeMCU board to try and rule out flawed hardware.
Any suggestions or help will be much appreciated. Thank you.

Did you double tab the reset button to force it into bootloader mode? Then try the upload.

Thank you for your suggestion. I just tried this, but still no luck.

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
iam getting this errors while uploading a blink program to esp8266 pls help me

sidagam sankar, please try the different solutions listed below.

You can try, turn off esp modul board and turn on and start flashing again

Returning to this, the issue still persisting, I tried once more with the
flashing software.
After flashing the NodeMCU I was once again able to upload to my NodeMCU from the Arduino IDE.
So no hardware flaws and no need for new drivers.

Try these steps:
1. Use a different USB port.
2. Go to Device Manage and check if the driver is installed. If already installed, uninstall it and then install it from Device Manager(worked for me, was having the same issue).
3. Nodemcu could be corrupt (faced same error and got it changed).

Same issue here. For me it was a hardware issue. The esp chip had solder that did not flow from the pads of the board to the esp board. To confirm this, before programming press down on the wifi module and keep pressed during programming. If it is a solder issue, it should program just fine. If it programs, you need to reflow all solder joints around the esp chip. Hope it helps.

After a lot of trial'n'error, this was the solution for me. Very frustrating!

Maybe there's something wrong with your driver.
Check which module of USB-to-UART of your NodeMCU is using.As far as I know, there're two most common modules:CH340 and CP2102.
Just download the driver (driver for CH340and driver for CP2102) and try again:)

Thank you for four answer.
Both my PCs says the CH340 is already installed and the other one installed with no further notice. However it still says the same.

i had a same problem . then as above said i uninstalled the what i installed drivers early . and reinstalled the drivers . and baude rate is 115200 .and uploaded the file. thank you sampath from srilanka

Please verify which you have before downloading random drivers.  The CH340 is rectangular, which the CP2012 is square.

Thank you for the advice. I did heed your warning and started downloading the CH340 driver from random places, which lead to a lot of malware and ultimately i had to format my laptop.


text:
How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor
I would like to make an alarm system using ultrasonic sensor.
My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.
But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.
I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.
int echoPin = 10; // pin 10 for the echo

int trigPin = 9; // pin 9 for trigger
int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
#include <NewPing.h> // Library for improved ultrasonic sensor readings

#include <SoftwareSerial.h>

NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

int ledpin=7;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 250;           // interval at which to blink (milliseconds

void setup() {
    pinMode(ledpin,OUTPUT);
    Serial.begin(9600); //sets up serial monitor
}

void loop() {

    delay(50);

    Serial.print("Ping: ");
    Serial.print(sonar.ping_cm());
    Serial.println("cm");

    //warning
    Serial.println("cm");

    //warning
    if(sonar.ping_cm()>=30)
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledpin, ledState);
      }

    }
}

You are initiating the NewPing library with NewPing sonar(trigPin, echoPin,30);. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says

sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from
if(sonar.ping_cm()>=30)

to
if(sonar.ping_cm()==0)

I follow your suggestion its working but when placing the hand near about 10 cm led some time blinking and some time not although when placing the hand more than 10 cm its blinking.But I want when object is 0 to 29 cm away led should not blink and when object is 30+ cm away led should blink and once led start to blink it continue to blink even when object comes near of it.

Can you confirm, that the distance is read correctly from the sensor (e.g. using the serial monitor)?

yes the distance is correctly showing.

I'm not sure, if that is the error, but on the site it also says "Ping sensors consistently and reliably at up to 30 times per second. " You use two consecutive calls to the ´ping_cm()´ function, which follow up on each other very quickly. Try to use it only once and save it in the cm variable.

Led is blinking but when an object is away more than 10 cm from the ultrasonic sensor led is blinking fast and hence when object come closer led is blinking slowly and even some time did not blink.But I want when object is 0 to 29 cm away led should not blink and when object is 30+ cm away led should blink and once led start to blink it continue to blink even when object comes near of it.

Mhh, I don't see any possibility in your code, that the blinking frequency of the LED may change. For that I'm out of ideas. When you want the LED to stay blinking, whatever happens, you can set a boolean variable, that makes your if-statement always true (you can combine it the with ping value check trough the || (boolean or))


text:
How can an Arduino do multiple actions in parallel without interfering with each other?
I am working with my son (9) and we are having a great time learning. But, we've run into a problem and could use your help.
We have two separate loops that we want to run without interfering with the other. Currently we have two LEDs that are blinking in a sequence that has delays built in to keep them on/off.
We also have a Photocell circuit that turns another LED on/off depending on the light.
The problem is, the photocell circuit is lagging 1/2 second due to the light sequence from the other loop.
How do we fix this?
// this is declans photo cell and led program

const int photoCell    =  0;  // photo cell variable
const int ledLightButt = 11;  // Led light variable assignment

int lightCal;                 // idk what dis iz
int lightVal;                 // this is the reading from photo cell I think

void setup() {
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);

    pinMode(ledLightButt, OUTPUT);
    lightCal = analogRead(photoCell);
}

void loop() {

    lightVal = analogRead(photoCell);

    if (lightVal < lightCal - 50) {
        digitalWrite(ledLightButt, HIGH);
    }
    else {
        digitalWrite(ledLightButt, LOW);
    }

    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    delay(250);

    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
    delay(250);

}

this may help ... https://www.norwegiancreations.com/2017/09/arduino-tutorial-using-millis-instead-of-delay/

tip: format your code properly so that the blocks of code are clearly defined .... i formatted your existing code as an example .... proper formatting is important in if-else bloks and in function blocks

The root of this behavior is that when the program runs delay() function - nothing else could run (digitalwrites, checks, conditions, etc.) until the delay() time is passed.
The effective solution for this is avioding the delay() function, and getting the same results (without the side-effect) using timers (like millis()) or other ways.
Googling "How to avoid delay()" will give you lot of information about how-to do it, one example can be found here:
Arduino Playground - How and Why to avoid delay() function.
Good luck with that, and enjoy your programming experience!

we found some other code that helped us avoid the delay() functions. Now we are able to use the timestamp "Millis" to run our blinking lights AND have another if statement running the photocell & third LED.
Making progress! Thanks for the suggestions! Here is the code and it works great to turn the LED on and off based on the photocell, and have the other LED's flashing on their own.
const int photoCell =0;
const int ledPin = 13;
const int led2Pin = 12;
const int led3Pin = 11;
int lightCal;
int lightVal;
int ledState = LOW;
int led2State = HIGH;
long previousMillis = 0;
long interval = 250;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(led3Pin, OUTPUT);
  lightCal=analogRead(photoCell);
}

void loop() {
unsigned long currentMillis = millis();
lightVal = analogRead(photoCell);

if(currentMillis - previousMillis >= interval)
{
  previousMillis = currentMillis;
  if (ledState == LOW)
  ledState = HIGH;
  else
  ledState = LOW;
  if (ledState == LOW)
  led2State = HIGH;
  else
  led2State = LOW;

  digitalWrite(ledPin, ledState);
  digitalWrite(led2Pin, led2State);
}
if (lightVal < lightCal - 50)
{
  digitalWrite(led3Pin, HIGH);
}
else {
  digitalWrite(led3Pin, LOW);
}
}

You can use the library that support blink without delay.
For example, You can refer to this example code:
#include <ezOutput.h> // ezOutput library

ezOutput led1(7);  // create ezOutput object that attach to pin 7;
ezOutput led2(8);  // create ezOutput object that attach to pin 8;
ezOutput led3(9);  // create ezOutput object that attach to pin 9;

void setup() {
  led1.blink(500, 250);       // 500 milliseconds ON, 250 milliseconds OFF. start immediately
  led2.blink(250, 250, 1000); // 250 milliseconds ON, 250 milliseconds OFF. start after 1000 milliseconds
  led2.blink(100, 100, 2000); // 100 milliseconds ON, 100 milliseconds OFF. start after 2000 milliseconds
}

void loop() {
  led1.loop(); // MUST call the led1.loop() function in loop()
  led2.loop(); // MUST call the led2.loop() function in loop()
  led3.loop(); // MUST call the led3.loop() function in loop()

  // DO OTHER WORK HERE

}

The tutorial is available here

I think that timing might be too hard for 9year old, So :
I will give an alternative:
Synchronizing two Arduino's using main or software serial. this can be used to teach Server client (master/slave) architecture where client is set to finish loop quicker and wait for syncing data from server (master) to start next one.
Note that if you are sending numbers over serial to another Arduino use Serial.write() (rather then Serial.print(); it saves you from dealing with asci and char to int (no fun for kid only trouble)
There is a third option of a library which tries to imitate parallel syncing, but that is too much trouble and not a good habit to gain

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


text:
Adding an LCD to Uno but not enough pins left
I am an absolute beginner and wanted to build a simple home automation system using DTMF module using this guide. My problem is out of 12 pins most of them are getting used in DTMF module(5) and the relay module(4). So how do i add an LCD display to it?

Use an I2C LCD adapter. Requires only I2C pins (A4 and A5).

Get a bigger board with more IO...?

I was going to say use an I2C backpack, but since @MikaelPatel got there before me I'll go with use an I2C GPIO Expander like a MCP23017 which will give you an 16 GPIO ports.

Do you know you can use the Analog pins as Digital pins, so there are another 6 there?

You are using 8 GPIO pins for your existing modules. That leaves 12 left for an LCD (assuming you aren't using the serial port).
An LCD can work from as few as 6 pins (4 data, E and RS) - WR can be tied LOW and RESET can be tied HIGH, and the remaining 4 data pins left floating (or tied low).
That still leaves you 6 pins to do other things. Or 4 if you (advisedly) steer clear of using pins 0/1 for anything.

I suggest you first try every component separately (or if you are new to Arduino, try first simpler components like LEDs, switches etc),
As told by others the following components are easier to use:

Use a matrix keypad, see for example keypad. To reduce the number of pins you can use a multiplexer, such as 74HC165. 74HC165 are very cheap, although they need some additional programming and are slower than using direct pins (although for a keypad you will not notice).
Use a display like 1602 or 2004. See example at 1602 Display. Make sure you order one that has an I2C adapter attached to it (or solder it yourself if you feel comfortable).
After you tested all components separately (make different sketches and save them in case you need them later), you can combine them.

You can use arduino mega rather than uno or nano .... Or can use **I2C adapter to control your LCD display, I2C adapter only needs two pins to communicate with arduino and is easy to use ......
**

You have chosen a mighty task as your first project. I suggest that you run through as many of the example programs as possible before undertaking your project.
Firstly, I would recommend a matrix keypad instead of the DTMF keypad as it is much easier to use with an Arduino. This will also allow you to use a multiplexer which would use fewer pins.

I2C allows you to communicate to the LCD with only 2 pins. Here is such a I2C LCD (with buttons) sold by Adafruit.

As well as the tutorial over at Adafruit, there is a tutorial on such a topic over at ArduinoInfo.
Alternatively, you could upgrade to a Arduino Mega which has 54 IO pins as apposed to 14 on the Arduino Uno.

If some of the pins aren't used at the same time there are ways to reuse them.
Otherwise use a serial shifter or o.o expanders to drive the LCD. 2 to 3 pins max. Even 1 pin is possible if you tolerate lower speed of update.


text:
Do I need resistors or capacitors on this relay?
I'm using my Arduino to control a relay switch, which has an extension cord attached to it (see photo).
The relay is connected to the Arduino via pin 9, which is set to pinMode(9, OUTPUT);
Do I need any resistors or capacitors or diodes attached to this? Almost feels too simple, given I'm running AC power through the relay. But maybe no?
It definitely works, but I want to make sure I'm not going to burn something out (or down).

Majenko's answer describes how to switch a relay. However DO NO DO THIS. Breadboards are not designed for mains voltages or currents. If you are playing with mains power you need proper isolation.

Yes, that is too simple.
The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.
Google for "Arduino Relay" and you will find hundreds of thousands of examples.
In short, the circuit you need to create is this:

What's the purpose of the transistor?

It acts as a switch turning the relay on and off.

Is that not the function of the Arduino? Sending digitalWrite(RELAY, HIGH); through one of the pins to the relay switches the relay.

No. The arduino isn't powerful enough to switch a relay reliably. It can switch the transistor and then the transistor switches the relay. Technically the transistor is acting as a current amplifier..

I'm definitely successfully switching the relay with just the Arduino. So, if it's functioning, is there any real reason to use the transistor (for, say...safety purposes)?

The key word that I used was reliably. You are most likely drawing too much current from the port for sustained operation. That is bad. You have no back emf protection. That is even worse. I'd give it a week tops before you have to throw your Arduino away.


text:
How can I reduce the size of my sketch?
Looks like I'm overshooting the storage of my Adafruit Trinket:
Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
Global variables use 109 bytes of dynamic memory.

Any tips for reducing the footprint of my code?
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

long fadeTime = 1 * 10000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int timeHour = 14;
int timeMinute = 43;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  if(!rtc.isrunning()) {
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      beep(TONE, notes[random(0,3)], 50);
      delay(100);
    }

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
  int x;
  long delayAmount = (long)(1000000/frequencyInHertz);
  long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
  for (x=0;x<loopTime;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

One suggestion would be to change any int variables that you know won't be outside the range of [-127, 127] to a byte variable. byte data type is of size 1 byte, int is 4 bytes. This similar concept can be used for the other variables also.

Have you tried different compiler optimization levels?

@JonathanSmit: The range of a byte is [0, 255], not [-127, 127], as it is typedefed to be an uint8_t. And int is 2 bytes, not 4.

Ops, sorry about that, totally crossed my mind. I forgot byte is unsigned. Also, aren't ints 4 bytes on most 32 bit and 64 bit compilers? http://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes

@JonathanSmit: “Also, aren't ints 4 bytes on most 32 bit and 64 bit compilers?” Yes, they are, but the ATtiny85 inside the Trinket is an 8 bit chip.

I find getting rid of the arduino digitalRead/Write() and pinMode can save space. As a quick test I save 6% of space on a program by removing one digitalRead and pinMode. Gives you an idea.

I'm wondering if there's a more compact way to execute the intent behind the beep function. Ultimately trying to just make the piezo generate a set of rapid beeping noises (this thing is for an alarm).

I'm wondering if there's a more compact way to execute the intent behind the beep function - I wrote a small library to do that, however for the Atmega328. You should be able to adapt it. http://www.gammon.com.au/forum/?id=11504&reply=11#reply11

The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.
The order I look for things to reduce the footprint of an Arduino program are:

data (e.g. large strings)
libraries
your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.
It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.
You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.
You may also save a little space by replacing initialized variables which don't change to constants. Storing 25 in a variable takes 1 byte, plus 2 bytes every time you reference it; 25 in a constant gets optimized away, and will take up 1 byte every time you reference it.
As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.
Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.
You can also save some bytes by removing the clause  if(!rtc.isrunning()) {, once you have set it up once.
Additional: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may not save you anything in the end.
You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.
Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds1000)/(delayAmount2)) = (501000)/(38172) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.
In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).
You now have:
#define random_beep_length 7
void random_beep (unsigned char speakerPin)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
    // Heavily modified!
  int x;
  unsigned char pitch = 2865+random(0,3)*238;
  for (x=0;x<random_beep_length;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

Thanks for the tips! I forgot to update my code from when I was doing some debugging. I actually need the RTC to detect the current hour and minute (which is now reflected in my post).

I think it is a great idea to set the clock once - in a separate sketch - and then omit the part that checks if the clock is running. If that doesn't help, modify the clock library (or make a copy) to omit the parts that set the time.

“you might specify the delayamount as 2865+random(0,3)*238”. Or, better yet, 2945+random(0,4)*256. This saves 8 bytes at the cost of a small inaccuracy in the frequencies. Or, an equivalent but less readable form: 2945+(random()&3)*256 (saves 18 bytes).

@EdgarBonet, then why not (11+random()&3)*256, saving another byte? :)

The sum of these tips did the trick. I'm at 97% now. :)

You probably mean beep((11+(random()&3))*256);. When I compile it, it takes 28 bytes of flash, v.s. 20 bytes for beep(2945+(random()&3)*256);. For some reason, gcc -Os computes your sum  as a 32 bit number. This can be fixed with beep((11+((uint8_t)random()&3))*256);, which looks ugly but compiles to only 16 bytes! :-)

An option not already mentioned, but may be worth mentioning, would be to remove the bootloader and program the chip directly with a hardware programmer (or another Arduino). That will increase the available sketch memory from 5kiB to the full 8kiB on the chip.

This is a good idea, however bear in mind you'll need to put the bootloader back if you ever want to use it the way it was originally designed.

Is there some sort of how-to anywhere about doing this? I have an Uno I presume I could do that with.

As already mentioned by AMADANON Inc. in his answer, you should qualify
as const all the constant variables at the beginning of the program.
This is probably the biggest space saver.
You can gain something like 100 bytes by using direct port
access instead of
pinMode/digitalRead/digitalWrite. In the case of the ATtiny85, you only
have port B, and the Arduino pin numbers are the same as the Atmel bit
numbers. So you would for example use PINB & _BV(BTNPIN) instead of
digitalRead(BTNPIN).
There are a few optimization opportunities in beep():

pass only one parameter, as speakerPin and timeInMilliseconds are
constants in your program
have this parameter be delayAmount instead of frequencyInHertz,
and store these delays, instead of the frequencies, in the notes[]
constant array
do not compute the number of iterations (the misnamed loopTime)
beforehand, instead compute the elapsed time and loop until you reach
the required time

Here is my version of beep() with these optimizations:
void beep(int delayAmount)
{
  for (uint16_t t = 0; t < BEEP_TIME*1000/2; t += delayAmount)
  {
    PORTB |= _BV(TONE);  // digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    PORTB &= ~_BV(TONE);  // digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

Notice that the loop variable is actually half the elapsed time. This
saves a few bytes. Making the number of iterations constant, as proposed
by AMADANON Inc., also saves a few bytes (6 bytes in my test).
You should also remove all the calls to strip.Color(): replace every
instance of strip.setPixelColor(np, strip.Color(r, g, b)) by
strip.setPixelColor(np, r, g, b).
With all these optimizations combined, I am quite confident you will
gain more than the 290 bytes you need to fit your program in the
Trinket.

"constant variables"? lol! I know what you mean :)


text:
How do I change pin assignments for the LUFA AVRISPMkII?
I just managed to get Dean Camera's LUFA AVRISP clone working on my Arduino Pro Micro, when to my dismay I found that to use PDI for my XMega, I need to have PD5 exposed for the clock source! The Pro Micro has PD5 connected to an LED, so I am not easily able to use it.
If worst comes to worst, I can desolder the LED and wire a jumper, but that would be a pain in the butt. So I am wondering if any of you know if I can change the clock pin assignment from PD5 to PD6 or some other accesible pin. Thank you in advance for your help!
--[[ EDITS ]]--
Sorry for my lack of clarity, I am using the Pro Micro as the programmer, and the AVRISP clone supports PDI to the XMEGA. The 32u4 is actually directly supported by the programmer firmware. Here is what I am doing:
--[[ EDITS II ]]--
There is a schematic.. umm.. draw-o? I don't know but anyway the cathodes of D1 and D3 are NOT connected. That wire is an error.

simulate this circuit – Schematic created using CircuitLab
--Cantos

Umm, moderator? I do not know if this really belongs in arduino. I am not using any Arduino software or anything, and is more relavant to general AVR programming...

Mentioning Arduino in AVR questions on electronics.SE is like tagging a C question with C++ tag on SO. People will pay attention to the respective artifact instead of the question itself.

Okay, I'll remember that

Note that you may also bring your question up on meta if you feel the migration should be reversed. I doubt leaving your question on arduino.SE will bring you answers, while you got at least one on EE.

Do you have access to the source code? I can't seem find it. Only the .hex files. If only the hex code is provided, it won't be easy to change the pin mapping in the code. That would involve decompiling the hex etc.. I don't see anything particularly special about pin PB5, so changing the code to PB6 would most likely be possible (provided you have the code).

I do have the source code (it has to be built from source for this processor). I guess I will just serch through it until I find the pin assignment :)

I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX_LINE_MASK to change the pin. Thanks to everyone who helped!

Can you give more details on your problem? Schematics or something like that?
As I see from here, the Arduino Pro Micro uses ATmega32u4 chip, which is not part of XMega family, so I'm not sure if their internals are mutually compatible. In any case, if you configure PD5 as an input for your clock, it will work as an input, since it's a GPIO pin (DDRD &= ~(1<<PIN5)). You'll just additionally have the LED blinking :). You can also configure PD6 as an input in the same way (DDRD  &= ~(1<<PIN6)).

just in case anyone else is trying to use a Pro Micro as a makeshift PDI programmer with the AVRISPMKII firmware included in the LUFA library: contrary to what the OP claims to have accomplished by editing AppConfig.h, it is NOT possible to reassign the XCK pin on ATMEGA devices (at least not to my knowledge). I can only conjecture as to why he made that claim (perhaps he confused XMEGA/ATMEGA, and thus ISP/PDI). I do not wish to blame the OP, but his post had sent me and others down a dead end for a minute, too bad there is no easy fix like that. :(
The XCK function is hard-wired to the pin, in this (ATMEGA32U4) case PD5. The LUFA code utilizes the ATMEGA's USART transmitter configured for synchronous operation, hence a clock signal must be provided to transfer data to the target device. That's why XCK must be used and there is no other way, at least not with LUFA. The call that enables the PDI target has nothing to do with the AUX_LINE define in AppConfig.h
The only way a Pro Micro board can be used is by either soldering a wire to the XCK pin or by holding a wire against it (if you can hold it steady for a couple of seconds without slipping, that is). Thus, if you need a makeshift PDI programmer that will not require soldering, get a Teensy 2.0 or something else that breaks out PD5 as a GPIO pin.


text:
What is the proper way to make library pin mappings configurable?
I am working with some libraries that provide APIs for interacting with specific hardware chips (that makes these drivers?).  However, different custom boards or shields will have the chip mapped to different pins meaning the library needs to be modified for each case.  Needing to modify the library does not work well with the Arduino IDE Library Manager.
Are there preferred/recommended patterns for exposing this configuration so that the library itself does not need to be modified every time?
Here is an example where it is documented which part needs to be changed to match the pin layout of your board.

Many of the normal Arduino libraries already do this - start by familiarizing yourself with that method, even from a user perspective.

The method I use is to provide the pins as parameters to the constructor. Those pin numbers are stored in variables to use later in the .begin() function and elsewhere.
Most of the time I use initialization lists to keep things simple. For example:
class Something {
    uint8_t _cs;
    uint8_t _dc;

    Something(uint8_t cs, uint8_t dc) : _cs(cs), _dc(dc) {}
    void begin();
};

void Something::begin() {
    pinMode(_cs, OUTPUT);
    pinMode(_dc, OUTPUT);
}

Something mySomething(10, 8);

I would use either of the following two possibilities:
Use (class) variables and set them within the constructor.
Advantages:

Always initialized
Easy to use (constructor and pin setup at once)

Use a separate (e.g. Init) method.
Advantages:

Can be dynamically changed

Remarks
For pin settings, mostly static circuits are used so the first approach is probably better.
For settings, mostly the second method is better.
If many pins are involved (not likely), use a structure or separate pin settings class.
Macros
What I wouldn't advice is macros. When users need to change source code themselves, and new versions are installed, they either have to merge or redo the changes again. The advantages is a bit less (machine)code, a little bit faster probably and a bit less memory usage, but all three aspects are minimal.

In case you'd avoid the C++ constructor stuff that's quite commonly an overkill on Arduino, you could use #define's (object-like macros).
Like so:
#define PIN_ONE 1
#define PIN_TWO 2

The preprocessor will seamlessly replace PIN_ONE with the number 1 and PIN_TWO with 2 assuming those definitions are in the library header .h file. This will most likely takes the least amount of resources compared to the other possible solutions.
Alternative 1
If you have the opportunity to use modern-ish C++, you can use constexpr to define variables. Compared to macros you'll get type checking and it should be just as efficient.

The problem is that they need to be in a place where both the .ino file as well as the library source can get to them. This usually means a separate header file with everything that requires.

Are you sure? Pretty sure I can do #define switches in .ino's and they are used in libraries, but I might be wrong.

It can work if the code for the library is strictly in the header, but not if it's in a different compilation unit altogether.

Yeah, that makes sense, didn't know the exact limitations, added that disclaimer.

depending on your approach.
1) if you just provide the binary + header files, you will have to make the pins variables.
2) if you provide the source code and expect the user to recompile the source code, use macros.


text:
ESP32: How to run two independent PID controllers, one per core?
I want to control 2 independent processes with 2 PID controllers. Is it possible to run each controller on a separate core? I'm using this PID library. According to its documentation, the PID::Compute() function should be called once every loop(). How can this be achieved when using RTOS tasks (for multi core execution)?

why not put both  PID::Compute()  and  PID2::Compute() in loop()? it still will be called once per instance

No that would work but the PID computation algorithm will only run on a single core and that's not what I want to achieve.

still one core runs WiFi

Sure. The existing Arduino setup and loop are just executed in their own task:
void loopTask(void *pvParameters)
{
    setup();
    for(;;) {
        if(loopTaskWDTEnabled){
            esp_task_wdt_reset();
        }
        loop();
    }
}

extern "C" void app_main()
{
    loopTaskWDTEnabled = false;
    initArduino();
    xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);
}

So there's no reason not to replicate that to give yourself an entire new setup and loop, or just a single function that does it all if you prefer.
TaskHandle_t secondPidTaskHandle;

void secondPidLoop() {
    // setup code here
    for (;;) {
        // PID loop code here
    }
}

void setup() {
    xTaskCreateUniversal(secondPidLoop, "secondPidLoop", 8192, NULL, 1, &secondPidTaskHandle, 0);
}

void loop() {
    // First PID code
}

The last parameter to xTaskCreateUniversal() is the core to execute on. The default setup/loop runs on core 1:
#define CONFIG_ARDUINO_RUNNING_CORE 1

So just use 0 and it'll run it on core 0.

esp32_technical_reference_manual_en.pdf
Page 620
As mentioned before, only an elevated process with PID of 0/1 can initiate a process switch. The new process
may have any PID from 0 ~ 7 after the process switch. The key for successful proactive process switching is that
Espressif Systems 620
Submit Documentation Feedback
ESP32 Technical Reference Manual V4.3
29. PID Controller
when the last command of the current process switches to the first command of the new process, PID should
switch from 0/1 to that of the new process.
The software procedure for proactive process switching is as follows:

Mask all the interrupts except NMI by using software.
Set register PIDCTRL_NMI_MASK_ENABLE_REG to 1 to generate a CPU NMI Interrupt Mask signal.
Configure registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG.
Configure register PIDCTRL_PID_NEW_REG.
Configure register PIDCTRL_LEVEL_REG and PIDCTRL_FROM_n_REG.
Set register PIDCTRL_PID_CONFIRM_REG and register PIDCTRL_NMI_MASK_DISABLE_REG to 1.
Revoke the masking of all interrupts but NMI.
Switch to the new process and fetch instruction.
Though we can deal with interrupt nesting, an elevated process should not be interrupted during the process
switching, and therefore the interrupts have been masked in step 1 and step 2.
In step 3, the configured values of registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG will
affect step 6.
In step 4, the configured value of register PIDCTRL_PID_NEW_REG will be the new PID after step 6.
If the system is currently in a nested interrupt and needs to revert to the previous interrupt, register
PIDCTRL_LEVEL_REG must be restored based on the information recorded in register PIDCTRL_FROM_n_REG
in step 5.
In step 6, after the values of register PIDCTRL_PID_CONFIRM_REG and register
PIDCTRL_NMI_MASK_DISABLE_REG are set to 1, PID Controller will not immediately switch PID to the value of
register PIDCTRL_PID_NEW_REG, nor disable CPU NMI Interrupt Mask signal at once. Instead, PID Controller
performs each task after a different number of clock cycles. The numbers of clock cycles are the values specified
in register PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG respectively.
In step 7, other tasks can be implemented as well. To do this, the cost of those tasks should be included when
configuring registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG in step 3.
Espressif Systems 621
Submit Documentation


text:
help with a loop
I recently got into programing and I'm making an alarm. I cant figure out how to make a buzzer loop. I have two blinking LED's and two fading ones. Now I plan to have sound and it won't work.  It only blinks once and stops. I would also like the two fading LED's to fade at different times. I can't figure that out. Here's the code. 8 is the buzzer and red and blue are the fading LED's.
int blue = 6;
int red = 9;
int brightness = 0;
int fadeAmount = 500;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(red, OUTPUT);
     pinMode(blue, OUTPUT);
      pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(8, LOW);
  digitalWrite(8, HIGH);
  delay(10);

 analogWrite(red, brightness);
  analogWrite(blue, brightness);
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 millis();
}

Have a look here, on how you can use different peripherals in a  non-blocking manner. The following code is from the link:
// These variables store the flash pattern
// and the current state of the LED

int ledPin1 =  12;      // the number of the LED pin
int ledState1 = LOW;             // ledState used to set the LED
unsigned long previousMillis1 = 0;        // will store last time LED was updated
long OnTime1 = 250;           // milliseconds of on-time
long OffTime1 = 750;          // milliseconds of off-time

int ledPin2 =  13;      // the number of the LED pin
int ledState2 = LOW;             // ledState used to set the LED
unsigned long previousMillis2 = 0;        // will store last time LED was updated
long OnTime2 = 330;           // milliseconds of on-time
byte brightness = 0;
byte brigthnessInterval = 10;

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState1 == HIGH) && (currentMillis - previousMillis1 >= OnTime1))
  {
    ledState1 = LOW;  // Turn it off
    previousMillis1 = currentMillis;  // Remember the time
    digitalWrite(ledPin1, ledState1);  // Update the actual LED
  }
  else if ((ledState1 == LOW) && (currentMillis - previousMillis1 >= OffTime1))
  {
    ledState1 = HIGH;  // turn it on
    previousMillis1 = currentMillis;   // Remember the time
    digitalWrite(ledPin1, ledState1);     // Update the actual LED
  }

  if(currentMillis - previousMillis2 >= OnTime2)
  {
    previousMillis2 = currentMillis;  // Remember the time
    if (brigthness <= 254) brigthness += brigthnessInterval;
    if (brigthness == 255) brigthness = 0;
    analogWrite(ledPin2, brigthness);
  }
}

Here, two LEDs are controlled with different intervals, I changed LED number 2 to fade in with an interval specified with OnTime2; watch out your fade amount though, because analogWrite has 255 levels, and you immediately increased it to 500. You can add as many intervals as you want in the same manner, and perform tasks in pseudoparallel.

I suggested the basics in my answer to your previous question - "To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED."
To put that more concretely, instead of brightness, you'll need a redBrightness and a blueBrightness, and initialize them to different values.
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}

For instance, initializing them to '0' and '128', respectively, would drive the LEDs 180 degrees out of phase, or one fading up while the other fades down, assuming you use the same fadeAmount variable for both. If you use a redFadeAmount and blueFadeAmount, you can make them fade at different rates, as well.

try and analyze this alarm sound sketch
const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

void setup()
{
}

void loop()
{
  alarmSound();
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}

i tried this it sayed alarm sound not declared in scope and i cant figure out how to fix it

you can't compile it in Arduino IDE? what is "alarm sound"? the function is called alarmSound

"I recently got into programing"
So start here :
https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm
To apply such principle start by finding suitable "blink (SINGLE) LED" in Arduino IDE examples. There is no real need to reinvent  the wheel / code when you just starting to learn programming as long as you do not just "cut and paste".
You can blink LED attached to pin 13 without using any additional hardware.
Then find an example doing same without using "delay".
Most newcomers have issues with Arduino hidden main function and navigating "loop".
Once you have hang of the loop function you can add multiple "instances" of blinking LED's, and later consolidate these instances into suitable function.
Then use same approach to your buzzer or any other device.
Good luck.