title: Replacing delay() with millis()

text:
# Question
Title: Replacing delay() with millis()
I'm currently attempting to replace delay() in my project so that i may perform other tasks while waiting on a particular event to fire.

The issue I'm having, is every example i've found using millis / elapsedmillis has everything inside the loop, where I'm trying to use it inside void buttons(). needless to say, either it's not going to work outside of loop, or I'm doing something ridiculous, and too tired, or too ignorant to see what i'm doing wrong..

The end goal is to have the button draw over the top of the existing one, wait 1000ms then draw the next button. (time interval will be changed later to sync with hardware spin down etc)

Here is the complete sketch, perhaps someone can show me a reliable way to replace delay in the buttons funciton:

```
#include <Adafruit_GFX.h>
#include <TouchScreen.h>
#include <stdint.h>
#include <SPI.h>
#include <SD.h>
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;
#include <elapsedMillis.h>

elapsedMillis timer0;
elapsedMillis sinceTime1;
elapsedMillis sinceTime2;
elapsedMillis sinceTime3;

#define debug = false;
//#define debug = true;

#if defined(__SAM3X8E__)
#undef __FlashStringHelper::F(string_literal)
#define F(string_literal) string_literal
#endif

// most mcufriend shields use these pins and Portrait mode:
uint8_t YP = A1;  // must be an analog pin, use "An" notation!
uint8_t XM = A2;  // must be an analog pin, use "An" notation!
uint8_t YM = 6;   // can be a digital pin
uint8_t XP = 7;   // can be a digital pin
uint8_t Landscape = 0;

uint16_t TS_LEFT = 120;
uint16_t TS_RT = 940;
uint16_t TS_TOP = 940;
uint16_t TS_BOT = 180;
#define MINPRESSURE 10
#define MAXPRESSURE 1000

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// For the one we're using, its 250 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0

// Assign human-readable names to some common 16-bit color values:
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

int16_t BOXSIZE;
int16_t PENRADIUS = 3;
uint16_t oldcolor, currentcolor;

#define SD_SCK 13
#define SD_MISO 12
#define SD_MOSI 11
#define SD_CS 10
// In the SD card, place 24 bit color BMP files (be sure they are 24-bit!)

void setup() {
  // Init TouchScreen
    ts = TouchScreen(XP, YP, XM, YM, 300);     //call the constructor AGAIN with new values.

    BOXSIZE = tft.width() / 6;
    tft.fillScreen(BLACK);

  // put your setup code here, to run once:
    Serial.begin(9600);

  tft.reset();

  uint16_t identifier = tft.readID();
if (identifier == 0x7789) {
        //Serial.println(F("Found ST7789V LCD driver"));
        TS_LEFT = 120; TS_RT = 940; TS_TOP = 940; TS_BOT = 180;
        Landscape = 1;
    } else {
        //Serial.print(F("Unknown LCD driver chip: "));
        //Serial.println(identifier, HEX);
        return;
    }

    //Serial.print(F("Found LCD driver chip ID: "));
    //Serial.println(identifier, HEX);

  tft.begin(identifier);

  //Serial.print(F("Initializing SD card..."));
  if (!SD.begin(SD_CS, SD_MOSI, SD_MISO, SD_SCK)) {
    Serial.println(F("failed!"));
    return;
  }
  //Serial.println(F("OK!"));
  tft.begin(identifier);
  tft.setRotation(3);
  BOXSIZE = tft.width() / 6;
  tft.fillScreen(BLACK);
  bmpDraw("splash.bmp", 80, 20);
  delay(5000);
  loadhome();

}

void loop() {
//DO STUFF HERE

//Testing Text stuff here
  tft.setTextColor(BLACK);
  tft.setTextSize(2);
  tft.setCursor(15, 33);
  tft.print("123.456");
  tft.setTextColor(BLACK);
  tft.setCursor(115, 33);
  tft.print("543.210");
  tft.setTextColor(BLACK);
  tft.setCursor(215, 33);
  tft.print("789.654");
  buttons();
}

void loadhome(){
  tft.setRotation(3);
  BOXSIZE = tft.width() / 6;
  tft.fillScreen(BLACK);
  bmpDraw("cell.bmp", 10, 25);
  bmpDraw("cell.bmp", 110, 25);
  bmpDraw("cell.bmp", 210, 25);
  bmpDraw("stop.bmp", 15, 175);
  bmpDraw("locked.bmp", 90, 175);
  bmpDraw("play.bmp", 165, 175);
  bmpDraw("home.bmp", 240, 175);
  bmpDraw("coolstp.bmp", 15, 105);
  bmpDraw("spinstp.bmp", 240, 105);

  tft.setTextColor(RED);
  tft.setTextSize(3);
  tft.setCursor(50, 3);
  tft.print("X");
  tft.setTextColor(RED);
  tft.setCursor(150, 3);
  tft.print("Y");
  tft.setTextColor(RED);
  tft.setCursor(250, 3);
  tft.print("Z");

}

int homer = 0;
int play = 1;
int lock = 0;
int cool = 0;
int spin = 0;

const int interval = 1000;
unsigned long curMillis; //Current millis

void buttons(){
  //Touchscreen stuff
    TSPoint p = ts.getPoint();

    // if sharing pins, you'll need to fix the directions of the touchscreen pins
    pinMode(XM, OUTPUT);
    pinMode(YP, OUTPUT);

    p.x = map(p.x, TS_LEFT, TS_RT, 0, tft.width());
    p.y = map(p.y, TS_TOP, TS_BOT, 0, tft.height());
/*
//Use to map buttons
//Be sure to mark out button code before use!!
 if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
    Serial.print(F("p.y ="));
    Serial.print(p.y);
    Serial.println("");
    Serial.print(F("p.x ="));
    Serial.print(p.x);
    Serial.println("");
 }
*/
// Begin Buttons
//Coolant Button
if (p.y > 110 && p.y < 170 && p.x > 250 && p.x < 300) { // if stop area is pressed
  if(cool == 0){
   bmpDraw("coolen.bmp", 15, 105);
   //Serial.println(F("Coolant Button Pressed!"));
   cool = 1;
  } else {
   bmpDraw("coolerr.bmp", 15, 105);
   sinceTime1 = 0;
   //delay(500); //replacing with millis()
   if (sinceTime1 >= 1000) {
   bmpDraw("coolstp.bmp", 15, 105);
   //Serial.println(F("Coolant Button Pressed!"));
   cool = 0;
   }
  }
}

//Stop Button
if (p.y > 185 && p.y < 235 && p.x > 250 && p.x < 300) { // if stop area is pressed
   //Serial.println(F("Stop Button Pressed!"));
   Serial.write(0x18);
   Serial.print("\n");
}

//Lock Button
if (p.y > 185 && p.y < 235 && p.x > 182 && p.x < 234) { // if stop area is pressed
  if(lock == 0){
    Serial.print("$X\n");
   bmpDraw("unlocked.bmp", 90, 175);
   //Serial.println(F("Lock/Unlock Button Pressed!"));
   lock = 1;
  } else {
    Serial.print("$X\n");
   bmpDraw("locked.bmp", 90, 175);
   //Serial.println(F("Lock/Unlock Button Pressed!"));
   lock = 0;
  }
}

//Play-Pause Button
if (p.y > 185 && p.y < 235 && p.x > 110 && p.x < 160) { // if stop area is pressed
  if(play == 0){
   Serial.print("~\n");
   bmpDraw("play.bmp", 165, 175);
   //Serial.println(F("Play/Pause Button Pressed!"));
   play = 1;
  } else {
   Serial.print("!\n");
   bmpDraw("pause.bmp", 165, 175);
   //Serial.println(F("Play/Pause Button Pressed!"));
   play = 0;
  }
}

//Home Button
if (p.y > 185 && p.y < 235 && p.x > 35 && p.x < 90) { // if stop area is pressed
  if(homer == 0){
   bmpDraw("homeg.bmp", 240, 175);
   //Serial.println(F("Home Button Pressed!"));
   homer = 1;
  } else {
   Serial.print("$H\n");
   bmpDraw("homey.bmp", 240, 175);
   sinceTime2 = 0;
   //delay(500); //replacing with millis()
   if (sinceTime2 >= 1000) {
   bmpDraw("homer.bmp", 240, 175);
   }
   //delay(500); //replacing with millis()
   sinceTime2 = 0;
   if (sinceTime2 >= 1000) {
   //delay(750);
   bmpDraw("homeg.bmp", 240, 175);
   //Serial.println(F("Home Button Pressed!"));
   }
   homer = 1;
  }
}

//Spindle Button
if (p.y > 110 && p.y < 170 && p.x > 35 && p.x < 90) { // if stop area is pressed
  if(spin == 0){
   bmpDraw("spinen.bmp", 240, 105);
   //Serial.println(F("Spindle Button Pressed!"));
   spin = 1;
  } else {
   bmpDraw("spinerr.bmp", 240, 105);
   sinceTime3 = 0;
   //delay(500); //replacing with millis()
   if (sinceTime3 >= 1000) {
   bmpDraw("spinstp.bmp", 240, 105);
   //Serial.println(F("Spindle Button Pressed!"));
   }
   spin = 0;
  }
}

}

#define BUFFPIXEL 15

void bmpDraw(char *filename, int x, int y) {

  File     bmpFile;
  int      bmpWidth, bmpHeight;   // W+H in pixels
  uint8_t  bmpDepth;              // Bit depth (currently must be 24)
  uint32_t bmpImageoffset;        // Start of image data in file
  uint32_t rowSize;               // Not always = bmpWidth; may have padding
  uint8_t  sdbuffer[3*BUFFPIXEL]; // pixel in buffer (R+G+B per pixel)
  uint16_t lcdbuffer[BUFFPIXEL];  // pixel out buffer (16-bit per pixel)
  uint8_t  buffidx = sizeof(sdbuffer); // Current position in sdbuffer
  boolean  goodBmp = false;       // Set to true on valid header parse
  boolean  flip    = true;        // BMP is stored bottom-to-top
  int      w, h, row, col;
  uint8_t  r, g, b;
  uint32_t pos = 0, startTime = millis();
  uint8_t  lcdidx = 0;
  boolean  first = true;

  if((x >= tft.width()) || (y >= tft.height())) return;

  //Serial.println();
  //Serial.print(F("Loading image '"));
  //Serial.print(filename);
  //Serial.println('\'');
  // Open requested file on SD card
  if ((bmpFile = SD.open(filename)) == NULL) {
    Serial.println(F("File not found"));
    return;
  }

  // Parse BMP header
  if(read16(bmpFile) == 0x4D42) { // BMP signature
    read32(bmpFile);
    //Serial.println(F("File size: "));
    //Serial.println(read32(bmpFile));
    (void)read32(bmpFile); // Read & ignore creator bytes
    bmpImageoffset = read32(bmpFile); // Start of image data
    //Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
    // Read DIB header
    read32(bmpFile);
    //Serial.print(F("Header size: "));
    //Serial.println(read32(bmpFile));

    bmpWidth  = read32(bmpFile);
    bmpHeight = read32(bmpFile);
    if(read16(bmpFile) == 1) { // # planes -- must be '1'
      bmpDepth = read16(bmpFile); // bits per pixel
      //Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth);
      if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed

        goodBmp = true; // Supported BMP format -- proceed!
       // Serial.print(F("Image size: "));
       // Serial.print(bmpWidth);
       // Serial.print('x');
       // Serial.println(bmpHeight);

        // BMP rows are padded (if needed) to 4-byte boundary
        rowSize = (bmpWidth * 3 + 3) & ~3;

        // If bmpHeight is negative, image is in top-down order.
        // This is not canon but has been observed in the wild.
        if(bmpHeight < 0) {
          bmpHeight = -bmpHeight;
          flip      = false;
        }

        // Crop area to be loaded
        w = bmpWidth;
        h = bmpHeight;
        if((x+w-1) >= tft.width())  w = tft.width()  - x;
        if((y+h-1) >= tft.height()) h = tft.height() - y;

        // Set TFT address window to clipped image bounds
        tft.setAddrWindow(x, y, x+w-1, y+h-1);

        for (row=0; row<h; row++) { // For each scanline...
          // Seek to start of scan line.  It might seem labor-
          // intensive to be doing this on every line, but this
          // method covers a lot of gritty details like cropping
          // and scanline padding.  Also, the seek only takes
          // place if the file position actually needs to change
          // (avoids a lot of cluster math in SD library).
          if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
            pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
          else     // Bitmap is stored top-to-bottom
            pos = bmpImageoffset + row * rowSize;
          if(bmpFile.position() != pos) { // Need seek?
            bmpFile.seek(pos);
            buffidx = sizeof(sdbuffer); // Force buffer reload
          }

          for (col=0; col<w; col++) { // For each column...
            // Time to read more pixel data?
            if (buffidx >= sizeof(sdbuffer)) { // Indeed
              // Push LCD buffer to the display first
              if(lcdidx > 0) {
                tft.pushColors(lcdbuffer, lcdidx, first);
                lcdidx = 0;
                first  = false;
              }
              bmpFile.read(sdbuffer, sizeof(sdbuffer));
              buffidx = 0; // Set index to beginning
            }

            // Convert pixel from BMP to TFT format
            b = sdbuffer[buffidx++];
            g = sdbuffer[buffidx++];
            r = sdbuffer[buffidx++];
            lcdbuffer[lcdidx++] = tft.color565(r,g,b);
          } // end pixel
        } // end scanline
        // Write any remaining data to LCD
        if(lcdidx > 0) {
          tft.pushColors(lcdbuffer, lcdidx, first);
        }
       // Serial.print(F("Loaded in "));
        //Serial.print(millis() - startTime);
        //Serial.println(" ms");
      } // end goodBmp
    }
  }

  bmpFile.close();
  if(!goodBmp) Serial.println(F("BMP format not recognized."));
}

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t read16(File f) {
  uint16_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read(); // MSB
  return result;
}

uint32_t read32(File f) {
  uint32_t result;
  ((uint8_t *)&result)[0] = f.read(); // LSB
  ((uint8_t *)&result)[1] = f.read();
  ((uint8_t *)&result)[2] = f.read();
  ((uint8_t *)&result)[3] = f.read(); // MSB
  return result;
}

```

# Answer
The usual technique at this scale of technology is to keep loop() pretty short, mostly making frequent calls to a timer function that keeps a list of things to be done (implemented with callback-functions) and the times at which to do them, and which calls those functions at the appropriate times. The upper level(s) of your sketch would schedule tasks by registering one or more callback-functions to be run at a given time or periodically.

When the timer function is called, if there is nothing to do, or when a callback-function returns, the timer function returns immediately to its caller (probably loop()). loop() can do other work, as long as it can still call the timer function as frequently as your task dispatching requires.

The SimpleTimer library at Arduino Playground is an implementation of such a timer-function.
> 2 votes

# Answer
Taking JRobert's advice, i checked out the simpletimer library.. the final solution was to set up three timers and change the way the buttons functioned.

as per documentation of the simpletimer library, added the following global:

```
#include <SimpleTimer.h>
SimpleTimer timer;
...

```

Then to setup, i added my three timers

```
timer.setInterval(7000, spindle); //times based on hardware reality
timer.setInterval(2000, coolant);
timer.setInterval(21500, homer);
...

```

Then started the timers in loop by adding:

```
timer.run();
...

```

Finally, i edited the buttons and added variables to denote state of button. i.e.

```
/*
0 == on,
1 == transitional1
2 == transitional2
3 == stopped
*/
int homeb = 0;
int cool = 0;
int spin = 0;

```

Changed the touch screen code for each button to kick off the timers...

```
//Coolant Button
if (p.y > 110 && p.y < 170 && p.x > 250 && p.x < 300) { // if stop area is pressed
  if(cool == 3){
   bmpDraw("coolen.bmp", 15, 105);
   //PWM the spindle pin on
   cool = 0;
  } else {
    if(cool == 0){
      //PWM the spindle pin off
      cool = 1; //Start the timer sequence for stopping coolant
    }
  }
}

```

then i added a void for each timer, this is where i redraw the buttons

```
void coolant() {
  if (cool == 1){
   bmpDraw("coolerr.bmp", 15, 105);
   cool = 2;
  } else {
    if (cool = 2){
   bmpDraw("coolstp.bmp", 15, 105);
   cool = 3;
    }
  }
}

```

Hope this helps someone else in the future, as it was a real pickle for me to figure out at first.. Thanks again, and credit goes to JRobert, his advice pointed me directly to the solution.
> 0 votes

---
Tags: timers
---


# Question
Title: Compilation error using arduino-mk on arch Linux (undefined reference to __dso_handle)
1. I'm compiling a simple sketch that reads values from an analog input and activates a buzzer on a digital input.
2. working on an Arduino uno.
3. the sketch compiles and runs fine on windows and arch linux using the Arduino IDE.

I recently tried to start working with Arduino-mk, I tried to compile the said sketch and got the following compiler error (analogVal is the variable holding the analogRead):

/usr/bin/avr-gcc -mmcu=atmega328p -Wl,--gc-sections -Os -o /home/niv/Gits/bin/uno/maglove/maglove.elf

```
~/Gits/bin/uno/maglove/maglove.ino.o ~/Gits/bin/uno/maglove/libcore.a  -lc -lm
/home/niv/Gits/bin/uno/maglove/maglove.ino.o: In function `_GLOBAL__sub_I_nothing':
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xc): undefined reference to `__dso_handle'
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xe): undefined reference to `__dso_handle'
maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0x18): undefined reference to `__cxa_atexit'
/usr/bin/avr-ld: /home/niv/Gits/bin/uno/maglove/maglove.elf: hidden symbol `__dso_handle' isn't defined
/usr/bin/avr-ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
/home/niv/Gits/Arduino-Makefile/Arduino.mk:1416: recipe for target '/home/niv/Gits/bin/uno/maglove/maglove.elf' failed
make: *** [/home/niv/Gits/bin/uno/maglove/maglove.elf] Error 1
make: Target 'all' not remade because of errors.

```

I am not very experienced with Arduino yet, and google has failed me in finding this error or any keyword from it in the context of Arduino uno.

thanks.

# Answer
> 2 votes
I can't say I fully understand what is going on, but it seems that if you add:

```
void * __dso_handle;

```

You may be able to eliminate one of the problems. You might try the same trick with `__cxa_atexit` as well.

I found the idea by searching on:

> arduino \__dso\_handle

This is the webpage that I found that suggested the `void *` hack.

---
Tags: arduino-uno, compile, linux, avr-gcc
---


# Question
Title: Briefly "wake up" Arduino in response to an event
I want to connect a device to a door handle, so whenever someone opens the door I'll be able to send a message via my arduino that is connected to a WIFI shield.

I have a simple orientation sensor, so I know when the handle is being pushed. The problem is I don't want to keep the Arduino on all of the time (energy issues).

The orientation sensor closes a circuit for about 100ms, so I thought to connect the battery to the Arduino in series with the sensor, but the problem is that it might take more than 100ms to connect and send the data - I need at least 5 seconds to be sure.

Any ideas on how to make the Arduino "power up" for 10 seconds each time someone uses the door handle and then to cut off the power?

# Answer
> 7 votes
Easy answer: Don't.

Have the Arduino sleep most of the time, and let the door handle invoke an interrupt that wakes it up. Then do whatever processing is required, and then go back to sleep.

This won't work as well with a full Arduino as it would with a bare MCU since the rest of the board has its own quiescent load, but once you get it working with an Arduino you can get a bare MCU, wire it up, write the code to it, and away you go.

# Answer
> 4 votes
I had a similar situation some time ago. I don't have the schematic at hand, but it looked more or less like the one below.

It works as follows:

1. Momentary switch closes and saturates Q1 via R1. It also powers the Arduino. The I/O in on the Arduino has not been programmed yet so it floats. Q1 energizes the coil of the relay which closes its N.O. contact. Now the circuit has latched and you have power to the Arduino for as long as you want.
2. Arduino starts, does its work (xmits signal or whatever) and then programs the selected I/O pin as output and pulls it low. This will divert current away from the base of Q1, which will cut the current to the coil and everything closes down and no power is drawn from the battery. R1 should be some 10 times greater than R2 for this to work. Say R1 = 1K, and R2 = 100 Ohm.

This is a concept drawn from memory, it might require some refining :-)

# Answer
> 2 votes
You may find the answer to How can a let my atmega328 run for a year on batteries? from SE Electrical Engineering helpful. It is a very detailed resource on power saving measures for the Arduino.

# Answer
> 2 votes
You are much better off **sleeping** the Arduino. In power-down mode the processor can use as little as 100 nA (0.1 µA) which is somewhat less than the self-discharge rate of batteries anyway.

I have a page about power saving techniques.

You also would want to make a custom board, or at least choose an Arduino without a voltage regulator, LEDs, USB chip, etc.

The Atmega328P, when in power-down sleep mode, can be woken by an external interrupt, such as what your door could provide.

---
Tags: sensors, power
---


title: Custom arduino board

text:
# Question
Title: Custom arduino board
Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:

Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?

In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!

# Answer
> 7 votes
I have a page about a breadboard Arduino which is basically an Atmega328P processor (same as in the Uno, inter alia) on a breadboard.

---

Also a wire-wrapped Arduino.

---

You can go pretty minimalistic with a ATtiny85 mounted on a button battery like this:

---

> Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board?

Ah there you might be asking a bit much. There are hundreds, if not thousands, of shields people have designed for it. Certainly you can make up your own board to meet a specific purpose.

# Answer
> 3 votes
Absolutely. You might start with the Arduino to Breadboard Tutorial while defining your hardware requirement - for example, decide what voltage you are going to run at (and pick an appropriate regulator) and then decide if you can use the imprecise 8 MHz internal oscillator or if you need a more precise external resonator or crystal.

Once you have determined your required circuitry you can advance to making circuit board, and possibly switch from the DIP version of the ATmega to a QFP package which is smaller and potentially ultimately easier to work with (for production you might even use a QFN, though that is a bit more challenging to solder by hand). You may also want to look at what package technology your peripheral chips come in.

Do note though both that you can buy smaller premade Arduion-compatible PCBs, and that there are other chips which are worth considering for a permanent project, some with Arduino compatible libraries available, and some without.

# Answer
> 1 votes
Yes it is possible. It can be as simple or as complex as you wish :)

http://www.instructables.com/id/How-to-make-your-own-Arduino-board/

---
Tags: shields
---


# Question
Title: When setting hardware timers as interrupts, should I prefer a lower prescaler value or a lower CTC?
I'm currently playing with Arduino's hardware timers, and a question came to my mind. Let me explain it a bit.

Let's suppose I want a certain function to execute every 1024 clock ticks. AFAIK, I could achieve this in several ways, playing with the prescaler value for Timer2, and its CTC:

1. Setting the prescaler to 1 and the CTC to 1024
2. Setting the prescaler to 8 and the CTC to 128
3. ...
4. Setting the prescaler to 1024 and the CTC to 1.

All these ways would achieve what I want, but, which one is more efficient? Or it doesn't matter at all?

Thanks in advance for sharing your knowledge :P

# Answer
> 2 votes
If 'clock tick' count (here 1024), timer width and MCU clock used are constant (a fixed value), I would not go for last option i.e. prescalar 1024 and CTC of 1. Here are my reasons (specially for Arduino )

1) When CTC is close to zero ( like 1-\> 10), sometimes timer behaves as if count is zero and outputs a square wave (with 50% duty ratio) with half the demanded frequency. So make CTC reasonably big. But again selecting a high clock frequency (pre scalar 1) may also show reduced accuracy. A intermediate option I think is better.

2) When count CTC changes dynamically in a process, timer pre scalar should be selected such that CTC count will always be less than or equal to timer width over whole process.

i.e. the maximum 'timer tick count' should be comfortably accommodated by the timer with it's given width. Even here same dilemma again occurs, then selection based on point 1 is better.

If this is not enough, then only way I think is to implement each case physically and check which combination gives you the best results. Practical results I think are more reliable ( may be you will get a board specific efficient combination!)

# Answer
> 3 votes
There is a trade-off between resolution and achievable frequencies. You mention Timer 2, but on the Atmega328P Timer 2 is an 8-bit timer, thus you would not be able to set the CTC to 1024.

Let's assume we are talking about an 16-bit timer, like Timer 1 on the Atmega328P. With a prescaler of one, you can time (assuming a 16 MHz clock) from 1 to 65536 "ticks", that is 62.5 ns up to 4096 µs.

This would be the most *precise* measurement because you are using one (processor) clock tick per timer tick (a prescaler of one).

However if you plan to time for more than 4.096 ms then you need to bump up the prescaler. The next prescaler up on Timer 1 is 8, so now you can time for an interval 8 times as long (32768 µs) however your accuracy (precision) has now decreased by a factor of 8. The *granularity* of the timer has increased from 62.5 ns to 62.5 * 8 ns, which is 500 ns.

If you need to time longer than 32.768 ms then the prescaler has to be larger again, the next one being 64. So now you can time up to 262144 µs, but with a granularity of 62.5 * 64, which is 4000 ns (4 µs).

My suggestion would be to use the lowest prescaler that you can, but still get the interval you want. So obviously you can't use a prescaler of one to time 10 ms.

---

I have a discussion about timers on http://www.gammon.com.au/timers.

On that page is a chart which helps visualize the effects of different prescalers:

The top part (count of one) effectively gives you the granularity of each prescaler. For example, a prescaler of 256 has a granularity of 16,000 ns (16 µs). Certain frequencies (powers of 2) will lend themselves to combinations (eg. prescaler of 1 with a count of 256, or prescaler of 256 with a count of 1).

However for frequencies that don't have that property, the smaller prescaler will (if it can be used) give a finer granularity.

---
Tags: interrupt, timers
---


# Question
Title: Why doesn't this debounce function work?
**Edit 2** I made a function that works, but I'm still confused about just one thing...

I'm very confused about how variables work in C++.

**In this program...**

```
  boolean debounce(void)
{
  static boolean buttonState=LOW;
  static boolean lastButtonState;
  boolean currentState = digitalRead(4);
  static unsigned long lastDebounceTime;
  if (currentState != lastButtonState){ //if the button state has changed
    lastDebounceTime=millis();  //reset timer
    }

  if ((millis()-lastDebounceTime) > 50)  //if 50 milliseconds has passed since last bounce
  {
    buttonState = currentState;  //read value again now that bouncing is over

    }
  lastButtonState = currentState;
  return buttonState;
}

```

**Why does changing this**

```
lastButtonState = currentState;

```

**To this**

```
lastButtonState = buttonState;

```

**Make any difference in the program?**

When I try the latter line of code, the whole function stops working and I don't understand why.

# Answer
This probably won't answer your question completely, but here are some notes from me:

```
buttonState = current ;  //read value again now that bouncing is over

```

This won't read the value again, it just copies `current` into `buttonValue`.

What you wanted is:

```
buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

```

You have multiple issues with your `debounce` call:

* `lastTimeDebounce` is never used by your code, so it is always zero.
* `lastButtonState` will be always `buttonVal` making the debounce function useless.

Some other tips:

* Don't use the same names for parameters as for global variables:

boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)

The global variable `BUTTON` will be **shadowed** by `int BUTTON`, essentially overriding it.
* Don't use global variables (unless you have a very good reason)

**EDIT**

I would strongly recommend writing a function that debounces only **one** pin.

Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).

**EDIT2**:

Here is a debounce function that should work:

```
const uint8_t PIN = 13;

/*
 * Returns debounced value for `PIN`
 */
boolean debounce(void)
{
    // Current state of the pin
    boolean currentState;
    // Last state of the pin, initial value is zero
    static boolean lastCurrentState = 0;
    // Timer
    static unsigned long debounceTimer = millis();
    // Debounced value, initial value is zero
    static boolean debouncedValue = 0;

    // We first read the current state of the pin
    currentState = digitalRead(PIN);

    // Then we look if the state has changed
    if (currentState != lastCurrentState) {
        // If it has, we need to reset the debounce timer
        debounceTimer = millis();
    }

    // Then we check if the timer has expired
    if ((millis() - 50) > debounceTimer) {
        // The timer expired so we update the value
        debouncedValue = currentState;
    }

    // Save the latest state
    lastCurrentState = currentState;

    // We always return a debounced value:
    return debouncedValue;
}

```

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.
> 4 votes

# Answer
"It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.

The problem is that you are trying to use global variables to remember the internal state of the debouncer function, and you're passing those variables into the function as parameters. In C (or C++, which is the underlying language that you're using), an assignment to a function parameter does NOT update the corresponding variable in the caller's environment. Therefore, `lastDebounceTime` never gets updated, and your `debounce()` function always just returns the current state of the button.
> 2 votes

# Answer
Im not an expert of C programming, but I can see lot of troubles in your programming, because you do call a function debounce(), but it is not a function that does a complete task, so you set additional variables outside of it. This is a bad practice, because you can't call the same function to compute multiple keys, that's what functons are for - make one function and call multiple times with different parameters. You should switch to pointer orented parameters for lastButtonState.

```
    boolean LastButton_1; // global or static variable
    long LastDebounce_1;
    int BUTTON_1;
        ... and so on

    boolean debounce(boolean *LastButton, long *LastDebounce, int BUTTON)
        {
          //your code here, where you read and write to variables located at pointer
           boolean something, new_value;
           something = *LastButton; //read value at pointer address
           *LastButton = new_value; //store the value at pointer address
        }
//now you call this
debounce(&LastButton_1, &LastDebounce_1, BUTTON_1)

```

Perhaps it is not correct, since I know only very basic C, but the way is the right one
> 1 votes

# Answer
If you only have one button to debounce, you can store it's state as static variables in the `debounce()` function itself, like:

```
bool debounce()
{
    const int pin = 4;
    static bool last_state;
    static unsigned long last_change;
    unsigned long now = millis();

    if (now - last_change > 50) {
        bool state = digitalRead(pin);
        if (state != last_state) {
            last_change = now;
            last_state = state;
        }
    }
    return last_state;
}

```

If you may have to debounce more than one button, the cleaner way would be to store the state inside an object, and have the debounce function be one of its methods. That's what the Bounce library does.
> 0 votes

---
Tags: serial, programming, button, debounce
---


# Question
Title: Clone pro micro serial port 'COM4' already in use
So I just got this board I ordered from ebay and tried to play with it for the first time. http://www.ebay.com/itm/Leonardo-Pro-Micro-ATmega32U4-Arduino-IDE-1-0-3-Bootloader-replace-Pro-Mini-/310634777706?pt=LH\_DefaultDomain\_0&hash=item4853468c6a

I connected it to my PC and it was installing a driver. I didn't pay much attention to it but I think it finished installing it successfully. I then installed arduino IDE 1.6.3(latest) and tried to compile and upload the empty default sketch just to see if it uploads it. the progress bar got to the end but it was stuck on "uploading..". I waited for a few minutes but it didn't seem like it is going to end so I unplugged the USB and re inserted it back. I then looked in the tools menu and saw it was set to port COM1 which is the communications port on my pc, so I changed it to port COM4(Arduino Leonardo) and the board to Leonardo and again tried to compile and upload the default sketch but now I got this error:

Arduino: 1.6.3 (Windows 7), Board: "Arduino Leonardo"

Error opening serial port 'COM4'. (Port not found)

trying to open the serial monitor gives the same error.

So I checked the item listing on ebay and it said that the board was supported under arduino IDE 1.0.3 so I downloaded it and tried to compile and upload the default sketch but it gave me the serial port 'COM4' already in use error.

I tried resetting the board, uninstalling and reinstalling the driver and the IDEs and disabling/re-enabling the device in the device manager. nothing helped.

I am not sure what I am doing wrong as I am new to this.

Thank you.

# Answer
Reboot you PC, see if that clears it.

If not then fire up Device Manager and have a look at what COM ports you are using.

I think there is a way of reassigning the ports used by the boards within the control panel, but I can't remember what it is at the moment, so have a quick google.

Its not the fact that its a Clone that's causing you an issue, its Windows drivers that have caused you issues. If all else fails, uninstall the drivers, reboot twice and try again. I also don't think using a newer version of the IDE will have a negative affect.
> 1 votes

---
Tags: serial, arduino-ide, arduino-leonardo, arduino-pro-micro, clones
---


title: How to make precise square wave?

text:
# Question
Title: How to make precise square wave?
I am playing with stepper motors and I need a precise square wave generator for f=29.710617283951Hz. I've done this on Raspberry Pi without any problems, but I need something smaller and with less power consumption.

Is it even possible to get that frequency?

# Answer
> 3 votes
Reducing the power requirement, compared to an R-Pi, should be straightforward, achieving 29.7106Hz is doable, reducing the size is harder (an R-Pi is quite compact).

Some of the available options depend on your electronics skills, and budget.

I'll assume you want to use off-the-shelf hardware as much as practical, but are okay to wire 'modules' together (size could be a bit smaller than an R-Pi using off-the-shelf parts, but could be *significantly* reduced by a custom made part).

I'll also assume you want to keep costs under $100. (I apologise if I am wrong, but this seems like a level that many of this community might find interesting :-)

### Preamble:

Even at 16MHz, 29.7106Hz represents a count of approximately 538,528, which requires 19 bits. So I would *not* use a chip with 8 or 16 bit timers. I would make my life easier by using a chip with 32 bit timers.

Further, the code will be manipulating quantities with at-least 19 bits, so I would *not* use an 8 or 16bit CPU. I would make my life easier by using a 32bit CPU that operates on 32bit quantities in a single operation. This may become very important if you opt for a software-heavy approach.

### Initial Approach:

Lets assume our 32 bit processor has a clock of 64MHz.
To generate a clock frequency close to 29.710617284Hz (as good as my calculator will do), load a timer with 2,154,112 (maybe 2,154,111, depending on how the counter triggers).

The more accurate divisor is 2,154,112.094.

That count is within 0.05ppm (parts/million) of 29.710617284Hz at a 64MHz clock.
Also, a count of +/- 1 is a change of less than 0.5ppm. That is about 30x better than the more relaxed requirement, '29.7106', mentioned in your comments.

Using 64MHz to drive the count will enable 4x better accuracy, 0.5ppm, than using a 16MHz clock, 2ppm, when we examine ways to implement this in the 'Options' section below.

*Summary so far:* if the microcontroller had a very accurate clock (much better than 0.5ppm error), then the problem is solved.

However, the crystals used to drive the microcontroller typically have a frequency stability of 30-50ppm, and may be even worse.

### Options to reach 0.5ppm:

*1. Replace the MCUs crystal with a much better part.*
This will typically require some soldering skill, and the parts I've seen (which are likely to replace the existing crystal) are stable at about 10ppm. That might be a factor of 3-5 better than the factory fitted crystal, so may be worth the effort, however there are better options.

*2. Feed the MCU with a higher-stability clock source than a crystal.*
Most MCU's can accept an external clock source in place of the crystal. Temperature Compensated Crystal Oscillators (TCXO) cost about $5, and can achieve 0.5ppm (0 to 40C, 2ppm -30C to +85C). So an improvement over an 'ordinary' crystal of 30-100x.

If this is appealing, I'd actually recommend looking at ST Micro's Nucleo boards. They are low-cost (under $12), so not much wasted if it doesn't work, and many of the boards already take an external oscillator, so may be easier to change. (They are 32bit CPU's with 32bit timers, and can run at 64MHz,) I imagine folks can recommend other boards.

*3. 'Discipline' the square-wave counter with an external high-quality clock*
The idea is to use a very accurate external clock, and adjust the square-wave count to get high-accuracy than the existing MCU crystal. While counting the MCU clock for the square wave, use a second counter to count the number of MCU clock cycles a known, high-quality, external timing source event takes. The external clock source could be a TCXO, an Oven Controlled Oscillator (OCXO), which can achieve 0.001ppm) or GPS.

Program code could estimate the error of the MCU clock vs higher-quality clock, and adjust the square-wave count *within each square-wave cycle*. This may keep the square-wave within 0.5ppm using one or more +1 or -1 adjustment of the counter. This approach has the advantage that the only electronics is connecting the high-quality timing source to a pin on the microcontroller. The rest is (carefully written) software.

Edit:
To be clear, this option 3 can use an unmodified, off-the-shelf, MCU development board. The original crystal is unchanged; there is no need to modify it to replace its crystal.

So it could use a small, e.g. Arduino-Nano size, microcontroller running at a reasonable rate (e.g. 64MHz) connected to a TCXO (or even OCXO), and get close to 0.5ppm error.

# Answer
> 2 votes
You can user Timer 1 on the Atmega328P (such as is found on the Uno) to get you into that ball park:

```
const unsigned long countTo = 33658;  // F_CPU / 8 / 29.71 / 2

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

  // PWM, top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11);  // PWM
  TCCR1B = bit (WGM13) | bit (CS11);   // PWM, prescaler of 8
  OCR1A = countTo - 1;                 // zero relative
  OCR1B = (countTo / 2) - 1;           // 50% duty cycle
  bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

I measured a frequency of 29.67 Hz on one device and 29.41 Hz on another. The Uno is driven by a resonator, not a crystal, so a couple of percent error is to be expected.

---

I have a page about the hardware timers and a cheat-sheet for Timer 1:

---
Tags: pwm
---


# Question
Title: Arduino with multiple buttons - will power be an issue?
I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?).

Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to `INPUT_PULLUP` mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?

So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?

# Answer
Most of your idea is sensible. Let's go over the sensible part first, and then we'll cover the bits that need work.

Using an internal pullup and shorting the input to ground is the correct way to approach this. Note that the pins will read `HIGH` when off and `LOW` when triggered this way.

Each pullup on an AVR is between 20kohm and 50kohm. This means that the current consumption if all 15 buttons are pressed is at most about \\$15 \cdot {5 \text{V} \over 20\text{k}\Omega} = 3.75\text{mA}\\$. This isn't enough for the USB connection to care about.

As for using the analog connections, A0 through A5 also have digital GPIO capability, which means that you would treat them exactly the same as you would the digital pins (A6 and A7 don't have digital GPIO unless you're running a ATmegaXX8PB with a special core).

And now the bad news.

The Arduino Uno is based on the ATmega328P, which *does not* have native USB capability. It communicates with the host through a serial connection via a USB-UART bridge. If you're using a real (or real-enough) Uno then that bridge is a ATmega16U2 which is a MCU that *does* have native USB capability, so it can be reprogrammed to interpret the serial stream from the '328P and talk USB to the host.

But if you aren't then you will either need to run a piece of software on the host that translates the serial stream to HID actions, or you will have to run a software USB stack on the '328P such as V-USB which will allow you to use Low-Speed USB 1.1 directly.

My recommendation is to see if you can get an Arduino or other AVR-based board that has an ATmegaXXU4 so that you can use `Mouse` and `Keyboard` directly instead of having to faff around with HID profiles and software USB. Unless that's your thing, of course.
> 2 votes

# Answer
Yes, it is safe to connect multiple buttons to ground. The pull-up resistors have a fairly high value - about 10 kΩ and we know from Ohm's Law that

```
I = V / R = 5 V / 10k = 0.5 mA

```

per button. Your USB power is good for about 500 mA.

Welcome to StackExchange.
> 2 votes

---
Tags: usb, button
---


title: SDA and SCL problem with MEMS

text:
# Question
Title: SDA and SCL problem with MEMS
I have a simple question to ask you about SDA and SCL pins. I have a gyro and I use these 2 pins to make it work; how can I use an accelerometer combined to a Gyro if these 2 pins are used? I should need another 2 SDA and SCL pins for the accelerometer... Tell me that I don't need to buy an IMU :D

EDIT: I'm using Gyro LG3D20H from Adafruit, reading gyro values each 10 ms.

# Answer
> 2 votes
I2C is designed to have multiple devices connected. Assuming the gyro and accelerometer have different I2C addresses they can both be connected to the same SDA and SCL pins.

For more information see http://www.gammon.com.au/i2c

Naturally you can only "talk to" one at a time. You may need pull-up resistors on both SDA and SCL, unless the hardware already has them.

---
Tags: arduino-uno, accelerometer, gyroscope
---


title: How to have arduinos work together?

text:
# Question
Title: How to have arduinos work together?
I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?

# Answer
You **can** make quite an impressive game.

**Features**

* Based on ATmega328P running at 16 Mhz (same as Arduino Uno).
* The game has a display resolution of 104x80 with 256 colors.
* Video mode is tile based and supports up to 3 sprites per scan line.
* Sprites are multiplexed so there can be unlimited number of sprites vertically on the screen.
* 4 audio channels with triangle, pulse, sawtooth and noise waveforms.
* Chiptune music playroutine and sound effects.
* NES controller support.

Video of it in action:

https://www.youtube.com/watch?v=sLvgW\_zb6bQ

Original post on the Arduino forum.

---

So, before you start wanting to connect lots of Arduinos together, investigate what can be achieved with just one. :)

The first thing to do, as others have mentioned, is to store static information into PROGMEM (see Putting constant data into program memory (PROGMEM) for more details).

If Petri Häkkinen can get his title screen, levels, sprites, music, and game logic into an Atmega328P you can too! Have fun!
> 1 votes

# Answer
Yes and no.

Yes you can make Arduinos communicate with each other and send messages to each other.

Can you use that to make a game? Possibly.

Is it worth the effort? No.

It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.
> 1 votes

# Answer
You can have two Arduinos communicate with each other but it is fairly complex. See this instructable. One process is using the I2C protocol.

A far easier option is to use a larger Arduino model. Consider the Mega 2560 since it has 8 times the Flash memory.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Pro Micro, get data out of Tx pin?
I have a Sparkfun Arduino Pro Micro with an ATmega32u4 on it and a Roving Networks RN32 Bluetooth Module

Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.

Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?

I uploaded this to the Arduino with no hiccups:

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

void loop(){
  Serial.print("HelloWurld");
}

```

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.

How do I get the Arduino to put out serial data on the Tx pin?

# Answer
> 19 votes
You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos. *Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question)*.

According to the documentation for the official Arduino Pro Micro:

> Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of `Serial` to `Serial1`

```
void setup(){
    Serial1.begin(9600);
}

void loop(){
    Serial1.print("HelloWurld");
}

```

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers. If you wish to probe it, that would be the best place to do so.

If you wish to transmit data out of a **different pin** which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use SoftwareSerial or similar implementation to bit-bang the serial data out of a general purpose I/O pin.

For example (inspired by this example):

```
SoftwareSerial mySerial(4, 5); // RX, TX

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

void loop(){
    mySerial.print("HelloWurld");
}

```

# Answer
> 5 votes
The bluetooth board uses **3.3V**, not 5V according the datasheet.

So you'll need to **shift the voltage level** between it and the Arduino board (which is **5V**). Note that the spec sheet shows how this can easily be done with 2 resistors (`R1` and `R2` in sheet typical application circuit, page 5).

Also, on the bluetooth module, the RS232 interface has 4 pins:

* UART\_TX
* UART\_RX
* **UART\_CTS**
* UART\_RTS

**UART\_CTS** must be **0** to ensure the device reads incoming bytes. Normally this is done by an internal pulldown resistor, but you must ensure you did not connect that pin to **+V**.

Finally, ensure that the baud rate of the module is properly set to **9600 bauds**, the same as in your program.

# Answer
> 4 votes
So I stumbled upon this thread while having similar problem, but with HC-05 module. So because I have too much free time on my hands during finals (no I don't) I decided to create a small github repo that might help someone sometime. https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup

The code is:

```
//Writen for pro micro
//These proved to be usefull
//http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin
//https://forum.sparkfun.com/viewtopic.php?f=32&t=38889&sid=8178cdb38005ff33cc380a5da34fb583&start=15

void setup()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial1.begin(38400);
}

void loop()
{

  //Serial1 is the physical Serial Connections on TX and RX pins
  if (Serial1.available()) Serial.write(Serial1.read());

  // Serial is from my understanding the virtual connection with computer via USB
  if (Serial.available()) Serial1.write(Serial.read());
}

```

# Answer
> 3 votes
Just hook up the serial pins from the bluetooth module to the corresponding Pro Micro pins: TX to RX and RX to TX. I hope this can help someone.

Then look for data like this:

```
void setup(){
   Serial1.begin(9600); // Init Hardware Serial port on pins 0 and 1 - Bluetooth
   Serial.begin(9600); // Init Virtual Serial Port - Machine

   Keyboard.begin(); // Init HID - Keyboard
}

void loop(){
   if (Serial1.available() > 0) {

     char myData = Serial1.read()

     // Send data from Bluetooth/Sensor to the Machine - Virtual Serial Port
     Serial.println(myData);

     // Emulate HID Device - Keyboard
     if ( myData == 0x7F ) { // Detect code of android backspace key
        Keyboard.write(0xB2); //  Convert received code char to PC/Linux ascii keycode for the backspace key. This can change between different OS!
     }

     else {
        Keyboard.write(myData);
     }

   }
}

```

# Answer
> 1 votes
You also may want to try the "SoftwareSerial" library. That way you can use almost any pins you want for serial comms. As a matter of fact, you can have a couple of serial ports.

Please do read up on the SoftwareSerial library though. It does have some restrictions.

---
Tags: serial, bluetooth, arduino-pro-micro
---


# Question
Title: ESP8266 stops responding when isolated relay is connected to AC tubelight
I'm completely new to Arduino and do not have an electronics background. I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.

I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.

I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html.

This is my code.

```
#include <SoftwareSerial.h>

#define DEBUG true
int relay = 8;
SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different
  pinMode(relay, OUTPUT);
  digitalWrite(relay, LOW);

  sendData("AT+RST\r\n", 2000, DEBUG); // reset module
  sendData("AT+CWMODE=3\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWJAP=\"xxxx\",\"xxx\"\r\n", 5000, DEBUG); // configure as access point

  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
}

void loop()
{
  if (esp8266.available()) // check if the esp is sending a message
  {

    if (esp8266.find("+IPD,"))
    {
      delay(1000);

      int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
      // the ASCII decimal value and 0 (the first decimal number) starts at 48

      if (esp8266.find("=="))
      {
        Serial.print("State : ");
        char c = esp8266.read();
        Serial.print(c);
        if (c == '1') {
          digitalWrite(relay, HIGH);
        }
        else {
          digitalWrite(relay, LOW);
        }
      }
      String webpage = "A";

      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend += webpage.length();
      cipSend += "\r\n";

      sendData(cipSend, 1000, DEBUG);
      sendData(webpage, 1000, DEBUG);

      String closeCommand = "AT+CIPCLOSE=";
      closeCommand += connectionId; // append connection id
      closeCommand += "\r\n";

      sendData(closeCommand, 3000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  esp8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {

      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}

```

The above code works perfectly until I connect the tube light to the relay. The power supply used in 9v 1A wall adapter.

The relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref\_=oh\_aui\_detailpage\_o03\_s00.

The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.

I'm really struggling hard to proceed here. Any help or hint would be much appreciated.

Thanks in advance.

# Answer
> 0 votes
Finally I got this working using only ESP8266 and minor tweaks. I'll post the circuit here just in case if somebody is trying to do the same thing.

Please note that this was done as a POC and I'm not from an electronics background.

Kindly note the blue wire from the GPIO 01 to resistor and an LED. I had to do this because when the circuit is powered on a HIGH signal is sent from the GPIO and the relay is turned on. I think it is the default behaviour of ESP8266. To suppress this initial flow, I did this (There may be a better way to do this according to electronics experts).

Diode used is 1N4001 Diode

Decoupling capacitor is - 10nf/100V (0.01uf/100V) Box Capacitor - Polyester

Relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref\_=oh\_aui\_detailpage\_o05\_s00

Transistor is bc547.

Before connecting the devices, I flashed nodemcu firmware to ESP8266 so that I can write code in Lua script. Refer any of these to flash the firmware - https://www.youtube.com/watch?v=Gh\_pgqjfeQc https://www.youtube.com/watch?v=pp6O96B1-Jk

I used LuaLoader to transfer the following code to the ESP8266. http://randomnerdtutorials.com/esp8266-web-server/

I'm posting my init.lua below.

**init.lua**

```
wifi.setmode(wifi.STATION)
wifi.sta.config("<ssid>","<password>")

cfg =
  {
    ip="192.168.1.101",
    netmask="255.255.255.0",
    gateway="192.1681.1"
  }
  wifi.sta.setip(cfg)

print(wifi.sta.getip())
led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
 gpio.write(led1, gpio.LOW)
 gpio.write(led1, gpio.LOW)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
print("receive")
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf.."<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body><h1> Control Panel</h1>";
        buf = buf.."<p>Tubelight <a href=\"?pin=ON1\"><button>ON</button></a> <a href=\"?pin=OFF1\"><button>OFF</button></a></p></body></html>";
        local _on,_off = "",""

print(wifi.sta.getip())
        if(_GET.pin == "ON1")then

              gpio.write(led1, gpio.HIGH);

        elseif(_GET.pin == "OFF1")then
              gpio.write(led1, gpio.LOW);
        elseif(_GET.pin == "ON2")then
              gpio.write(led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
              gpio.write(led2, gpio.LOW);
        end

        client:send("HTTP/1.1 200 OK\r\n");
        client:send("Content-type: text/html\r\n");
        client:send("Connection: close\r\n\r\n");
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

```

If everything is running, connect your phone or computer to the same wifi using "`<ssid>`","`<password>`" and access the IP 192.168.1.101 to see a webpage with one buttons "ON" and "OFF". Click on it an check whether it is working.

# Answer
> 0 votes
I suspect that you've connected the relay wrong. I think that the LNP of the relay is supposed to be connected to D8 and the v+ to 5/3.3V and GND to GND....

# Answer
> 0 votes
If you are doing what you have said you are doing then I think the answer is so obvious no one will ever see it.

You say you have a 9V 1A power supply. Since you are powering the Arduino from this it is DC. Is that correct?

You are connecting an "AC Tube light" to the relay (which supports 1A 12V DC). If you are connecting an AC device to a DC supply then things probably do go wrong.

To test everything is working properly can you switch the AC light for a DC light?

I think you can get Relays with AC output and a DC Switching signal, but that will need a bit of research.

Hope that helps, if not comment and I'll try again.

---
Tags: arduino-uno, esp8266, relay
---


# Question
Title: Simple network protocol to communicate between N slave arduino and 1 central arduino?
i am looking to communicate text ( 40 char for each message ) between N arduino and a central one ( Communication is one way slaves to Master).I am looking for wire communication with 1 to 5 m distance.Does anyone know the best approach to do that ?

Vincent

# Answer
> 2 votes
You have quite a few options available to you as your requirements are filled by quite a few protocols, I am not going to list all. You can use things such as I2C, CAN, RS-485, RS-232.

You can find a few good examples from this EE.SE post from a search.

The CAN option is quite a good one for your application and is easy to set up and there are quite a few libraries available for the common chip MCP2525 and MCP2551. Yo can also get a 'shield' with this functionality from sparkfun.

The other options are discussed in the linked EE.SE post with regards to RS-485.

I2C can be implemented with the Wire library of arduinos and other libraries.

You can use RS-232, but I don't think it will be immune to noise at the distance you want, but you can still try. What you can do is use a multiplexer, such as this one CD74HC4067, and use it to multiplex the TX line from each node to the RX of the master.

From SFE's site:

> For example, you could use it to connect the TX pins of 16 devices to one RX pin on your microcontroller. You can then select any one of those 16 devices to listen to. If you want two-way communications, you can add a second board to route your microcontroller’s TX line to 16 device’s RX lines. By using multiple boards, you can create similar arrangements for I2C, SPI, etc.

You will probably want to add some sort of checksum/CRC to the data you send over the network too.

# Answer
> 0 votes
IMHO you should first decide your network topology.

If you want a "star" network, i.e. a network when every node is directly connected to the central one, you can use any protocol. Maybe even a multiplexed serial interface.

If you want a daisy chain interface or a bus one use can or RS485.

Personally I'd avoid I2C (it's good for on-board communication, but if the device is a few meters away the noise can break it).

My suggestion: use serial over half duplex RS485: you can get very low price physical interfaces. Since it is half duplex, only one can "speak", so the master first sends an address, then puts itself in listen mode and waits. The slave whose address was told puts itself in sending mode and sends the data.

This way you will have a bus (so you can simply attach a node to another node without having to place a wire till the masater) and you'll have a simple bus logic which will prevent the information to collide. And, most important, RS485 is very strong (up to 1km if I remember well).

CAN can (sorry) be simpler to use, since the anti-collision is "embedded" in the protocol, but it's a bit more complicated to use (you'll need a transceiver and to implement the whole logic in the microcontroller instead of using a dedicated peripheral like the serial interface).

---
Tags: arduino-uno, arduino-ide, atmega328, networking, atmega16u2
---


# Question
Title: HC-05 Bluetooth Module - INQ-Command doesn't work
For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

**The Problem**

I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)

Here are the steps that I am trying to do with the Arduino and HC05 module:

```
AT <-- confirms, that Command Mode is running successfully
OK

AT+ROLE? <-- 1 For Bluetooth Master Mode
+ROLE:1
OK

AT+CMODE? <-- 1 allows connecting to any BT address
+CMOD:1
OK

AT+INQM? <-- Show Inquiry access values
+INQM:1,1,48
OK

AT+INQ <-- Inquiry Bluetooth Device

```

After ~60 seconds, it just says "OK", but according to this tutorial or according to this youtube video it should display all Bluetooth-devices, that are ready to connect. The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).

**Why is the inquiry not working? What is wrong here?**

**The circuit is exactly like in this picture:**

For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates **AT-Command-Mode** According to this site, you can do it like that.

Here is my code, that I use, to communicate with the module. - It works good!

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';
int buf[64]; //buffer to store AT commands
int len = 0; //stores the length of the commands

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    delay(500);
    mySerial.begin(9600);
    Serial.println("BlueTooth is ready");
}

void loop()
{

  if(Serial.available())
  {
    len = Serial.available(); //store number of bytes to read
    for(int i = 0; i<len; i++) //store all bytes into the buffer
    {
      buf[i] = Serial.read();
    }
    for(int i = 0; i<len; i++)
    {
      mySerial.write(buf[i]);
      Serial.write(buf[i]);
    }
  }

  if(mySerial.available())
  {
    len = mySerial.available();
    for(int i = 0; i<len; i++)
    {
      buf[i] = mySerial.read();
    }
    for(int i = 0; i<len; i++)
    {
      Serial.write(buf[i]);
    }
  }

}

```

Here is a related question but the answer doesn't help.

# Answer
I did a factory reset of the device. That resolved the issue

```
AT+ORGL
AT+RESET

```

Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.

If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN **must remain** high.
> 2 votes

# Answer
Try this example from the datasheet:

```
AT+INIT
AT+INQM=1,9,48  // max of 9 devices, timeout of 61 seconds
AT+INQ

```

And use this in your loop() instead:

```
void loop() {
  while (Serial.available())
    mySerial.write(Serial.read());
  while (mySerial.available())
    Serial.write(mySerial.read());
}

```
> 0 votes

---
Tags: bluetooth, arduino-nano, remote-control
---


# Question
Title: connection between Arduino Uno with nRF24L01 and notebook with wireless card
My project intend to command an Arduino UNO by my notebook without cable. I thought to use a RF Nordic nRF24L01 cabled on an Arduino UNO, and to use the wireless card of my notebook to send command to it. Is it possible? Any solution? Is this hardware solution possible?

I need to send to Arduino four analog signals to setup the light of four led.

# Answer
> 2 votes
Absolutely no. Can you connect your bluetooth headset to the wireless router? No because even if they share the same band they "speak" different protocols. So why could you do that with the nRF24L01?

If you want to communicate with your PC you have three options:

1. Choose nRF24L01. In this case, since the PC does not have that device, you will need to make an adapter (the easiest one could be an USB adapter). You can connect a microcontroller to a USB to serial converter and to the nRF24L01 and use it as a bridge.
2. Choose Wifi. Then you'll need a new transceiver for the arduino UNO you are using (maybe the ESP8266, which is around 2$) but can be a bit more complicated for just sharing data (I never used it, though, so I can be wrong).
3. Choose bluetooth. Usually this is my preferred way to communicate with a board. Cheap (the HC-06 module is about 2-3 $) and easy to use (the interface is a plain serial).

Good luck ;)

---
Tags: arduino-uno, communication, nrf24l01+, wireless, linux
---


title: 3.95 TFT LCD SPI or parallel interface

text:
# Question
Title: 3.95 TFT LCD SPI or parallel interface
I would like to get one information about this TFT LCD module . This particular module works with parallel interface with arduino mega and uno.

I am trying to get rid of arduino in my project and use esp8266 itself. I have this module http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html

This has only the parallel interface pins mentioned which requires around more than 10 pins to make it work. Is there any possibility that there is an SPI interface supported for this one by making use of any of the existing pins for the parallel interface.

I don't think so but still can someone confirm that. If so I need to get SPI interface ready TFT LCDs.

Thanks,

# Answer
In general, no. The interface used by the chip is normally hard wired either in the connections to the Chip On Glass or in the connections of the shield (most commonly the former) and as such cannot really be changed.

You will need to either use a TFT screen that has the interface already set to SPI (and there are many) or use some form of SPI I/O expander to provide enough I/O pins to drive a parallel display.

Note that using SPI to communicate with a screen makes the screen updates considerably slower than using a parallel interface. The bigger the screen the slower it gets.
> 1 votes

---
Tags: arduino-mega, lcd, esp8266, spi
---


# Question
Title: pass class internal function as callback
I am trying to pass a class internal function as a callback function within the class. The error behavior is similar to this problem. Whatsoever, I was unable to construct working code based on that question's answer.

I try to pass over a callback function from within the class,in order to create a finite state machine, inspired by the examples I found on adafruit regarding multithreading. The idea is, that each state can call his successor. The class itself then represents the state machine and I just will call its update function.

While the following code does not resemble this utility, it resembles the problem in a minimal example (based on this larger codepiece):

```
class MyClass
{
  const byte theAnswer = 42;
  void (*myCallback)();

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }

  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

  void call()
  {
    myCallback();
  }

   MyClass()
  {
    setCallback(&MyClass::print_info);
  }
};

MyClass AClassOfItsOwn();

void setup()
{
  Serial.begin(9600);
  while (! Serial); // Wait until Serial is ready
}

void loop()
{
  AClassOfItsOwn.call();
  return;
}

```

I get the following error code returned:

> ...testscript.ino: In constructor 'MyClass::MyClass()':
>
> testscript:25: error: no matching function for call to 'MyClass::setCallback(void (MyClass::\*)())'
>
> ```
>      setCallback(&MyClass::print_info);
>
>                                      ^
>
> ```
>
> ...\testscript.ino:25:41: note: candidate is:
>
> ...\testscript.ino:6:12: note: void MyClass::setCallback(void (\*)())
>
> ```
>    void setCallback(void (*callback)())
>
>         ^
>
> ```
>
> ...\testscript.ino:6:12: note: no known conversion for argument 1 from 'void (MyClass::*)()' to 'void (*)()'
>
> ...\testscript.ino: In function 'void loop()':
>
> testscript:40: error: request for member 'call' in 'AClassOfItsOwn', which is of non-class type 'MyClass()'
>
> ```
>    AClassOfItsOwn.call();
>
>                   ^
>
> ```
>
> exit status 1 no matching function for call to 'MyClass::setCallback(void (MyClass::\*)())'

---

**fun times with polymorphism**

This is code we discussed during looking for a solution. I leave it here for future reference.

I tried creating an instance of this wrapper within the actual class to hold the callback, but that did not work either.

```
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  {
    myCallback();
  }

  void setCallback(void (*callback)())
  {
    myCallback = callback;
  }
};

class MyClass : public CallbackWrapper
{
  const byte theAnswer = 42;
  public:

  void print_info()
  {
    Serial.println(theAnswer);
  }

   MyClass()
  {
    CallbackWrapper::setCallback(&MyClass::print_info);
  }
};

```

trying to store the callback function in a wrapping class (also not working, `'((MyClass*)this)->MyClass::CBW' does not have class type`)

```
class CallbackWrapper
{
  void (*myCallback)();
  public:

  void call()
  { myCallback(); }

  void setCallback(void (*callback)())
  { myCallback = callback; }
};

class MyClass
{
  const byte theAnswer = 42;
  CallbackWrapper CBW();
  public:
  void print_info() { Serial.println(theAnswer); }
  void call() { CBW.call(); }
  MyClass()
  { CBW.setCallback(&MyClass::print_info); }
};

```

An update on why I want to change the callback function during runtime. Here I try to randomly change the callback function:

```
class MyClass
{
  CallbackWrapper CBW();
  public:
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CBW.call();
    if (rand() > 0.5)
    {
      CBW.setCallback(&MyClass::do_this)
    }
    else
    {
      CBW.setCallback(&MyClass::do_that)
    }
  }
   MyClass()
  {  }
};

```

For discussion with Michail

```
class CallbackWrapper
{
  public:
  void (*myCallback)();
  void call()
  { myCallback(); }

  virtual void setCallback(void (*callback)())
  {  }
};

class MyClass : public CallbackWrapper
{
  public:
  void setCallback(void (*callback)())
    { myCallback = callback; }
  void do_this() { Serial.println("doing this"); }
  void do_that() { Serial.println("doing that"); }
  void call()
  {
    CallbackWrapper::call();
    if (rand() > 0.5)
    { setCallback(&MyClass::do_this); }
    else
    { setCallback(&MyClass::do_that); }
  }
   MyClass()
  {  }
};

```

# Answer
Unless you specifically limit yourself to one single class for a callback (i.e., include the class name in the function pointer specification) then you can ONLY use `static` member functions as callbacks.

`static` member functions appear as a normal function, not a member function, so don't have the implied `MyClass *this` as a first parameter.

If you want to allow member functions that aren't `static` you will have to make use of *polymorphism* and have a single *base* class that all classes which provide a callback function will inherit from. Then you limit the callback function pointer to be members of that base class.

It is possible to do it if you are happy to limit to just one class, though the syntax is rather cryptic:

```
class MyClass
{
  const byte theAnswer = 42;
  void (MyClass::*myCallback)();

public:

  void call() {
    (this->*myCallback)();
  }

  void setCallback(void (MyClass::*callback)()) {
    myCallback = callback;
  }

  void print_info() {
    Serial.println(theAnswer);
  }

  MyClass() {
    setCallback(&MyClass::print_info);
  }
};

```

Using polymorphism you can only pass a callback function that is a member of the parent class, so it looks like that method may be out.
> 6 votes

---
Tags: programming, c++, arduino-ide, class
---


title: Delay function broken?

text:
# Question
Title: Delay function broken?
I noticed timing inconsistencies in my project, and further debugging pinpointed it to the problem below. The text should be updating every second, but the returned values are \>\> 1000ms.

To clarify, the text is not showing up every second. The delays between texts vary according to fluctuating start and finish values.

I'm using a Teensy 3.2. Changing the baud rate doesn't help.

Is my timing crystal busted? Is there a serial buffering issue? I don't know how to fix either of these.

Any help would be appreciated!

Edit:

Here's the code if anyone wants to test. I found that adding more delay functions screws the output up in completely unlinear ways.

```
unsigned long start, finished, elapsed;

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

void loop() {
  Serial.println("Start...");
  start = millis();
  Serial.println(start);
  delay(1000);
  finished = millis();
  Serial.println(finished);
  Serial.println("Finished");
  elapsed = finished - start;
  Serial.print(elapsed);
  Serial.println(" milliseconds elapsed");
  Serial.println();
}

```

Edit #2:

I thought it was worth showing everyone this screenshot. It looks like `delay(1000)` just isn't functioning at all.

Edit #3:

I debugged it with an LED and it blinked at exactly 1s intervals. It seems like `delay(1000)` works, so the problem must be related to the serial buffering. I also updated my software but that didn't help.

Edit #4:

New developments from further debugging:

* The problem is not reproducible on a different computer. The Arduino serial monitor on other computers displays correctly.
* Updating to the latest OSX, arduino IDE, and teensyduino did not help.
* Terminal 'screen' command surprisingly prints correct serial communication.
* Serial monitors from 3rd party apps, like CoolTerm and Arduino IDE do not work.

# Answer
After correcting the syntax error (missing semicolon) I tried your code on my Teensy 3.0. The results look OK to me:

```
Start...
1250
2250
Finished
1000 milliseconds elapsed

Start...
2250
3250
Finished
1000 milliseconds elapsed

Start...
3250
4250
Finished
1000 milliseconds elapsed

Start...
4250
5250
Finished
1000 milliseconds elapsed

Start...
5250
6250
Finished
1000 milliseconds elapsed

Start...
6250
7250
Finished
1000 milliseconds elapsed

Start...
7250
8250
Finished
1000 milliseconds elapsed

Start...
8250
9250
Finished
1000 milliseconds elapsed

```

---

Since the code you posted doesn't compile, can you re-test please with your posted code, assuming you add in the semicolon, and put a space before "milliseconds elapsed".

---

Further down my test I see this:

```
Start...
153258
154258
Finished
1000 milliseconds elapsed

Start...
154259
155259
Finished
1000 milliseconds elapsed

Start...
155259
156259
Finished
1000 milliseconds elapsed

```

Now are you talking about the "creep" in the start time? That doesn't totally surprise me, because the rest of the code must take *some* time to execute.

---

*I know this isn't an "answer" per se, but I can't post this much information into a comment.*
> 4 votes

# Answer
Since the subtraction's result (`finished - start`) displays alright, it means the right number is being stored in the variable, so it's Serial that is screwing up the task of printing it. Try reducing the baud rate to 9600 and try again.
> 0 votes

---
Tags: teensy, timing
---


# Question
Title: Arduino Micro blue light dimms and turns off when I plug in my circuit
I have a PING Ultrasonic Sensor, Adafruit Absolute Orientation Sensor, and a Continuous rotation servo. All pins are connected to an Arduino Micro. However because the micro only has one 5V output, I used a rail from a breadboard. I connected the + & - leads from all the devices to the rail and then plugged in two leads connecting 5V and GND from the Micro to the rail. My goal was two send power from the Arduino Micro down the rail to all three devices.

I plugged in the Micro, and instead of seeing green lights on the sensor (powered on), the blue light on the Micro turned off and the servo twitched. I have no idea why. Do I need external power for the 5V?

# Answer
> 0 votes
This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.

---
Tags: adafruit, arduino-micro
---


# Question
Title: Corrupted files generated by Arduino with SdFat library. How to avoid that?
I got:

with this sketch using SPI/SdFat+OneWire/DallasTemperature+EmonLib and no matter what I try I got corrupted files like this.

I even haven't attached my sensors yet :( I have tried with 3 SD cards so far, each formatted with SD Memory Card Formatter and each one has this problem.

There is a separate question like that (Corrupted files generated by Arduino with SD library. How to avoid that?) but it concerns SPI confict but here SD is my only SPI device on the bus.

Any ideas?

# Answer
> 0 votes
This SD shield has CS on D4, not D10

---
Tags: sd-card
---


# Question
Title: Arduino cluster functionality - feasibility advice for arduinos to communicate using variable-length long strings?
My apologies. This is my first time on this site and I wasn't even aware that it wasn't some sort of discussion forum until receiving the automated response message to my already submitted vague and open-ended question.

**Thank you Nick Gammon** for pointing out Wanago's very interesting project, and I am sorry I did not provide enough information to show the difference in requirements. His solution is quite strictly structured and rigid (not just physically). But I wish to provide a solution that might allow anyone to fairly easily create an ad-hoc collection of any available arduino compatible hardware - which could also allow use of ESP devices for additional functionality if wished, but would not require ESPs as a means of connecting nodes. There may be a better solution than your RS485 Rolling Master for connecting nodes, but yours is the best solution I have yet seen so far, and not least because of the minimal resources required.

**Thank you JBulmer** for your clear overview and assessment, which does now give me a point of focus. In order to pursue this, I must try to aquire sufficient skills to add some form of multiple-chunk protocol layer on top of Nick Gammons Rolling Master protocol. I don't know if I'll manage it because I'm a hacker not a programmer, therefore I would appreciate if I could give my reasons for trying, because I would very much value your opinion as to whether you think it would be worth my efforts or not.

Nicks protocol already provides auto-negotiating of nodes and takes care of most fault-tolerance type issues. I believe it auto-detects nodes and assigns them IDs which are stored in each individuals EEPROM, so he has already taken care of most of the connectivity side of things.

And I think the main reason for him using a defined message length was in order for all nodes to be able to poll in timeslot sequence for opportunity to transmit as master, which means it ought to be possible to somehow sync up re-constitution of split message blocks.

So apart from the protocol extension for handling of long strings, I don't see any other major obstacles which I can't imagine a solution for in principle even if not yet aware of how. I hasten to add that I am pushing myself way out of my comfort zone to try to achieve this because I think (though perhaps wrongly) that it might offer much benefit to ordinary arduino amateurs (such as myself) who I feel arduino is mainly aimed at. So the following example is not any specific requirement of mine, just something to illustrate some of the potential that could be offered to non-professionals - hopefully after the initial scene-setting, things can become more apparent...

The majority of arduino project examples use the serial monitor as a quick and easy way for user interaction, which can then be expected to need customising for more practical methods of input and output - but clustered nodes communicating serially might allow many project examples to be used almost as is.

An Infra-Red sender makes a good starting point. The IRremote library IRsendDemo.ino monitors the serial port for a keypress then calls a send routine, eg: irsend.sendSony. The incoming serial trigger could be made to be anything the user wished to use as a command, such as MyIRblaster, and could also include an equivalent text string of any required parameters for appropriate data conversion before use, ie: MyIRblaster Sony(0xa90, 12) All this can be developed and tested in independent isolation using the serial monitor, then when happy, add a 'common' block of RS485-based cluster-talk code, allowing any other node the ability to then send it a MyIRblaster command and parameter to action when needed.

As the IR arduino is using the IRremote library anyway, we may as well also give it an IRread capability, which wouldn't even require any associated trigger command.

It would be an advantage to be able to save IR signals somewhere though, but trying to squeeze on additional SD and FAT libraries as well as IRremote might be a step too far, so perhaps better just to add a separate SD node for storage. The SD node could have a file of saved IR codes, perhaps each with an asscociated corresponding simple text description such as TVmute, and have a suitable command+parameter capability added such as "SendBlaster (name)". This would allow any node to issue eg: "SendBlaster TVmute" to the SD node which in turn could issue a corresponding MyIRblaster Sony(0xa90, 12) command to the IR node.

And similarly to action any other types of node functionality for that matter - it would be relatively trivial to add some relays to the IR node if wished, and make the node recognise a "Relay (name)" command+parameter for instructing it to control any relay as required.

But it would also be just as easy (if not easier from a software point of view) to add a separate Relay node if wished. And similarly, even a Trigger node perhaps offering 64 channels of interupt-driven inputs - which also wouldn't need to recognise any incoming command, just simply be able to issue perhaps a 'Triggered' command plus appropriate triggered channel number as a lookup instruction to the SD node. Every trigger input could be assigned its own corresponding list of responses in its config file entry, which could include any of the functionality that any of the nodes could respond to.

Adding new functionality to the cluster would be as simple as adding another command keyword to a relevent nodes list of commands to be parsed for, which when matched would branch to an appropriate internal function.

So adding a "WriteLOG" command to the SD node (and having it parse for an accompanying "Details" parameter) could provide a facility for every node to be able to record events to an event log just by sending the serial command "WriteLOG (details)"to the SD node.

Commands don't have to be external, they could include any locally recognised macro-type commands for accessing any of the internal capability. So for instance the SD node could recognise a "Pause (duration)" instruction to invoke a non-blocking delay if wished. This could allow the SD node to send multiple IR code commands with pauses between each transmission. It might also recognise a 'No\_Retrigger (duration)' timer to prevent unwanted repeat triggering of PIRs etc.

To better appreciate the potential now, we could create a config file on SD that contains an appropriate channel entry # for every trigger input we might wish, be it IR receives, PIRs, switch contacts or whatever. The channel #3 doorbell entry could be something like this...

# 3 Doorbell, No\_Retrigger (3mins), MyIRblaster (TVmute), Relay (Porchlight) (ON), Relay (Doorbell) (ON), Pause (3secs), Relay (Doorbell) (OFF), MyIRblaster (TVun\_mute), Pause (5mins), Relay (Porchlight) (OFF).

If the SD node receives a 'Triggered Doorbell' instruction it simply parses the corresponding #3 entry and sends any extracted commands out for the other nodes to action as appropriate. In this case it would ignore subsequent PIR retriggering for 3 minutes, send commands to mute the TV, turn on the porch light, ring the doorbell for 3 seconds, unmute the TV, then turn the porch light off after 5 minutes. It could also easily include simple local conditional logic to only turn the Porchlight when dark etc, which could allow option for appropriate qualifiers to a commands parameters, ie: Porchlight (ON) (IF\_dark).

PIR sensors could select CCTV cameras, or even send IR commands to point a PTZ cam to preset positions, and all using just the same cluster functionality being used above.

A voice node might be added to givie an "Announce (message)" command, then add appropriate config entries to provide appropriate voice announcements for any triggered events.

Even amateurs could evolve quite sophisticated flexible ad-hoc systems without needing any rocket science, and without hardware constraints other than needing cheap RS485 adapters and sufficient memory for running the protocol and parsing out any commands plus conversion of any parameters.

Although the SD node in the example above is tending towards becoming a systems co-ordinator, it is still just essentially another cluster peer node. But perhaps there could be good grounds for trying to modify Nicks Rolling Master to take advantage of what benefits an SD intelligent controller might offer, such as newly connecting nodes automatically obtaining assigned IDs plus other 'characteristics' and 'behaviour' from the centrally managed SD config file.

I'm willing to roll up my sleeves and prepare for the long slog if the concept is considered realistic and worthwhile, but I would certainly welcome informed opinion as to whether it might be or not.

-------Original---------

I am looking into the feasibility of linking multiple Arduinos together to form a cluster of Arduino and ESP8266 nodes capable of sending sequences of plain text commands plus optional parameters to each other.

This could offer a mechanism for any node to be able to access the functionality of any other node without having local burden of that functionality.

For instance, only the SDcard node would require the libraries and overheads for accessing a centralised config file on SD card, but any of the other nodes could request appropriate entries from the config file whenever needed, or have ability to write event entries to a log file.

Similarly for an InfraRed node and its IR libraries, allowing any other node to send it plain text commands and parameters to transmit any required IR code even though the other nodes don't have local IR functionality themselves.

Basically, each individual arduino might just be considered a black box that does something useful and can be programmed to respond to certain external text commands (so in fact any other platforms with similar blackbox functionality could also easily be integrated to the cluster if wished). Each node would parse an incoming string for a command that matched any of it's own local list of recognisable commands (ie: IRsend \[code\]) then branch as appropriate with any extracted accompanying parameters.

A cluster could be built up to include any and all required arduino functionality even though all of that functionality could never be squeezed onto any single arduino.

So an automation cluster could include things like voice announcements, web access, X-10 firecracker control etc just by including the appropriate nodes. Then tomorrow a voice recognition node might be easily added - needing to do nothing more than just issue appropriate text commands to also invoke any already existing functionality.

In principle, anyone could have the capability for doing almost anything they might wish, so although I don't know if this cluster functionality idea can be practically achieved or not, but the possible potential offers much incentive for trying.

And Nick Gammons excellent RS485 Rolling Master article brings the possibility so tantalisingly close... but it uses fixed-length messages to achieve it's clever self-negotiating fault-tolerance, and I'm afraid I don't know enough to be able to merge variable-length long string capability with his enticing communications system.

So I would appreciate any suggestions, even just informed advice telling me to forget it because it cannot be done (cos at least then I'd be able to get some sleep!).

Thanks, Robin Baker.

# Answer
Someone (Wanago) has done a similar project here. However instead of ESP8266 he used I2C which sounds more practical to me.

See images:

He had the same basic idea - each board has a specific task, and the work is shared between them.
> 2 votes

# Answer
Many communication systems use fixed-length, or limited-length, data exchange at the lower levels. For example, the ethernet network, under TCP/IP, has a maximum package size of 1526 bytes.

However, that doesn't prevent us moving large chunks of data, e.g. a DVD across the Internet.

A common approach is to use a layered protocol suite. Each layer is responsible for providing a service to the higher layer by using the service of the lower layers.

We talk about layered protocols because it provides a powerful, yet simplified way of thinking about communication problems. Rather than get bogged down in lots of detailed issues which need to be solved to work, we try to organise the problem into simpler and simpler solutions. Eventually things which we can implement without too much difficulty can be built, then higher layers are built from the simpler capabilities of lower layers.

The highest level of your protocol would provide the sort of service you need. In this case, you want to be able to send long-ish string messages, so the highest level would do that by using a mid-level fixed-length service.

In its turn the mid-level fixed-length service might provide error-free fixed-length messages using a still-lower-level service which can move fixed-length messages, but can't correct some types of errors.

(This is just an illustration of the idea, please don't take this as a concrete suggestion on how to implement anything.)

So, don't think "I don't know enough to be able to merge variable-length long string capability with his enticing communications system"

Instead, ask the simpler question, "how could I use that existing fixed-length communication system to send variable length strings?"

The answer might be pretty simple if the underlying system guarantees the order that messages are received. For example, send a count of the message length (in one or more messages) then send that number of bytes. The receiver knows how much to expect, and needn't act to interpret the data until it is received.

Then how to tell the difference between the command and its parameters? The command might be the first 'parameter' in the string, and parameters come after it.

The way I interpret your question, there may be several problems beyond sending variable length strings. There are potential problems like: adding or removing nodes, nodes failing, allocating 'names' to services on nodes (so commands can be sent to the appropriate node), etc.

However, the fundamental problem of sending long strings over a fixed-length communication channel is straightforward, and can be solved in a few different ways (I mentioned one, above).
> 2 votes

---
Tags: programming, communication
---