# Question
Title: How to correctly pack an unsigned long from 3 unsigned chars?
I would like to use 652 unsigned long values on an Arduino Uno, but it doesn't look like there's enough memory. I thought about the splitting unsigned long values to 3 unsigned chars to store in PROGMEM which I can letter recall and join as unsigned long as needed.

I'm not super experienced with byte manipulations and I got myself stuck when trying to merge the data. When I try with one variable at a time, I get the expected output. The part I'm confused about is why do I get different values when using a variable as an array index for each value ? How can I fix this ?

Here's my test code so far:

```
#include <avr/pgmspace.h>
#include "flashData.h"

void setup() {
  Serial.begin(115200);
  unsigned long fromPROGMEM = (onsets1[0] << 16) | (onsets2[0] << 8) | onsets3[0];
  Serial.println(fromPROGMEM);

  unsigned long fromValues = (0x00 << 16) | (0x01 << 8) | 0xF3;
  Serial.println(fromValues);

  byte b1 = 0x00;
  byte b2 = 0x01;
  byte b3 = 0xF3;

  unsigned long fromBytes = (b1 << 16) | (b2 << 8) | b3;

  Serial.println(fromBytes);
  delay(2000);

  unsigned char c1,c2,c3;
  unsigned long value;

  Serial.println("data using same index:");
  for(int i = 0 ; i < 10; i++){
    c1 = onsets1[3];
    c2 = onsets2[3];
    c3 = onsets3[3];
    value = (c1 << 16) | (c2 << 8) | c3;
    Serial.print("index: ");
    Serial.print(i);
    Serial.print("\tvalue:");
    Serial.println (value);
    delay(10);
  }

  Serial.println("data using counter:");
  for(int i = 0 ; i < 10; i++){
    c1 = onsets1[i];
    c2 = onsets2[i];
    c3 = onsets3[i];
    value = (c1 << 16) | (c2 << 8) | c3;
    Serial.print("index: ");
    Serial.print(i);
    Serial.print("\tvalue:");
    Serial.println (value);
    delay(10);
  }
}

void loop() {

}

```

and flashData.h:

```
#ifndef _flashData_h_
#define _flashData_h_

static PROGMEM const unsigned char onsets1[652] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03};
static PROGMEM const unsigned char onsets2[652] = {0x01,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x25,0x26,0x28,0x29,0x2A,0x2B,0x2C,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,0x38,0x39,0x3A,0x3B,0x3C,0x3F,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x48,0x49,0x4A,0x4C,0x4D,0x4E,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x59,0x5A,0x5B,0x5C,0x5E,0x5F,0x61,0x63,0x64,0x65,0x67,0x6A,0x6B,0x6C,0x6D,0x6E,0x70,0x71,0x73,0x75,0x76,0x77,0x79,0x7C,0x7E,0x7F,0x80,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9E,0x9F,0xA0,0xA1,0xA2,0xA3,0xA4,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xC0,0xC2,0xC4,0xC6,0xC9,0xCB,0xCD,0xCF,0xD2,0xD4,0xD6,0xD8,0xDA,0xDB,0xDD,0xDF,0xE0,0xE2,0xE4,0xE6,0xE7,0xE8,0xE9,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF4,0xF6,0xF7,0xF8,0xF9,0xFA,0xFD,0xFE,0xFF,0x00,0x01,0x02,0x03,0x06,0x07,0x08,0x0A,0x0D,0x0F,0x10,0x11,0x12,0x13,0x14,0x16,0x18,0x19,0x1A,0x1C,0x1D,0x1F,0x21,0x22,0x23,0x25,0x28,0x2A,0x2B,0x2C,0x2E,0x30,0x31,0x33,0x34,0x35,0x38,0x3C,0x3D,0x3E,0x41,0x42,0x44,0x45,0x46,0x47,0x48,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x53,0x54,0x56,0x57,0x58,0x59,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x63,0x65,0x66,0x67,0x69,0x6A,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x75,0x77,0x78,0x79,0x7A,0x7B,0x7D,0x7E,0x7F,0x80,0x82,0x84,0x87,0x89,0x8B,0x8E,0x90,0x92,0x94,0x97,0x99,0x9B,0x9D,0xA0,0xA2,0xA4,0xA5,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB9,0xBA,0xBB,0xBD,0xBF,0xC0,0xC2,0xC4,0xC6,0xC7,0xC8,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDC,0xDD,0xDE,0xDF,0xE0,0xE1,0xE2,0xE4,0xE6,0xE8,0xEA,0xEB,0xED,0xEF,0xF1,0xF2,0xF3,0xF5,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFF,0x01,0x03,0x04,0x05,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x13,0x15,0x16,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x20,0x21,0x23,0x24,0x25,0x27,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x30,0x32,0x33,0x35,0x36,0x37,0x3A,0x3B,0x3C,0x3E,0x40,0x43,0x44,0x45,0x47,0x48,0x49,0x4A,0x4C,0x4D,0x4E,0x50,0x55,0x56,0x57,0x59,0x5A,0x5B,0x5E,0x5F,0x60,0x61,0x62,0x63,0x65,0x66,0x67,0x68,0x69,0x6B,0x6C,0x6F,0x70,0x71,0x72,0x73,0x74,0x76,0x77,0x79,0x7A,0x7B,0x7D,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x99,0x9B,0x9D,0x9F,0xA2,0xA4,0xA6,0xA8,0xAB,0xAD,0xAF,0xB1,0xB4,0xB6,0xB7,0xB8,0xBB,0xBD,0xBE,0xBF,0xC0,0xC1,0xC2,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCC,0xCD,0xCE,0xCF,0xD1,0xD3,0xD6,0xD8,0xDA,0xDC,0xDE,0xDF,0xE0,0xE1,0xE3,0xE4,0xE5,0xE7,0xE8,0xE9,0xEA,0xEC,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFE,0x01,0x03,0x04,0x05,0x07,0x09,0x0A,0x0B,0x0C,0x0E,0x10,0x12,0x13,0x14,0x15,0x17,0x18,0x1A,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x34,0x35,0x37,0x39,0x3C,0x3E,0x40,0x42,0x43,0x45,0x47,0x49,0x4A,0x4B,0x4C,0x4E,0x50,0x52,0x53,0x54,0x56,0x57,0x58,0x59,0x5B,0x5C,0x5D,0x5F,0x60,0x61,0x62,0x64,0x66,0x68,0x69,0x6B,0x6C,0x6D,0x6E,0x70,0x71,0x72,0x74,0x75,0x76,0x78,0x79,0x7B,0x7C,0x7D,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x8A,0x8B,0x8C,0x8D,0x8F,0x90,0x91,0x93,0x94,0x95,0x96,0x97,0x98,0x9B,0x9D,0x9F,0xA1};
static PROGMEM const unsigned char onsets3[652] = {0xF3,0x31,0x59,0x76,0x98,0xBA,0xDD,0xFF,0x43,0x66,0x88,0xAA,0xC7,0xEF,0x0B,0x2D,0x50,0x72,0x8E,0xB1,0xD3,0xF5,0x17,0x3A,0x5C,0x7E,0xA0,0xC8,0xE5,0x0D,0x29,0x6E,0x90,0xAC,0xD5,0xF7,0x13,0x35,0x58,0x7A,0x9C,0xB9,0xE1,0xFD,0x42,0x6A,0x86,0xA8,0xC5,0x0F,0x31,0x54,0x7C,0x92,0xB5,0xCB,0xF9,0x1B,0x43,0x60,0xA4,0xC1,0xE3,0x28,0x4A,0x72,0x8E,0xB1,0xD3,0xF5,0x17,0x34,0x5C,0x78,0xBD,0xDF,0x01,0x46,0x62,0x84,0xCF,0x0D,0x30,0x52,0x7A,0x91,0xD5,0xF7,0x1A,0x5E,0x86,0xA3,0xE7,0x26,0x5F,0x92,0xAF,0xF3,0x1B,0x32,0x5A,0x7C,0x9F,0xBB,0xE3,0x00,0x28,0x4A,0x66,0x89,0xAB,0xC7,0x0C,0x34,0x4A,0x72,0x95,0xB7,0xD9,0xFB,0x1E,0x3A,0x62,0x7F,0x9B,0xC3,0xE0,0x2A,0x52,0x69,0x91,0xB3,0xD5,0xF7,0x1F,0x36,0x58,0x80,0x9D,0xB9,0xE1,0xF8,0x42,0x65,0x81,0xA9,0xCB,0xE8,0x10,0x54,0x93,0xD2,0x16,0x60,0x9F,0xE4,0x28,0x6D,0xAB,0xF0,0x12,0x34,0x79,0xB2,0xDA,0x02,0x46,0x85,0xAD,0xCF,0xF2,0x0E,0x30,0x4D,0x75,0x97,0xB9,0xD0,0xFE,0x1A,0x65,0x87,0xA3,0xC5,0xE2,0x2C,0x4E,0x6B,0x8D,0xAF,0xD7,0xEE,0x38,0x5B,0x77,0xC1,0x00,0x45,0x67,0x89,0xAB,0xCE,0xF0,0x01,0x57,0x7F,0x95,0xDA,0xFC,0x1E,0x5D,0x7F,0x9C,0xE0,0x25,0x6F,0x91,0xAE,0xF2,0x14,0x3C,0x7B,0x98,0xBA,0x04,0x82,0xAF,0xCC,0x16,0x33,0x77,0x94,0xBC,0xD2,0xFA,0x1D,0x3F,0x61,0x7D,0xA6,0xC8,0xE4,0x29,0x51,0x8F,0xAC,0xCE,0xF0,0x13,0x35,0x57,0x79,0x9C,0xBE,0xE0,0x02,0x47,0x69,0x8B,0xCA,0xF2,0x31,0x53,0x75,0x98,0xBA,0xD6,0xF9,0x15,0x5F,0x82,0xA4,0xC6,0xE8,0x05,0x33,0x60,0x7D,0xBC,0xFA,0x3F,0x83,0xC2,0x0C,0x51,0x95,0xD4,0x18,0x5D,0xA1,0xE0,0x25,0x69,0xA8,0xD0,0xE7,0x0F,0x31,0x53,0x75,0x98,0xB4,0xDC,0xF9,0x1B,0x3D,0x5F,0x7C,0xA4,0xC0,0x05,0x21,0x49,0x88,0xD2,0xF4,0x11,0x55,0x94,0xBC,0xDE,0x1D,0x4B,0x62,0x8F,0xAC,0xF0,0x2F,0x57,0x74,0x96,0xB2,0xD5,0xF7,0x1F,0x3B,0x63,0x86,0xAE,0xC4,0xEC,0x09,0x47,0x8C,0xD0,0xF3,0x15,0x54,0x98,0xC0,0xE2,0x05,0x21,0x66,0x88,0xA4,0xD2,0xEF,0x39,0x72,0xBC,0xD9,0xFB,0x23,0x3F,0x62,0x84,0xA0,0xC3,0xF0,0x07,0x2F,0x4C,0x74,0x90,0xCF,0xF7,0x13,0x3B,0x58,0x74,0x9C,0xB9,0xDB,0x03,0x1F,0x6A,0x86,0xA3,0xED,0x0F,0x31,0x4E,0x76,0x92,0xB5,0xF9,0x27,0x38,0x7C,0xA4,0xC1,0x05,0x28,0x4A,0x8E,0xCD,0x11,0x3A,0x50,0x9B,0xBD,0xDF,0x93,0x24,0x40,0x68,0xA7,0x2A,0x58,0x74,0xB9,0xDB,0xF7,0x3C,0x5E,0x80,0xA3,0xC5,0xE7,0x09,0x2C,0x48,0x70,0x8D,0xD1,0xF9,0x38,0x54,0x77,0x9F,0xBB,0xDD,0x00,0x22,0x60,0x83,0x9F,0xE9,0x11,0x2E,0x50,0x72,0x95,0xB7,0xDF,0xFB,0x18,0x40,0x5C,0x7F,0xA1,0xB8,0x08,0x2A,0x46,0x6E,0x8B,0xAD,0xD5,0xFD,0x14,0x58,0x97,0xDC,0x20,0x59,0xA9,0xEE,0x32,0x71,0xB5,0xF4,0x38,0x77,0x99,0xC1,0x06,0x4A,0x6D,0x8F,0xAB,0xCE,0xF0,0x0C,0x34,0x57,0x79,0x95,0xBD,0xDA,0x02,0x1E,0x46,0x5D,0xA7,0xE6,0x25,0x6F,0xAE,0xF2,0x14,0x37,0x5F,0x7B,0xC0,0xE8,0xFE,0x21,0x43,0x6B,0x8D,0xC6,0x10,0x33,0x55,0x77,0x99,0xBC,0xD8,0x00,0x1D,0x45,0x5B,0x83,0xA0,0xE4,0x29,0x67,0x8F,0xAC,0xF0,0x18,0x35,0x63,0x79,0xB8,0xFD,0xC1,0x4D,0x6F,0x86,0xCA,0xF2,0x09,0x4D,0x92,0xBA,0xD6,0xF9,0x15,0x37,0x59,0x82,0xA4,0xBA,0xE8,0x05,0x27,0x49,0x6B,0x8E,0xAA,0xCC,0xEF,0x17,0x33,0x78,0xB6,0x01,0x3F,0x7E,0xC3,0xEB,0x07,0x4C,0x90,0xB2,0xD5,0xFD,0x19,0x5E,0xA2,0xBE,0xE1,0x03,0x25,0x47,0x64,0xAE,0xD6,0xED,0x15,0x31,0x59,0x76,0xB5,0xF9,0x1B,0x3E,0x7C,0xA4,0xC7,0xE9,0x0B,0x33,0x50,0x8E,0xB6,0xD9,0x01,0x11,0x56,0x7E,0x95,0xDF,0x9F,0x13,0x29,0x46,0x68,0x8A,0xAC,0xC9,0xEB,0x0D,0x2A,0x52,0x6E,0xAD,0xCF,0xF7,0x25,0x30,0x64,0x7B,0xA3,0xBF,0x09,0x42,0x8D,0xCB};

#endif

```

And here's what I see from Serial:

```
499
499
499
data using same index:
index: 0    value:1654
index: 1    value:1654
index: 2    value:1654
index: 3    value:1654
index: 4    value:1654
index: 5    value:1654
index: 6    value:1654
index: 7    value:1654
index: 8    value:1654
index: 9    value:1654
data using counter:
index: 0    value:4294945024
index: 1    value:4294962688
index: 2    value:12806
index: 3    value:28928
index: 4    value:4294948096
index: 5    value:4294964224
index: 6    value:14337
index: 7    value:30464
index: 8    value:4294940928
index: 9    value:4294951174

```

I see what I expect for first 3 values and also for data using same index, but no when using a variable as an index for the PROGMEM arrays.

What is going on and how can I fix this ?

**Update** Mikael's answer is the solution, but I will post a working snippet here for reference:

```
#include <avr/pgmspace.h>
#include "flashData.h"

void setup() {
  Serial.begin(115200);
  delay(2000);

  unsigned char c1,c2,c3;
  unsigned long value;

  Serial.println("data using counter:");
  for(int i = 0 ; i < 652; i++){
    c1 = (unsigned char) pgm_read_byte(&onsets1[i]);
    c2 = (unsigned char) pgm_read_byte(&onsets2[i]);
    c3 = (unsigned char) pgm_read_byte(&onsets3[i]);
    value = (((unsigned long) c1) << 16) | ((unsigned long)c2 << 8) | (unsigned long)c3;
    Serial.print("index: ");
    Serial.print(i);
    Serial.print("\tvalue:");
    Serial.println (value);
    delay(10);
  }

}

void loop() {

}

```

The key is not only explicitly casting the data read, but also correctly reading the the PROGMEM data.

# Answer
You can try (explict unsigned long values):

```
unsigned long fromValues = (0x00UL << 16) | (0x01 << 8) | 0xF3;
Serial.println(fromValues);

```

or:

```
value = (((unsigned long) c1) << 16) | (c2 << 8) | c3;

```

The issue is that the expression is implicit int and not long (as you are assuming). You need to tell the compiler about this.

An extra bonus comment: There is actually a 24 bit integer definition in AVR GCC according to the wiki, see Extensions, Types.

Cheers!
> 5 votes

# Answer
I got it to work by typecasting firmly and using multiplications:

```
  Serial.println("data using counter:");
  for (int i = 0 ; i < 10; i++) {
    c1 = onsets1[i];
    c2 = onsets2[i];
    c3 = onsets3[i];
    value = (uint8_t)c3 + (uint16_t)((uint8_t)c2*256)+(uint32_t)(c1*65536);
    Serial.print("index: ");
    Serial.print(i);
    Serial.print("\t");
    Serial.print(c1, HEX);
    Serial.print(", ");
    Serial.print(c2, HEX);
    Serial.print(", ");
    Serial.print(c3, HEX);
    Serial.print(" ");
    Serial.print("\tvalue:");
    Serial.println (value, HEX);
  }

```

The result:

> ```
> data using counter:
> index: 0    A1, F6, 0   value:A1F600
> index: 1    FC, A7, 0   value:FCA700
> index: 2    B5, 7A, B8  value:B57AB8
> index: 3    EF, DB, 0   value:EFDB00
> index: 4    14, F9, 0   value:14F900
> index: 5    D7, 7F, 0   value:D77F00
> index: 6    F2, 72, 1   value:F27201
> index: 7    6F, DB, 0   value:6FDB00
> index: 8    5E, 5E, 0   value:5E5E00
> index: 9    F0, E7, B8  value:F0E7B8
>
> ```
> 2 votes

---
Tags: arduino-uno, memory-usage, progmem
---


# Question
Title: Leostick Receiving message from Uno using USB jumpers cables
I have a Arduino Uno which is looping over Serial.println("$testmessage"). Connected to this is a USB cable that i have cut and soldered male jumper leads to . I need to receive this message ("$testmessage") from the Uno using this USB cable without using the leosticks usb connector. After receiving the correct messgae from the Uno i plan to use Serial to send data from the leostick to my pc.

I'm stuck trying to figure out how to receive this message from the Uno.

Currently the the USB 5v and ground is connected to the leosticks 5V, GND pins. The Uno powers on and the the tx led is flashing every 100 milliseconds.

Can i just plug the green and white wires from the USB cable into D0&D1 and except it to work?

(Uno plugs into usb cable in the image) https://i.stack.imgur.com/M0kbb.jpg

# Answer
While USB *is* a serial protocol, it's a completely different serial protocol than the RS-232-style logic-level serial protocol that the Serial library supports. So the approach mentioned in the question has no logical chance of working.

Also, the USB electrical signal is differential (double-ended, or line-to-line, rather than single-ended, or line-to-ground). So the mentioned approach has no electrical chance of working.

What may work is to wire from Tx on the Uno to Rxd1 on the Leostick, and from Rx to Txd1, unless that conflicts with the Leostick's USB-Serial link.
> 0 votes

# Answer
I don't think this has any chance of working. You can't use USB to interface between the two devices, as the Leostick can't work as USB host. Your best bet is to use (software) serial.
> 0 votes

---
Tags: arduino-uno, serial
---


# Question
Title: Controlling 2 relays with IR remote, push button and bluetooth - sort of works, need help!
I'm still very new to arduino and coding and having some difficulties trying to figure out what I am doing wrong here.

This program is to have control over 2 relays, using a combination of an IR receiver and a ir\_remotecontrol with pre-programmed buttons (ir\_remote buttons 1 = relay 1 toggle, button 2 = relay 2 toggle). A master momentary hard wired switch to override changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if only 1 relay is on toggle it off with first click of button then toggle both back on after second click of button. The Bluetooth module and android app is to also control relays the same as the ir\_remote via integers sent through the serial port.

It all sort of works at the moment...

If I just work the relays using the ir remote and the momentary switch it all works perfectly.

if I make sure the relays are in the off position using the remote switch and then use the Bluetooth it also works perfectly.

The problem only is when I use a combination of the ir remote or switch and the Bluetooth - things get weird - the Bluetooth commands seem to reverse and the relays start making a buzzing noise and the momentary switch muddles things up so basically it's all bad news! I've stared at this code for hours and tried a few different things but I just can't see what's wrong.

Let me know if I need to give a more detailed example of the errors I am having. Just thinking it is probably obvious for you pro's out there when you see my noob code!.

Any help would be greatly appreciated!

```
/*This program is to have control over 2 relays, using a cobination of   an IR reciever and remote control with pre programmed buttons    (ir_remote buttons 1 = relay 1 toggle, 2 = relay 2 toggle).
A master momentery hard wired switch to overide changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if 1 only relay is on toggle it off with first click of button then toggle both back on after sencond click of button.
Bluetooth module and andoid app to also control relays the same as the ir_remote.
 */
//include libaries, and initialise variables
#include <SoftwareSerial.h>
#include <IRremote.h>
#define irPin 8
#define RxD 7
#define TxD 6
#define relay1 13
#define relay2 12
#define buttonPin 2
SoftwareSerial blueTooth(RxD, TxD);
IRrecv irrecv(irPin);
decode_results results;
int comdata;
const int wait = 30;
int sensorValue = 0;
int sensorOut = 0;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState = 0;
int lastButtonState = 0;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup()
{
  blueTooth.begin(38400);                     //set bluetooth baud rate
  delay(500);
  irrecv.enableIRIn();                        //enable infrared recieve
  pinMode(relay1, OUTPUT);                    //setting relays 1 & 2 to output
  pinMode(relay2, OUTPUT);
  pinMode(buttonPin, INPUT);                  //setting momentery swith (overide) to inpt
  digitalWrite(relay1, relay1State);          //putting current status of relays into a variable
  digitalWrite(relay2, relay2State);

}

void loop()
{
  if (blueTooth.available())                  //setting a variable for bluetooth recieved serial commands
  comdata = blueTooth.read();

  if(comdata == '1'){

  digitalWrite(relay1, relay1State);          //if bluetooth receivs "1" toggle relay1state -- essentially relay 1 ON
  }
  if(comdata == '0'){
  digitalWrite(relay1, !relay1State);         //if bluetooth receivs "0" toggle relay1state -- essentially relay 1 OFF

  }
  if(comdata == '2'){
  digitalWrite(relay2, relay2State);          //if bluetooth receivs "2" toggle relay2state -- essentially relay 2 ON

  }
  if(comdata == '3'){
  digitalWrite(relay2, !relay2State);         //if bluetooth receivs "3" toggle relay2state -- essentially relay 2 OFF
  }

  if (irrecv.decode(&results)){                     //Start listing for ir commands, if set remote button code is recvived toggle the variable relay1State or relay2state
  switch (results.value){
      case 0xFF30CF:
        relay1State = !relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        relay2State = !relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
    }

  int reading = digitalRead(buttonPin);          //debounce used to help with faulse readings from momentery switch
  if (reading != lastButtonState) {
   lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

  if (reading != buttonState) {
      buttonState = reading;

  if (buttonState == HIGH) {                      //if the momentery switch is pressed toggle masterstate which is both relay 1 and relay 2 state
     masterState = !masterState;
     relay1State = masterState;
     relay2State = masterState;
      }
      }
    }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;

}

```

# Answer
> 1 votes
Looks like it could be reusing the old comdata values in the first part of loop(). Maybe make the first chunk:

```
   if (blueTooth.available()) {
      comdata = blueTooth.read();
      switch (comdata) {  // set state variables based on bluetooth
      case  '0':  // if bluetooth receivs "0" clear 1
          relay1State = 0;
          break;
      case  '1':  // if bluetooth receivs "1" set 1
          relay1State = 1;
          break;
      case  '2':  // if bluetooth receivs "2" set 2
          relay2State = 1;
          break;
      case  '3':  // if bluetooth receivs "1" clear2
          relay2State = 0;
          break;

      case  '4':  // if bluetooth receivs "4" toggle 1
          relay1State = !relay1State;
          break;
      case  '5':  // if bluetooth receivs "5" toggle 2
          relay2State = !relay2State;
          break;
      case  '6':  // if bluetooth receivs "6" toggle master/both
          masterState = relay1State = relay2State = !masterState;
          break;
      }  // end of switch
      // apply state variables to outputs
      // (could be left to the end of the loop() code)
      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
   } // end of bluetooth processing

   ... /// IR processing code

   // debounce button and toggle masterstate & set state vars accordingly
   // see http://arduino.stackexchange.com/questions/17443/how-to-simulate-delay-to-debounce-mechanical-button-using-millis
   //

// re-ensure output state matches the state variables.
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
}

```

As it is, the if() statements trigger on the state of the last read comdata, not on the whether a new command was read.

Also, maybe check whether the toggling comments match the code or the code matches the intention properly.

# Answer
> 2 votes
Only the button changes `relay1State` and `relay2State`. The IR and BT only change the pin using digitalWrite. But then in the last 3 lines, the pin is changed back to the value of `relay1State` and `relay2State`.

I think for the IR and BT you need to change e.g. `digitalWrite(relay2, !relay2State);` to `relay2State=false;` etc.

PS It there a pull-up/pull-down resistor on the button pin?

---
Tags: arduino-uno, bluetooth, relay, remote-control
---


title: Arduino Variable Data Type?

text:
# Question
Title: Arduino Variable Data Type?
Is there a variable data type available for Arduino? I have a class that should have a member that will differ in data type, in the past I have used the "variable" keyword in c++ but when I tried to use it the compiler yelled at me. I searched online and found a couple of articles that mentioned that if you are using an alternate GUI (I am using eclipse mars) that you can enable the feature but I can not find the correct settings as the examples I had found were for Juno and below.

Here is an example of what I am trying to accomplish

```
class DisplayItem{

   public:
   variant *displayVar;

   void Display(){
      Serial.println(displayVar);
   }
}

int intDisplay;
String strDisplay;

DisplayItem item();
item.displayVar = &intDisplay;
item.Display();
item.displayVar = &strDisplay;
item.Display();

```

I realize I could create a overloaded function to display different data types but it would be allot easier if I could simply assign a reference to a variant datatype and reuse the variable.

---

**Edit**

So after looking through the answers I think I have this figured out. I needed to keep track of which variable was being set, I put together a quick example in hopes it will help someone else out with the same question.

```
class DisplayItem{

   private:
   int iVarType;

   union{
      int *i;
      float *f;
   } displayVar;

   public:
   void SetVar(int *var){
      displayVar.i = var;
      iVarType = 0;
   }

   void SetVar(float *var){
      displayVar.f = var;
      iVarType = 1;
   }

   void Display(){
      if (iVarType == 0){
         Serial.println(displayVar.i);
      }else if (iVarType == 1){
         Serial.println(displayVar.f);
      }
   }
}

int intDisplay = 1;
float floatDisplay = 0.123;

DisplayItem item();
item.SetVar(&intDisplay);
item.Display();
item.SetVar(&floatDisplay);
item.Display();

```

Will Display:

```
1
0.123

```

# Answer
> 2 votes
For the situation illustrated in the question – displaying data – polymorphic functions already exist, and might as well be used in this case. Specifically, use the `Streaming.h` contributed library. It adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size. You can install it via `Streaming5.zip` from arduiniana.org .

In other cases, a `union` data structure allows treating an area of memory different ways. Wikipedia's *Union type* article explains the general idea. See eg tutorialspoint.com/cprogramming for `union` syntax and usage. For some reason, arduino.cc's Language Reference page hasn't got `union` on its list of language features. However, mcgurrin.com has a page called *There is Power in a Union* that codes a simple Arduino C example two ways (where `bearing` is an `int`):

```
higherByte = compass.read();
lowerByte = compass.read();
bearing = ((higherByte<<8)+lowerByte)/10

```

-vs-

```
union Data {
  byte b[2];
  int value;
};
...
union Data data;
data.b[0] = compass.read();
data.b[1] = compass.read();
bearing = data.value/10;

```

# Answer
> 1 votes
No, there is no such thing. The whole concept of "type" only exists during compilation, not at run-time.

However, you can "emulate" it using "setters" and keeping your own internal state information:

```
class Thing {
    private:
        String *strvar;
        int intvar;
        int type;

    public:
        void set(int val) {
            intvar = val;
            type = 1;
        }
        void set(String &str) {
            strval = &str;
            type = 2;
        }
        void Display() {
            if (type == 1) {
                Serial.print("Value: ");
                Serial.println(intval);
            } else if (type == 2) {
                Serial.print("String: ");
                Serial.println(strval);
            } else {
                Serial.println("Something went wrong");
            }
        }
};

Thing t;
String s = "This is a string";
int i = 23;
t.set(s);
t.Display();
t.set(i);
t.Display();

```

The multiple functions named the same but with different parameters are *overloaded*. The best match is picked at compile time.

---
Tags: programming, arduino-mega, data-type
---


title: Arduino Mega, ST7920 using COSA

text:
# Question
Title: Arduino Mega, ST7920 using COSA
I am trying to learn and understand the COSA Library using a 12864ZW (ST7920) 128X64 LCD Display. Right now I am able to use the LCD using the u8glib but also found that COSA has a library for the ST7920 Display, I originally used this tutorial to get things working.

The main problem that I have now is in the ST7920 Documentation there is a schematic that shows how to hook up a ST7920 Compatible LCD. The first tutorial only uses 3 lines from the Mega and the Cosa is using what looks like 6 lines.

Looking at the header file, it looks like it is derived from the HD44780 Class and what I can gather is pins 16 and 4 are hard coded for something? I am not quite clear on how to use the Cosa version of the library. Can someone please give me a explanation and perhaps a explanation on how to get this working using Cosa?

# Answer
> 1 votes
The Cosa ST7920 library uses text mode only (16X4). The ST7920 class is controlled though an adapter. There are several adapters available depending on how you wish to connect to the Arduino. They range from parallel 4-bit to SPI with shift register. The adapters implement the interface HD44780::IO. There are several LCD examples. The CosaLCDbench shows the possible configurations with LCD and Adapters. Please see the file for further details.

---
Tags: arduino-mega, lcd, st7920
---


# Question
Title: Prevent Switch case from not being complete
I got this program. It controls a refrigeration room using a ds1280 temperature probe.

The thing is, sometimes the probe reach 7.00°C then the refrigerattion cycle start (refrigeration cycle is on a switch case statment) and then the probe read 6.75. So the refrigeration don't complete its start and leaves part of the system in wrong mode.

How can I add some guard to ... once the switch case statment don't being interrupted by anything unless complete the on in this case or the off in other case.

Here are the most resembling parts of the code.

```
void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

void turnOnCompressor(){

/*
This subrutine is intended to stop the refrigeration cycle
in the most ordered way, and keeping the refrigerant on
the high side of the system.
*/

// boolean refrigerattion = false; // var to handle ref status only once
// byte compOn = 0;
// byte pascomOn = 0; //to chek if the variable has updated.
// unsigned long  comOnTime  = 0;
// unsigend long  comOnDelay = 1500;
// unsigend long  comOnCT    = 0;     //the current time of the compressor.

//------for debug only
//Serial.print("comOnCT  =             "); Serial.println(comOnCT);
//Serial.print("comOnCT - millis()  =  "); Serial.println(millis() - comOnTime );

// Serial.println("INICIANDO REFRIGERACION");

if(refrigerationBegin == true )
{

if(refrigerattion == true && millis()- comOnTime  >= comOnDelay ){
   compOn ++;
   comOnTime = millis();
 /*
 //--------for debug only
 Serial.println("---------------------");
 Serial.print("Var compOn "); Serial.println(compOn);
 Serial.print("comoON  "); Serial.println(compOn);
 Serial.print("pascomON"); Serial.println(pascomOn);
 Serial.println("---------------------");
*/
}

if(compOn > pascomOn ){

  switch(compOn){

  case(1):
  lcd.setCursor(0,0);  lcd.print(F("      CICLO DE      "));
  lcd.setCursor(0,1);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  break;

  case(2):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 1       "));
  digitalWrite(dif1, LOW);
  break;

  case(3):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("       VENT 2       "));
  digitalWrite(dif2, LOW);
  break;

  case(4):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      SOLENOIDE     "));
  digitalWrite(solenoid, LOW);
  break;

  case(5):
  lcd.setCursor(0,0);  lcd.print(F("    REFRIGERACION   "));
  lcd.setCursor(0,1);  lcd.print(F("     ENCENDIENDO    "));
  lcd.setCursor(0,2);  lcd.print(F("      COMPRESOR     "));
  digitalWrite(compressor, LOW);
  break;

  case(6):
  lcd.setCursor(0,1);  lcd.print(F("                    "));
  lcd.setCursor(0,2);  lcd.print(F("                    "));
  refrigerattion = false;
  refOff = true     ;       // to cycle only once the set of the instructions per cycle.
  compOn = 0;
  cycleFansvar = false;        //bool to chek the refrigerattion has stop
  //--------------------------------
  //refrigerattion = true; add this variable at the end of the off routine to cycle the
  //operation otherwise will just start once
}
}
}

refrigerationBegin = false;
}

```

# Answer
> 1 votes
Are you trying to control by temperature or by time?

(I'm finding the code hard to follow. There seem to be 2 copies of it, and the comments in turnOnCompressor() seem to contradict the function name. I also don't see any code that mentions temperature.)

If this is temperature controlled, you need a dead-band - a temperature range bounded by a high- and a low setpoint. If you have a single setpoint, the system will jitter as air-circulation and electrical noise make the temperature appear to alternate above and below setpoint. The turn-on setpoint needs to be higher than the turn-off setpoint. You'll need to experiment to find out how far apart they need to be for the system to be stable.

---
Tags: programming, arduino-mega
---


# Question
Title: Can I use 5V 1A Adapter to power Arduino UNO?
I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).

My question is can use any of these to power my Arduino UNO with a barrel connector?

What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.

# Answer
> 2 votes
If we look at technical specifications, it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (**never go above 20V**). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.

---
Tags: current
---


title: ATtiny85 SPI with Timer 0

text:
# Question
Title: ATtiny85 SPI with Timer 0
Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.

What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.

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

int main(void){
    DDRB = (1 << DDB2) | (1 << DDB1); // USCK & DO Output
    DDRB &= ~(1 << DDB0); // DI Input
    PORTB |= (1 << DDB0); // Pullup Resistor for DI

    TCCR0A = (1 << WGM01); // Timer 0 in CTC Mode
    OCR0A = 0xFF; // Timer 0 Compare A
    TCCR0B = (1 << CS02) | (1 << CS00); // Prescaler / 1024

    USICR = (1 << USIWM0); // USI 3 Wire Mode
    USICR |= (1 << USICS0); // Timer 0 for USI 4-bit Clock Source

    USIDR = 0x7F; // Why you no go? :c

    USISR |= 0x08; // Set Counter to 8
    USISR = (1 << USIOIF); // Clear Counter Overflow

    while(1);
    return 0;
}

```

# Answer
Did you forget to load the counter and clear flags in USISR?
> 0 votes

---
Tags: timers, attiny, spi
---


title: Measuring acceleration in g's

text:
# Question
Title: Measuring acceleration in g's
I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial. I have two questions, which are;

* Can I measure fractional values, like .8 in acceleration due to gravity?
* when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?

I am using analog pins and 3.3V power supply from Arduino to power the sensor.

# Answer
> 0 votes
If you read the datasheet you can quickly find that the output of the device is 300mV per *g*. That means:

1. Read the analog value
2. Convert it to millivolts
3. Divide it by 300

The result is the *g* value. If you do it using floating point then yes, you get fractions of a *g* resolution.

For instance:

```
float mv = analogRead(0) / 1023.0 * 5000.0;
float g = mv / 300.0;

```

If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step. Divide that by 300 and you get a resolution of 0.01628g

As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down. It's all in the datasheet \- it makes for good reading, I suggest you take a look.

---
Tags: arduino-uno, sensors
---


# Question
Title: Reset Arduino Uno R3 from Serial when it freezes (stops looping)?
I have an Uno that loops processing serial commands and reading from a DHT11 sensor. For whatever reason, the device often stops responding. I put an LED on a pin and gave it a blink to see whether the loop is running, and sure enough the loop() stops running (the LED stays ON or OFF, depending on when it froze). I enabled the watchdog at 2 seconds, but it does not reset the device \[it still stays frozen, even though wdt\_reset() is called at basically the same time as the blinking LED is toggled\].

I then tried various combinations of BaudRate=1200 (or 9600), Open(), Close(), DtrEnable=true \[on both the Uno and the Mega\], yet none of the combinations would make the device reset. The device *will* reset, however, if I re-upload the sketch using the Arduino IDE. I would like to emulate this resetting functionality from my own program's code. Reading on the official site, it sounds like the Baud=1200 reset feature is available only on certain models (not the Uno or Mega).

My code is by no means simple as I am no beginner when it comes to programming. This is the first time, however, that I have had a finicky unit that freezes all the time (say between 10 minutes and 2 hours into running). I merely want to reset the unit from the PC using code, like the Arduino IDE does. On the other hand, if the watchdog worked correctly, that would be fine as well. At the same time, I am not that experienced with electronic circuits, so making a circuit that would "press" the "reset" pin when the LED stops blinking is not something I am quite ready to do. Plus, I do not want to add a bunch more components if the job can be done through code.

On a side note, the Serial connection appears to be fully functional the whole time. The LED on the unit that indicates receiving from the PC continues to function whenever I send data to the device. I can connect and reconnect without any apparent issues. Plus, the Arduino IDE has no problem uploading new sketches and resetting the device. Naturally, no data is received from the device after it freezes (until it gets reset, of course).

**Update 1**: I made a simple sketch (see below) that would run for about 20 seconds and then let the WDT watchdog timeout do its thing. Result: (a) Running the code on an Arduino-brand Mega 2560, the device simply resets every 20 seconds and keeps blinking; (b) Running the code on a generic (made in China) Uno R3, at timeout the L light turns on and the device becomes completely unresponsive (not even the reset button or the Arduino IDE can save it); It must be unplugged to reset it. (c) Running the code on an Arduino-brand Uno R3 works as expected, just like on the Mega 2560.

```
#include <avr/wdt.h>
void setup() {
  wdt_reset();
  wdt_enable(WDTO_2S);
  wdt_reset();
  pinMode(A5, OUTPUT);
  delay(1);
  Serial.begin(125000);
}
unsigned int LoopCount = 0;
bool TestLED = false;
void loop() {
  if(LoopCount % 300 == 0){
    TestLED = !TestLED;
    digitalWrite(A5, TestLED ? HIGH:LOW);
    if(LoopCount < 20000)
      wdt_reset();
  }
  delayMicroseconds(1000);
  LoopCount++;
}

```

Nevertheless, I still would like if someone could provide a solution in terms of resetting a frozen generic Uno from Serial in .NET code -- not the WDT frozen, but the normal frozen (of unknown origin). I may be the one coding, but I'm unfortunately not the one deciding which units are put into production.

**Update 2**: I switched the EasyDriver to its own power source, where the only things in common with the stepper and the Arduino were the ground and the two signal wires. The generic Uno board ended up being even more problematic, going into a new freeze mode (after just a minute or two, pretty reliably) where the L light would blink very quickly. I'm not sure whether it had anything to do with toggling of the DtrEnable property, but I decided to stop messing with the generic board for the time being. The name-brand Uno appeared to freeze occasionally or malfunction as well with the original wiring, but the Watchdog did its thing and reset it straight away every time. Also, I tried toggling the RtsEnable property with the generic board, but it didn't seem to make a difference. The board would become unresponsive and unrevivable, even from the Arduino IDE.

Some more background: The reliability problem only really started to surface when I hooked up the DHT11 temperature sensor, *even though* the freezing would tend to happen only when the stepper motor was running. I have the DHT11 hooked up exactly as advocated by Adafruit, and it tends to read correctly most of the time.

**Update 3**: I was thinking maybe the SainSmart Mega2560 would be different from the no-name generic I was using. After getting one and hooking it up, I have found it to have the exact same problem. The SainSmart CPU crashes between 5 and 15 minutes into running. The serial chip (or module) keeps going as you can still see the serial lights change when you send to it. However, the on-board reset button does nothing, and the Arduino IDE cannot upload to the device or reset it. Only a power cycle can save it.

# Answer
> 3 votes
You can reset the Uno over the serial link by toggling the DTR line. How you do that depends on what platform and language you are using. There is a capacitor between the line and the reset pin, so the toggle must last a minimum ammount of time. 0.5 seconds works.

This is ok for just a quick fix hack, but probably better in the long run to (1) figure out why the code is crashing, and/or (2) figure out why WDT is not working.

# Answer
> 0 votes
Since we don't know the nature of the freeze-up, and the clone-board behaves differently than an Arduino-brand board but we don't know how or why, there's not much more we can offer beyond suggesting you recommend a higher quality board to your management. You surely have reason enough to do so.

The last remaining thing I can think of, and it's kludgey work-around (shame on me) is:

You know the board will come back after a power-cycle. Kludge up a 555 timer circuit that powers-down the board for a second or two, and trigger it from the DTR line. This is really a broken fix for a broken board!

If my management or a client was intent on shipping a product built with these, I'd have to speak up about potential damage to the company's reputation - and possible liability, if a failure could have real consequences someone - and if necessary, write my objections to the next three levels above me. This board should not be shipped in a product.

---
Tags: arduino-uno, serial, arduino-mega, reset
---


# Question
Title: Multiple rgb control plus calculation help
Hi me and a friend is making a computer shelf with leds in the woodwork, were using a special glue for the plexiglass in the shelf which means we're using individual rgb leds, four leds for each window (3 windows) and what I need help with is, amount of voltage, ampere, code and how to connect all this up. I've used 123d.io to sketch something up but I'm struggling with getting proper strength in the leds.

(code https://puu.sh/lI6PC/e214028b07.txt)

Aswell as some of them change colors as the picture here shows:

I'm very new at these things so I really appreciate all help and advice (and from an earlier post, reason for not using strips is purely based on the method of build, the shelf will not sit correct if the strips were in use)

# Answer
It's not advised to connect leds in parallel, with only one common resistor. Slight difference in forward voltage of the leds will create big current differences. This will make some leds appear brighter that neighboring leds. It can also damage the brighter led since too much current can flow through them. So you need to add a resistor to each led, and common the other side of these resistors to the transistor.

Second bigger error is that there isn't any resistor between the arduino pin and the base of the transistor. Without it there is nothing limiting the current going into the base, which could fry the arduino pin.
> 2 votes

# Answer
There's a lot to unpack here, this is actually several questions.

First of all, the way your circuit is designed currently, your data pins are connected via the transistors to ground. This means if you set a pin high, or use analogWrite(), the Arduino will pump as much current as it can get, directly into the ground. This can damage the Arduino. Put a resistor between the pin, and the transistor.

The first point is that you are using several LEDs. If you want to control them separately, you will need 3 pins per colour. AnalogWrite() only works on PWM pins - if you look at your Uno, you can see that some of the pins are marked with a ~ (pin 3,45,6,9,10,11) - these are the only ones you can (easily) use. Since there are 6 of them, you could only run 2 LEDs this way. You could either run the project on multiple arduinos (1 Arduino per 2 "windows"), or you can get a chip to do the heavy lifting for you. I am working on a similar project, and am using a TLC5940 - there is a thorough tutorial at http://playground.arduino.cc/Learning/TLC5940 \- they also save you from having all the resistors and transistors, and each TLC5940 will run up to 16 LED-pins (3 per LED, so you can run up to 5 "windows"). They are also designed to daisy chain, so if you need more, you can just add another chip; no extra Arduino pins to worry about. 3 of them can run all 12 of your LEDs independently.

The next item to be aware of is that there is a limit to how much power (in Amps, or milliAmps) you can draw from a given power source. Each part will use a certain number of millAmps. The spec sheet for your parts should tell you how many. LEDs are generally around 20mA (per colour), but this varies - check the datasheet. An Arduino uses about 50mA. This means that if all 12 of your LEDs are bright white, you will be drawing 50mA+(20mA * 12 * 3) = 770mA.

How does this affect you? Well, if your project draws less than the power source can provide, you're golden! You can't provide "too much current" to a component - it will draw what it needs. When you draw more than the supply can supply, you get one of two results. If it runs on the mains, it will overheat, and eventually either burn out, or catch fire (there are exceptions to this, but you'd better be sure of your facts before risking it!). How long this takes, depends on how much current you are drawing, and how much margin there is on the power supply. In the case of a battery, the battery will drop in voltage, and will also heat up (but is much less likely to catch fire). I suspect this is happening here. If you have a multimeter, you can hook up your circuit to batteries, and then measure the voltage between + and - on the batteries.

P.S - +1 to @Gerben - you need one resistor per LED leg (except common). If you use the TLC5940, you would need 3 TLC5940s; as I said before, you can daisy-chain them. This does, however, mean that you can control each LED individually.
> 1 votes

---
Tags: arduino-uno, rgb-led
---


# Question
Title: Arduino UNO inconsistent I2C register reading from ArduCam
I have an Arducam hooked up to an Arduino UNO. The code I am running looks like this:

```
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"

const int CS = 10;

ArduCAM myCAM(OV5642, CS);

void setup() {
  uint8_t vid, pid;

  Wire.begin();
  Serial.begin(115200);
  pinMode(CS, OUTPUT);

  SPI.begin();

  //Check if the camera module type is OV5642
  myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);

  if ((vid != 0x56) || (pid != 0x42))
    Serial.println("Can't find OV5642 module!");
  else
    Serial.println("OV5642 detected.");

...

```

and the rdSensorReg16\_8 function from the library:

```
//I2C Write 8bit address, 16bit data
byte ArduCAM::wrSensorReg8_16(int regID, int regDat)
{
    Wire.beginTransmission(sensor_addr >> 1);
    Wire.write(regID & 0x00FF);

    Wire.write(regDat >> 8);            // sends data byte, MSB first
    Wire.write(regDat & 0x00FF);

    if(Wire.endTransmission())
    {
        return 0;
    }

    delay(1);
    return(1);
}

```

The problem I am experiencing is that sometimes I will receive the "Can't find OV5642 module!" message, and other times everything is fine and I receive "OV5642 detected" (I have the OV5642 module hooked up, so it should always be returning detected).

I have tried using different cables to connect the camera to my UNO. I have tried swapping out my USB cable. I have tried using a 12v wall adapter to power the UNO. None of these options permanently solved my problem - I still receive both messages interchangeably.

One thing that *seems* like it is adding consistency is when I change which USB port on my computer the cable is plugged into. Every time I switch the USB port I am using, it seems like for the first run I'll receive the successful "OV5642 detected" message, but after reseting the Arduino or re-uploading my sketch, I go back to the "Can't find OV5642 module!" message.

Can anyone help me troubleshoot why I am getting inconsistent readings? Thank you.

# Answer
> 0 votes
I would start by adding a short delay before SPI.begin() and verifying that the power drawn does not exceed 500 mA.

The product description describes the power on sequence. OV5642

---
Tags: arduino-uno, i2c, spi
---


# Question
Title: Read gyro output values with other programming languages
I have a large quantity of gyro values and I read them through the Arduino serial monitor. I'd like to know how I can use these values in other programming languages (such as C/C++/Java) after the values are read. Are there particular libraries for the Arduino that could help me in this way?

# Answer
> 1 votes
If your Arduino sketch is printing the data as ASCII numeric strings (human-readable), then any language with support for reading and writing to a serial device can interact with your Arduino on the port it is connected to, and collect the gyro data as it is being sent.

# Answer
> 1 votes
Yes, of course you can.

In C/C++ there are different libraries depending on your operating system - that is if you even really need a library to help you at all (in Linux you certainly don't - you just use standard system calls - open, read, etc).

In Java there are a few different ones. RXTX is a common (though not very good) one. Personally I ise JSSC(Java Simple Serial Connector) since it contains the JNI files for all the main platforms - you don't have to get the right separate library packages for your specific OS like you do with RXTX.

Then of course there's things like PySerial for Python, Device::SerialPort for Perl, and whatever nonsense Microsoft have created for C# and their .NET stuff.

So in general: pick a language you are comfortable with, then ask Google how to use the serial port in it.

---
Tags: arduino-uno, serial
---


# Question
Title: What is better: one sprintf() or multiple strcat() and itoa()?
I was creating Arduino function which sends two `int` and additional `char`s between them and at the beginning and end of `char` array - then print that array to the serial port in almost real time. (For example "X50Y100T".)

I don't want to use `String` object in Arduino and I found two possible solutions:

* Using `sprintf()`:

```
char sendBuffer[16];
void dataSend(int first, int second) {
  sprintf(sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
};

```
* Or something like this:

```
char sendBuffer[16];
void dataSend(int first, int second){
  char convert[6];
  sendBuffer[0] = 'X';

  itoa(first, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'Y';

  itoa(second, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'T';

  Serial.println(sendBuffer);
  memset(sendBuffer,0,sizeof(sendBuffer));
};

```

My question is - which one is better from technical point of view?

The `sprintf()` looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of `sprintf()`? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of `char` array?

# Answer
Why do you feel you need to use either method? Neither are needed. Just print the individual parts:

```
Serial.print('X');
Serial.print(first);
Serial.print('Y');
Serial.print(second);
Serial.println('T');

```

No intermediate buffers, just sending the data direct out to the UART.
> 4 votes

# Answer
Here's a method that for some reason uses slightly fewer bytes of flash memory than Majenko's does, while producing the same output:

Add `#include <Streaming.h>` at the beginning of the program, and replace the five statements shown in Majenko's answer with the following line:

```
Serial << 'X' << first << 'Y' << second << 'T' << endl;

```

That is, use the `Streaming.h` contributed library, which adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size. You can install it via `Streaming5.zip` from arduiniana.org.

When the `#if`-delimited sections in the program shown below are selected individually (by changing two of the three 01's at a time to 0's), I got the following compiled-code and RAM figures, running the program on a Nano, where all three ways appear to give the same output:

```
      Bytes  Bytes
Alt.  Flash   Ram    Note
 1    2,204   182    Five Serial.print stmts
 2    3,384   190    Using snprintf()
 3    2,176   182    One Streaming stmt

```

I don't know whether this slight decrease (from 2204 to 2176 bytes of flash) is replicable, but the method probably is worth trying in your situation.

The program:

```
#include <Streaming.h>
void setup() {
  Serial.begin(115200);
}
void loop() {
  int first=50, second=100;
  //enum { first=50, second=100};
#if 01
  Serial.print('X');
  Serial.print(first);
  Serial.print('Y');
  Serial.print(second);
  Serial.println('T');
#endif
#if 01
  char sendBuffer[16];
  snprintf(sendBuffer, sizeof sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
#endif
#if 01
  Serial << 'X' << first << 'Y' << second << 'T' << endl;
#endif
}

```

Note, I used `snprintf()` rather than `sprintf()` because it's easier to avoid buffer overruns with `snprintf()` than with `sprintf()`.
> 2 votes

# Answer
As a general principle code that is easy to read and modify is "better" – the problem here is that there are many "betters" to consider:

* Readability
* Maintainability
* Space efficiency
* Time efficiency

There is no universal answer to which of those is the most important. My personal bias is to start with code that is easy to read and obvious in its function. Then if time or space are an issue to start looking for ways to improve.

In your code, you could also do something like this:

```
  itoa(first, sendBuffer[1], 10);

```

Which would save you a function call and perhaps some space.

Also keep in mind that the cost of `sprintf()` in terms of space may get amortized over many uses, so it might not be as bad as it initially seems.
> 0 votes

# Answer
The sprintf() function has a memory cost because of the library import at compile time. But it only costs that once, no matter how many more times you use it. Unless you're running out of space, memory used is not a big deal. There's no point keeping some memory unused on an Arduino.

I think it's better to use sprintf() because:

* sprintf() produces code that is more readable, since the final output string can be easily visualised - obviously with only place holders for the variable parts.
* Making minor changes to the output is quicker, since there's not lines of output generator functions to re-organise.
* You end up with less code. Less code is is easier to debug and maintain.

I would however, encourage you to use snprintf(). This function differs from sprintf() by taking the maximum buffer size as an argument. This will help prevent problems with buffer-overruns (i.e.: accidentally putting more data into a string than in can hold)

Sprintf on Arduino does not include support for floating point numbers though. This is quite a drawback. One needs to use additionally use dtostrf().

The real takeaway point is this: Only optimise your program when you need to. Donald Knuth said: "Premature Optimisation is the root of all evil".
> 0 votes

---
Tags: arduino-uno, serial, sketch, string, code-optimization
---


title: Error in Arduino Library file

text:
# Question
Title: Error in Arduino Library file
I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.

**Error**

> FPS\_GT511C3\FPS\_GT511C3.c.cpp.o: In function Command\_Packet::GetPacketBytes()': C:\Users\Dipti\Documents\Arduino\libraries\FPS\_GT511C3/FPS\_GT511C3.c.cpp:17: undefined reference tooperator new\[\](unsigned int)' FPS\_GT511C3\FPS\_GT511C3.c.cpp.o: In function FPS\_GT511C3::GetResponse()': C:\Users\Dipti\Documents\Arduino\libraries\FPS\_GT511C3/FPS\_GT511C3.c.cpp:735: undefined reference tooperator new\[\](unsigned int)' collect2.exe: error: ld returned 1 exit status

Library File (CPP)

> byte\* packetbytes= new byte\[12\];
>
> byte\* resp = new byte\[12\];

# Answer
The core of the problem is that the code is being compiled as C and not C++.

The error says 'new\[\]' is undefined at the link stage. This is because the linker is not pulling in the C++ standard libraries. The built-in function new\[\] it doesn't exist in C.

The filename FPS\_GT511C3.c.cpp is the elephant in the room. You could consider renaming it (and others) to FPS\_GT511C3.cpp. Although the plain Arduino IDE does not really have a problem with building them.

Another option might be to modify the new\[\] (and delete\[\]) for C's malloc() and free(). However this is only appropriate for the allocation of simple types (byte, int, etc). If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.
> 1 votes

---
Tags: c++, library
---


# Question
Title: One LED being constant and another blinking
I have just started my first project. I got through with 2 periodically blinking LEDs. Now I want one LED (blue) to be lit constantly and the other (red) to be blinking as before. Can anyone help me with this?

This is my code for blinking LEDs.

```
int red_led = 4;
int blue_led = 3;

void setup() {

  pinMode(red_led, OUTPUT);

  pinMode(blue_led, OUTPUT);

}

void loop() {

  digitalWrite(blue_led, LOW);

  digitalWrite(red_led, HIGH);

  delay(1000);

  digitalWrite(blue_led, HIGH);

  digitalWrite(red_led, LOW);

  delay(1000);

 }

```

# Answer
> 2 votes
The wonderful thing about the Arduino is that it hides a lot of the programming "noise" and lets you concentrate on the code that is actually doing the work. Part of the joy of programming is starting to "own" the code and being able to make it do what you want.

The answer here isn't too hard, and I'm sure that many could answer your question – but I think you might enjoy the experience more (and you would earn more respect) if you make a stab at it yourself first. Or if you already have, tell us what you've tried and what happened when you tried it. That will help us help you to see not only the steps necessary, but the concepts that will enable you to branch off on your own.

Do you know what is causing the LEDs to blink in your current code?

# Answer
> 1 votes
Remember that the setup() function runs once, and then the loop() function runs forever. So to keep the blue LED light, simply turn it on, but never off. The code for the red LED remains unchanged.

```
const int red_led  = 4;
const int blue_led = 3;

void setup()
{
    pinMode(red_led, OUTPUT);
    pinMode(blue_led, OUTPUT);

    digitalWrite(blue_led, HIGH);  // LED On
}

void loop()
{
    digitalWrite(red_led, HIGH);  // LED On
    delay(1000);
    digitalWrite(red_led, LOW);   // LED Off
    delay(1000);
}

```

---
Tags: arduino-uno
---


# Question
Title: Interfacing Arduino with matplotlib animation
I've also asked this question over on stack exchange so I'll link the actual question here.

The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use `flush()`. I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.

Edit: Here's a snippet of the code.

```
void loop() {
  // put your main code here, to run repeatedly:
  val1 = analogRead(0);
  val2 = analogRead(1);
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  //Serial.flush();
  delay(50);
}

```

# Answer
On the Arduino side, `flush` simply waits until the last byte has been fully transmitted. It says nothing about how quickly it is being read by the PC.

The general problem you are having is called "flow control". It has been solved with many different techniques, like "handshaking". For example, the PC could send a character when it has received the last byte of a data set (a line, as returned by `readline`):

```
line = self.ser.readline()
self.ser.write("!"); // Tell Arduino line was received
line = line.split()

```

While the PC proceeds to parse the line, the Arduino will eventually receive the handshake character:

```
void loop()
{
  // Send a line
  Serial.println( ... );

  // Wait for handshake character
  bool gotHandshake;
  do {
    while (!Serial.available())
      ; // wait for chars
    char c = Serial.read();
    gotHandshake = (c == '!');
  } while (!gotHandshake);
}

```

Then the Arduino can proceed to send the next data set (i.e., a line). The OS on the PC will buffer characters from the Arduino until the python program receives them with `readline` and sends another handshake character. No `delay` required.
> 1 votes

---
Tags: arduino-uno, serial, programming
---


# Question
Title: How can I adapt the DallasTemperature library to accept another 1-Wire class?
A commonly used library is the DallasTemperature library, used to access DS18B20 sensors on a 1-Wire bus. When creating a DallasTemperature object you pass a reference to a OneWire object. OneWire can create a 1-Wire bus on pretty much any port of an Arduino.

An example of this is like so:

```
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

```

However, there are some issues with using OneWire to drive a 1-Wire bus, mainly around driving longer bus lengths, dealing with shorts, and other errors.

There is a commonly available chip called the DS2482-100 that can drive longer busses (hundreds of feet), deals with shorts and other errors. It is also less CPU heavy and it deals with a number of the slower aspects of 1-Wire.

For this reason, I would like to be able to pass a reference to a library that I have created instead. Currently, I am doing this by:

* Calling the library OneWire
* Replicating all the methods called by the DallasTemperature library
* Swapping out the OneWire library for mine

This is relatively messy. I would ideally like to be able to pass either a reference to my library or a 1-Wire library, so that people can chose which interface to use.

How would I go about doing this?

# Answer
> 4 votes
The typical way to achieve what you want would normally be to create your own **subclass** of `OneWire` class and **override** the methods you need to change, then pass a pointer to an instance of your class to the `DallasTemperature` constructor.

However, for this to work, the `OneWire` class must have been developed with extensibility (subclassing) in mind, i.e. use **virtual** methods that you can override.

Unfortunately, a quick look at `OneWire.h` shows that no method is virtual in there.

So that means in the end you will have to perform some hacks, just as you do now.

What you could potentially do (that's still a hack, but maybe a bit less dirty) is:

* replace `OneWire.h` to make all methods virtual (at least those you need to override)
* keep the original `OneWire.cpp` that should still compile with the newly adapted header file
* create a new `MyOneWire.h` / `MyOneWire.cpp` to define your own `OneWire` subclass that overrides all necessary methods as you want

Then you can pass either a `OneWire` or a `MyOneWire` instance to `DallasTemperature` constructor.

NB: when I see my answer, this makes me think your question is more a general C++ question than an Arduino-related one.

# Answer
> 0 votes
> The DS2482-100 is an I2C-to-1-Wire®bridge device that interfaces directly to standard (100kHz max) or fast (400kHz max) I2C masters to perform bidirectional protocol conversion between the I2C master and any downstream 1-Wire slave devices.

It uses a higher level protocol over I2C which does not directly match the bit-banged OneWire interface above.

A possible solution is to "only" reuse the OneWire interface and reimplement it. Sub-classing will not work as the member functions are not virtual. Unfortunately this will not work directly due to error handing, timing, etc. The DallasTemperature class will also need modifying.

Please see the DS2482-100 product description and protocol.

To achieve your goal of allowing either bit-banged or DS2482-100 based 1-Wire master would require 1) an abstract interface (class) used by 1-Wire master device drivers, 2) sub-classes for each implementation master variant.

As the 1-Wire protocol has a number of common commands a delegation pattern is more useful. Please see the Cosa OWI::Driver and DS18B20 device driver for an example of the delegation pattern.

---
Tags: library, build
---


# Question
Title: Can I work with larger numbers than an unsigned long long in Arduino?
I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

# Answer
There are many ways to use numbers bigger than an `unsigned long` on Arduino. The right one depends on the application.

**Floats and Doubles** `float`s and `double`s types on Arduino can hold exact integers up `2^53`. That is a very large number. They are built into the Arduino compiler.

**uint64\_t** The `uint64_t` type can hold exact integers up to `2^64`. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.

**BigNumber (or bc)** The `BigNumber` type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...

https://github.com/nickgammon/BigNumber

Again, this type is not supprted by the Arduino built-in library functions so you will need to either down-convert or find `BigNumber` compatible functions for things like printing and serializing.
> 3 votes

---
Tags: arduino-mega
---


# Question
Title: How to make 2 LEDs flash in a 5/4 Polyrhythm?
Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.

```
//Making a 5/4 Polyrhythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {

  for(i=0; i<5; i++)
  {
     digitalWrite (LED13, HIGH);
     delay(500);
     digitalWrite (LED13, LOW);
     delay(800);
  }

  for(i=0; i<4; i++)
  {
     digitalWrite (LED7, HIGH);
     delay(500);
     digitalWrite (LED7, LOW);
     delay(1000);
  }

```

}

# Answer
> 4 votes
I generally calculate whether the led must be on or off, based on the current time.

```
//Making a 5/4 Polyrythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {
    // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
    // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
    bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
    bool led7on  = (millis()/750)%2!=0;
    digitalWrite (LED13, led13on);
    digitalWrite (LED7, led7on);
    delay(10);
}

```

# Answer
> 1 votes
See https://arduino.stackexchange.com/a/17929/6628 with code like:

```
const int onTime = 500;
const int measureTime = (int) (60*1000/10);  // 10 BPM, or 1500*4ms/measure
const int off4 = measureTime/4 - onTime;  // take care these don't go negative
const int off5 = measureTime/5 - onTime;  //
unsigned long next5;
unsigned long next4;

...
loop(){
  unsigned long now;
  now=millis();
  ...
  if(next5 < now) {
     if digitalRead(LED13) { next5 = now+off5;   digitalWrite(LED13,LOW );}
     else                  { next5 = now+onTime; digitalWrite(LED13,HIGH);}
  }
  if(next4 < now) {
     if digitalRead(LED7)  { next4 = now+off4;    digitalWrite(LED7,LOW );}
     else                  { next4 = now+onTime ; digitalWrite(LED7,HIGH);}
  }

}

```

---
Tags: led, timing
---


# Question
Title: Trinket: Battery + USB at the same time?
Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?

I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

# Answer
> 2 votes
From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit\_products\_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.

If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines. See https://www.pjrc.com/teensy/external\_power.html Option 2 for an example of the cable surgery.

---
Tags: power, usb
---


# Question
Title: Interleave Assembly and Source for avr-objdump
Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)

Original Makefile

Here's my current Makefile:

```
PREFIX=avr-
CC=${PREFIX}gcc
OBJCOPY=${PREFIX}objcopy

BIN=knightrider
MCU=attiny85
OBJS=../src/tinySPI.o src/knightrider.o

PROG?=atmelice_isp
PORT?=usb

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    @mkdir -p bin
    ${OBJCOPY} -O ihex -R .eeprom build/$< bin/$@

${BIN}.elf: ${OBJS}
    @mkdir -p build
    ${CC} ${LDFLAGS} -o build/$@ $?

install: ${BIN}.hex
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq

clean:
    rm -f build/*
    rm -f bin/*

fuses:
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq

```

What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?

# Answer
> 3 votes
First make sure you add `-g` to all your compilation commands.

Then you can run `avr-objdump -S build/spi.elf` (for instance).

Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.

Here is a makefile I use:

```
PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
 -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
fuse:w:0xd6:m -U efuse:w:0x05:m -qq

```

---
Tags: assembly, avr-toolchain
---


# Question
Title: max current while using a shift register
In arduino's official page about ShiftOut https://www.arduino.cc/en/Tutorial/ShiftOut, a drawing with two 74HC595 powered by the arduino board, is displayed.

Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.

So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?

Thank you

# Answer
> 2 votes
0.20A is *not* the maximum current for an Arduino device. 0.20A is the maximum current for *the chip that is on the Arduino*. Thus it is only relevant to devices that are *directly* connected to the Arduino's IO pins (that connect direct to the chip).

The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board. Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.

---
Tags: shift-register
---


# Question
Title: Arduino RTC - getting the time from RTC after the power is cut off
I have a new DS1307 (original, not a Chinese rip off), with a new battery. It is working great, but when I turn the Arduino off (it is currently connected to laptop) and then turn it back on, it resets the time.

The line that sets the time is (in setup part of code):

```
setDS1307time(30, 42, 21, 4, 26, 11, 14);

```

So, when the Arduino gets the power back it runs the program again and it overrides the correct current time.

How can I avoid this?

# Answer
Without knowing the DS1307 well, I think there are two options:

1. Make the setting of the clock a UI function (you should probably do this in any case since you will want users to have the ability to set the clock). The user would have to initiate the action (and put in the time to set) so there would be no problems the clock getting reset inappropriately, or
2. Do a check for sanity of the clock before you run that line. You might be able to do that through the clock API (e.g., make a call to check the time, or to get the clock status and see if it makes sense) or you could do it by storing the clock status in nonvolatile memory. The very worst case would be that you store the time of last boot and check that it seems reasonable (e.g., the time you get from the RTC is after the last boot and is within reason – say no more than a month or a year ago). If the time is too far off to feel confident you could issue a "check time" warning.

If you have a network connection using NTP as well as the RTC would be a very smart option. NTP can hold the time within a few milliseconds. The RTC would then provide you with protection against a network outage.

If you are using the Arduino to manage scheduled events one thing you'll want to think about is events that are scheduled in a moment of time that is either "skipped" as you advance the clock or that "repeats" if you set the clock back. One way to handle that is to never "jump" time, but to always just speed it up or slow it down.
> 4 votes

# Answer
If setup() runs, it is because the system has been restarted. It could becuase the reset button was pushed, or it could be due to a power-cycle. But either way, the code will start over completely. So you could

1. Deal with restart issues in setup() as it will only be called once per session (unless you call it in your own code); or
2. Make a variable `static boolean PowerCycled = true;` and clear it once your code has dealt with its re-start issues. After a restart, the initialzed data will get reloaded, including `PowerCycled` with it's initial value of `true` restored.
> 1 votes

---
Tags: arduino-uno, rtc
---


# Question
Title: Is there any way I can turn off the 5V pin?
I'm trying to find a way I can toggle the 5V pin to turn on/off. I want the voltage to pass to another wire at a certain point. It should be off and then when something happens, the 5V should turn on.

How can I do this?

# Answer
> 5 votes
For energy-efficient switching (along with relatively high-current capability), I recommend using a *Darlington* transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.

# Answer
> 2 votes
There isn't programmatic control of the 5V pin, it is hard wired to the USB or the output of the Vin Voltage regulator.

You might try something from How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino? to control the low side of the external device. If you need high-side control, maybe an opto-isolator would be a good solution.

# Answer
> 2 votes
If I'm understanding you correctly, you want a 5 V output that is under programatic control. Do you know how much power you want to pull from the pin?

If the demand is fairly low, you could use one of the digital pins directly – they will supply about 40 mA on an "official" Arduino.

If you need more power, then you could use the pin to switch an external device such as a transistor or a relay.

# Answer
> 1 votes
You don't really want to do that. The 5V pin is on the power bus of your Arduino board. If it *were* possible to turn it off, the entire Arduino would shut down.

---
Tags: pins
---


# Question
Title: Trinket Pro 5V red light flashing when battery attached
I am using Trinket Pro 5V to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position. It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.

Is the power source not sufficient - 9V?

Has anyone faced a similar problem?

# Answer
> 1 votes
Please consider reading the "https://learn.adafruit.com/trinket-gemma-servo-control/wiring" tutorial.

It says

> It is suggested you use an external wall or battery supply and not power the servo via the regulator. servos can draw up to 500mA and the Trinket regulator can only source 150 milliamps (USB power generally 500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, please hook the servo power directly to the battery. Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, use a better power source.

Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".

The "Adafruit 16-Channel Servo Driver with Arduino" tutorial says:

> Good power choices are:

You might also want to look at other Battery holders that hold lots of AA batteries in a convenient package.

Related: "How to get high current from 9 volt batteries" and "What is the max current I could draw from a 9V battery?".

---
Tags: power, battery
---


# Question
Title: Issue in installing Arduino unit library and running with Firmata test application
I am trying to update the Arduino library via the library manager and I tried to download it from the link given in the firmata\_test program:

> WARNING: Category '' in library ArduinoUnit is not valid. Setting to 'Uncategorized' C:\Users\SAURAB~1\AppData\Local\Temp\arduino\_c8217a5b56c170d64dfe4c80a1a205dc\firmata\_test.ino: In member function 'virtual void test\_beginPrintsVersion::once()':
>
> C:\Users\SAURAB~1\AppData\Local\Temp\arduino\_c8217a5b56c170d64dfe4c80a1a205dc\firmata\_test.ino:32:3: warning: narrowing conversion of '249' from 'int' to 'char' inside { } \[-Wnarrowing\]
>
> };
>
> ^
>
> Multiple libraries were found for "Firmata.h" Used: C:\Users\saurabh2836\Documents\Arduino\libraries\Firmata Not used: C:\Program Files (x86)\Arduino\libraries\Firmata

I'm getting this error. I searched but found no conclusive answer. I'm using Windows 8 64bit and Firmata downloaded from http://www.firmata.org/.

Am I doing something wrong?

# Answer
The compiler is giving a lot of information. The warnings can be ignored but the "multiple libraries" indicates that there is at least two copies of Firmata installed. Check (search) that you have not got several downloads of Firmata. Worst case reinstall to clean up that.

Cheers!
> 1 votes

---
Tags: arduino-uno, firmata
---


# Question
Title: Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino
Intel Edison Kit for Arduino Hardware Guide instructs:

```
echo 28 > /sys/class/gpio/export
echo 27 > /sys/class/gpio/export
echo 204 > /sys/class/gpio/export
echo 205 > /sys/class/gpio/export
echo 236 > /sys/class/gpio/export
echo 237 > /sys/class/gpio/export
echo 14 > /sys/class/gpio/export
echo 165 > /sys/class/gpio/export
echo 212 > /sys/class/gpio/export
echo 213 > /sys/class/gpio/export
echo 214 > /sys/class/gpio/export
echo low > /sys/class/gpio/gpio214/direction
echo high > /sys/class/gpio/gpio204/direction
echo high > /sys/class/gpio/gpio205/direction
echo in > /sys/class/gpio/gpio14/direction
echo in > /sys/class/gpio/gpio165/direction
echo low > /sys/class/gpio/gpio236/direction
echo low > /sys/class/gpio/gpio237/direction
echo in > /sys/class/gpio/gpio212/direction
echo in > /sys/class/gpio/gpio213/direction
echo mode1 > /sys/kernel/debug/gpio_debug/gpio28/current_pinmux
echo mode1 > /sys/kernel/debug/gpio_debug/gpio27/current_pinmux
echo high > /sys/class/gpio/gpio214/direction

```

However line 3 already gives an error:

```
echo: write error: No such device

```

Any suggestions on how to enable I2C?

# Answer
> 0 votes
It was a strange problem which we were not able to resolve in an acceptable manner after all.

The problem disappeared after we re-flashed the device.

---
Tags: i2c, edison
---


# Question
Title: May I use both USB-serial and tx/rx pins at the same time?
I am building a CNC machine based on GRBL code on a uno. I also have found a script to read data on a N64 controller. I know there is not enough pins available to do both codes running on the same arduino, so I was wondering if I could have my GRBL arduino connected to a computer thru USB, and at the same time, have a second arduino reading data from the n64 joystick, create Gcode accordingly, and feed that Gcode to the GRBL arduino through the tx/rx pins of each of them. I guess I'll have to put a on-off switch on the tx/rx wife to avoid "noise" when I actually send Gcode to the GRBL arduino from the computer.

Does this all make sense?

# Answer
> 3 votes
The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the SoftwareSerial library or the Wire Library or investing in a better board with more than one serial port.

# Answer
> 1 votes
Low impedance circuits connected to the TX/RX pins would cause distortion in the serial signal and would interfere with communication.

A switch would help here. Alternately, you could use a Mega 2560 with more IOs, or if you are breadboarding it, use a 1284p chip.

You could also use SoftwareSerial to communicate with the other Arduino on another set of pins.

---
Tags: arduino-uno, serial, usb
---


# Question
Title: How to interface with generic IR RGB LED controller?
I want to hook up an arduino to one of those generic RGB LED controllers, you see them everywhere, they are these little white boxes with power input and RGB strip plug and an IR LED lead. Is there a way to take to the IR + and - and connect them the arduino? Then spoof an IR signal to control the control module? I want to do it this way because I already own both the arduino and control module and that module handles the power for the LEDs. All I am hoping I have to do is send the controller the hex value for the IR command through the the arduino in order to control it. Here's a link to what the module looks like and the remote it comes

https://www.amazon.com/dp/B00ASHQQKI/ref=cm\_sw\_r\_cp\_awd\_htMywb1W85962

# Answer
> 1 votes
The IRRemote Library is a good starting point, but you'll probably need a RAW mode. I've got a couple IR controllers from different companies, and they use different codes for the same things.

---
Tags: arduino-uno, rgb-led
---


# Question
Title: Using more than 8 digits using the sevseg library
I am using sevseg and i can't get more than 8 digits to work. I really need 15. Does somebody know what I can do to get this?

Shown is the original example

This is using Gabriel Staples example in the sevseg library:

```
#include <SevSeg.h>

SevSeg sevseg; //Instantiate a seven segment controller object

void setup()
{
  byte numDigits = 4; //<<---I am wanting 15, but doesn't work after 8------
  byte digitPins[] = {2, 3, 4, 5}; //Digits: 1,2,3,4 <--put one resistor (ex: 220 Ohms, or 330 Ohms, etc, on each digit pin)
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

  sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
// Note: 100 brightness simply corresponds to a delay of 2000us after lighting each segment. A brightness of 0
// is a delay of 1us; it doesn't really affect brightness as much as it affects update rate (frequency).
// Therefore, for a 4-digit 7-segment + pd, COMMON_ANODE display, the max update rate for a "brightness" of 100 is 1/(2000us*8) = 62.5Hz.
// I am choosing a "brightness" of 10 because it increases the max update rate to approx. 1/(200us*8) = 625Hz.
// This is preferable, as it decreases aliasing when recording the display with a video camera....I think.
  sevseg.setBrightness(10);
}

void loop()
{
  //local vars
  static byte decPlace = 0;

  sevseg.setNumber(8888,decPlace);
  decPlace++;
  decPlace %= 4; //rollover back to 0 once variable gets to 4; To anyone wondering: the % is called the "modulo" operator; see here for explanation & example: https://www.arduino.cc/en/Reference/Modulo

  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

```

Using the following code, I can't get the 3rd set of 5 numbers to display. I have changed the sevseg.h file to 15, but that shouldn't matter:

```
#include <SevSeg.h>

SevSeg sevseg1;//Instantiate a seven segment controller object 1
SevSeg sevseg2;//Instantiate a seven segment controller object 2
SevSeg sevseg3;//Instantiate a seven segment controller object 3

void setup()
{

  Serial.begin(9600);

byte segmentPins[] = {22, 23, 24, 25, 26, 27, 28, 34}; //Segments:     A,B,C,D,E,F,G,Period

  byte digitPins1[] = {29, 30, 31, 32, 33};
  sevseg1.begin(COMMON_CATHODE, sizeof(digitPins1), digitPins1,  segmentPins);
  sevseg1.setBrightness(10);

  byte digitPins2[] = {35, 36, 37, 38, 39};
  sevseg2.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins2, segmentPins);
  sevseg2.setBrightness(10);

  byte digitPins3[] = {40, 41, 42, 43, 44};
  sevseg3.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins3, segmentPins);
  sevseg3.setBrightness(10);

}

void loop()
{

static byte decPlace = 2;

  sevseg1.setNumber( 12345, decPlace );
  sevseg2.setNumber( 12345, decPlace );
  sevseg3.setNumber( 12345, decPlace );

  sevseg1.refreshDisplay();
  sevseg2.refreshDisplay();
  sevseg2.refreshDisplay();
}

```

# Answer
You can change the pre-defined maximum number of digits at the top of the `SevSeg.h` header file to as many as 10, if you use `long` or `unsigned long` when you call `setNumber`. It is defined here, on line 27:

```
#define MAXNUMDIGITS 8 //Increase this number to support larger displays

```

This the version referenced from the Arduino Playground SevSeg. Be sure to use the same number in your modulo, too:

```
void loop()
{
  //local vars
  static byte decPlace = 0;

  sevseg.setNumber(8888,decPlace);
  decPlace++;
  decPlace %= 10; //rollover back to 0 once variable gets to 10

```

`decPlaces` is mostly useful for floating-point numbers: it specifies how many digits after the decimal point should be displayed. For integer values, it specifies how many leading zeroes will be displayed.

However (as you discovered), you cannot call `setNumber` with anything larger than a `long`, so you are limited to 10 or fewer digits for `MAXNUMDIGITS`. (There is no byte overflow -- it's just limited to the number of decimal digits in 232-1.) This is a limit of one SevSeg instance. You could have *two* instances of `SevSeg` like this:

```
#include <SevSeg.h>
SevSeg sevseg1;
SevSeg sevseg2;

void setup()
{
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

  byte digitPins1[] = {2, 3, 4, 5, 22, 23, 24};
  sevseg1.begin(COMMON_ANODE, sizeof(digitPins1), digitPins1, segmentPins);
  sevseg1.setBrightness(10);

  byte digitPins2[] = {14,15,16,17,18,19,20,21};
  sevseg2.begin(COMMON_ANODE, sizeof(digitPins2), digitPins2, segmentPins);
  sevseg2.setBrightness(10);

  sevseg1.setNumber(  7654321UL, 7 );
  sevseg2.setNumber( 87654321UL, 8 );
}

void loop()
{
  sevseg1.refreshDisplay();
  sevseg2.refreshDisplay();
}

```

The first instance handles 7 digits, and the second instances handles 8 digits. Note the use of "UL" to force and `unsigned long` call.

## Update 11-DEC-2015

> Using the following code, I can't get the 3rd set of 5 numbers to display. I have changed the sevseg.h file to 15, but that shouldn't matter:

First, the `MAXNUMDIGITS` is the maximum *per instance*, so you could set it to **5** to save some precious RAM.

Second, you have a copy and paste error:

```
sevseg1.refreshDisplay();
sevseg2.refreshDisplay();
sevseg2.refreshDisplay();   <--  Oopsies!  :)

```

Third, I assume the `setNumber` calls are placeholders for what you're really going to use. Since they always set the same value, they could be in `setup`. In your final program, there must be some input that will be used to calculate a number to display with `setNumber`.
> 5 votes

# Answer
Looking at the sevseg README file on GitHub I find this:

> If you wish to use more than 8 digits, increase MAXNUMDIGITS in SevSeg.h.

Have you done that? Seems like that might be the problem.

As @slash-dev said, be sure to also modify the `loop()` code as well:

```
void loop()
{
  //local vars
  static byte decPlace = 0;

  sevseg.setNumber(8888,decPlace);
  decPlace++;
  decPlace %= numDigits;

```

I think it makes more sense to use `numDigits` rather than a hard coded constant that you have to remember to change whenever you change the number of digits in your display. It would be worth checking the code for any other hard coded constants. If space is an issue, it might be worth checking to see if using a `#define` results in smaller code than using a variable – in any case do something to avoid needing to understand what "magic numbers" are doing. This is especially important when the same numeric value (e.g., 4) is being used for multiple reasons. Then it gets hard if you need to change the value as you have to understand the purpose behind each use.
> 1 votes

---
Tags: arduino-mega, display, ui
---


# Question
Title: Arduino Uno data logger shield recording nonsense time
I'm using an Arduino Uno with the Adafruit Data Logger Shield powered by a Voltaic 5V 2A battery pack. When writing to an SD card, the time stamp never changes (always reports the same now.unixtime). However, when powered from a laptop, the time stamp is correct and everything seems to be working.

The input voltage from the battery is confirmed to be just over 5V and not substantially lower the the laptop usb port.

Has anyone seen this before? Any ideas?

# Answer
Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.

You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.
> 2 votes

# Answer
The problem was indeed a question of voltage.

I was using the battery to supply 5 volts to the DC power port, which as suggested by the comments needs 7 volts or more. The problem is fixed by using the battery, which supplies a stable 5V, to give power to the USB port (or, presumably the 5V pin, though that is not available in my application).
> 2 votes

# Answer
If you are putting just over 5V into the Vin, it goes through the on-board regulator and needs a 7v minimum per https://www.arduino.cc/en/Main/ArduinoBoardUno The Adafruit Data Logger Shield doc at https://learn.adafruit.com/downloads/pdf/adafruit-data-logger-shield.pdf shows a 9V battery pack.
> 1 votes

---
Tags: arduino-uno, shields, datalogging
---