# Question
Title: Why can I not use pointers instead of array with PROGMEM?
I'm currently changing some libraries to use flash instead of RAM for string storage so that I do not run out of SRAM on a project.

Some strings in the library are declared in this manner:

```
const char *testStringA = "ABC";

```

This is different to how I normally see this done:

```
const char testStringB[] = "DEF";

```

However, I think that these two are equivalent when declared const and initialised in the declaration. Both work fine in code.

I attempted to move these to flash:

```
const prog_char *testStringC PROGMEM = "GHI";

```

I then found that this didn't work. It was producing gobbledegook when printed.

However, following the more usual pattern of:

```
const prog_char testStringD[] PROGMEM = "JKL";

```

works fine.

I can see in the disassembly:

```
00000068 <testStringC>:
  68:   04 01                                               ..

0000006a <_ZL11testStringD>:
  6a:   4a 4b 4c 00                                         JKL.

```

So it is clear the pointer and PROGMEM results in the string/array not being initialised.

Why is this?

Example code:

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

const int BUFFER_LEN = 20;

const char *testStringA = "ABC";
const char testStringB[] = "DEF";
const prog_char *testStringC PROGMEM = "GHI";
const prog_char testStringD[] PROGMEM = "JKL";

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

void loop()
{
    char buffer[BUFFER_LEN];

    Serial.println(testStringA);
    Serial.println(testStringB);

    strncpy_P(buffer, testStringC, BUFFER_LEN);
    Serial.println(buffer);

    strncpy_P(buffer, testStringD, BUFFER_LEN);
    Serial.println(buffer);

    delay(1000);

}

```

# Answer
Well, this question has been wisely answered in an answer to Stack Overflow question *C: differences between char pointer and array*.

Basically, what you're declaring as PROGMEM with,

```
const prog_char testStringD[] PROGMEM = "JKL";

```

is both the array and the memory it points to, that is, the elements of the array, both in current's scope stack. Whereas with:

```
const prog_char* testStringC PROGMEM = "GHI";

```

you declare a PROGMEM pointer to a constant string that may stay elsewhere in memory, but not declared as a PROGMEM string.

Though I did *not* test that, but you should try to declare:

```
const prog_char* testStringC PROGMEM = F("GHI");

```

to actually allocate the pointed string within the PROGMEM space. I *guess* it should be working, using Arduino's `F()` macro, which adds a lot of boilerplate code to actually have the same result as the array declaration.

As said in comments, if not in a global context, the `PSTR()` macro could be used instead of the `F()` macro.

Simpler is better: use the array declaration, not the pointer one!

Cf that other answer, the `__flash` qualifier is a third solution ;-)
> 7 votes

# Answer
What this line:

```
const prog_char *testStringC PROGMEM = "GHI";

```

does is to write prologue code to copy the characters in the string to SRAM, and then initializes the *pointer* stored in flash to this SRAM location. You must load the pointer via normal means, and then dereference the pointer as usual.

```
const char *str = pgm_read_word(&testStringC);
Serial.println(str);

```

This line:

```
const prog_char testStringD[] PROGMEM = "JKL";

```

creates the *array of characters* in flash, allowing you to access it as expected.
> 3 votes

---
Tags: progmem, pointer
---


title: Webserver on Arduino

text:
# Question
Title: Webserver on Arduino
How can I run a webserver in a Arduino Uno? I want to use my Arduino to monitor things in my home such as temperature. I want to be able to access this data through the internet.

# Answer
You'll need something like the Ethernet Shield to connect your Arduino Uno to a LAN.

As for webserver functionality, the Webserver Example sketch does the bulk of what you need.

For the "access this data through the internet" part, assuming you want access beyond your LAN; you'll need to perform Port Forwarding on your local router (i.e. allow the "Internet" to see your Arduino).

If you need wifi, then personally I prefer the CC3300 to the Arduino Wifi shield.
> 2 votes

# Answer
The Arduino Yún has been made with this use case in mind. The Bridge library allows your sketch to publish data such as sensor readings: this data is available through a REST api.

Say you want to publish the temperature of your living room: you'll write something like

`Bridge.put("living_room", String(19)); //celsius`

You can then access the data via web with a URL like

`http://arduino.local/data/get/living_room`

You can get all sensor readings without specifying the key name, with

`http://arduino.local/data/get`
> 2 votes

---
Tags: arduino-uno, ethernet, networking
---


# Question
Title: Controlling water temperature accurately
I have following setup:

* Arduino Duemilanove
* Small water heater connected with optical relay (PWM is ok)
* Waterproof DS18B20 temperature sensor
* Unknown amount of water (but temperature sensor and heater are always underwater).

How can I accurately control water temperature, based on temperature sensor readings? By accurately, I mean up to accuracy of temperature sensor (in this case, ±0.5°C). Everything should run on Arduino, so no additional data storage or processing power is available. For debugging, I can obviously use computer.

I have tried running PID, but it seems really hard to

1. Avoid overshooting - going over target temperature either initially, or when (cold) water is added
2. Stabilize properly after adding cold water.

# Answer
> 3 votes
You need to know the response time of your system and the repeatability of your measurements to characterize your data (establish confidence). I suggest taking samples and average them before turning the heater back on.

Imho, water will not happily stay within 0.5°C. Can you allow for coarse and fine modes? Use a higher PWM for great differences and then lower PWM for when close to target.

Once homed in on your target, there are a few means you can try to improve temperature stability. While pre-built things like PID work for many, I normally implement functionality like this manually.

---
Tags: pwm, pid
---


# Question
Title: All voltage directed to pin 3 when multiple pins are set to out put
I just finished testing a haptic device at university, and when I took it home I got the joy of finding the device not working. Here's what I can trace the problem to: when multiple pins are set to output (pin 2~11), pin 3 writes constantly to high and there is nothing I can do to make it stop.

Using a blinker program one pin at a time produces no problems, however when I run a blinker program that cycles through all pins, pin 3 is set to constant high. My actual code is similar in function but more complex. This program below though gets the same error.

```
void setup()
{
  for (int c =2; c<12; c++){
    pinMode(c, OUTPUT);
  }
}

void loop()
{
  for (int c =2; c<12 ; c++){
     digitalWrite(c, HIGH);
     delay(100);
     digitalWrite(c, LOW);
     delay(100);
  }
}

```

Is this a sign my arduino died? My device had been working for weeks on my prior code with no problem (and no updates).

# Answer
It is probably a dead chip. Try getting a new ATmega chip for the Arduino (easily found online for ~$5) and see if that fixes it.
> 1 votes

---
Tags: pins
---


title: How much can an Uno be overclocked?

text:
# Question
Title: How much can an Uno be overclocked?
When running the board at room temperature (20 C) without any extra cooling mechanisms added, how much can the Arduino Uno be overclocked?

Also, what would I need to change/update to overclock the board?

# Answer
With no active cooling, most ATmega328P will run at 30MHz but you will need to up the supply voltage to ~6V. I have never done this on an Arduino board, just an ATmega328P.

I provided an external clock from a signal generator.

The only way to achieve a speed faster than 16MHz is to change the crystal/oscillator/clock input for one faster than 16MHz.

As this was just an experiment, I didn't alter f\_cpu in boards.txt, so all timers etc. would be incorrect. Baud rates would also be incorrect - the only way to upload code was to change back to 16MHz.
> 7 votes

---
Tags: arduino-uno, performance
---


title: Have I fried my A2 port?

text:
# Question
Title: Have I fried my A2 port?
I'm playing around with a SparkFun Redboard (essentially, an Arduino UNO).

I have a simple 5V sensor that I'd been trying to get to work with A2 and analogRead(). Nothing seemed to work. It's supposed to be cycling from 0 to 5V, which should give me values from 0 to 1023, and instead I get constant values of around 260.

In desperation, I tried using other ports. On A0, A1, and A3 I get the signals I expect. On A2, still nada.

So, the question. Is there something I could have done in configuring things that would have made A2 and only A2 stop reading correctly? If so, how can I reset it?

Or is there some other function that I might be using that could interfere with A2? Currently, I'm only using Serial over USB - could that interfere with A2?

Or could I simply have fried the port?

# Answer
I wrote a simple program that used all six analog pins as digital outputs, and wired up an LED. All of the pins except A2 would blink the LED. So yes, it is fried. Thanks.
> 2 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Circuit diagram interpretation and electrical flow
I'm new to Arduino and consequently, to circuits. I've been reading Arduino Robotics by Warren and this was a circuit present in the book.

From what Warren has said, electricity in the circuit travels from the negative pole to the positive, BUT to imagine it as going the other way for simplicity. So, looking at this circuit... it seems useless to have the resistor placed after the LED, based on the + --\> - model. Wouldn't the LED turn on before going through the resistor, rendering the resistor useless?

Sorry if this seems like a basic concept, I'm entirely new to this.

# Answer
**Should the Resistor be Placed Before or After the LED?**

The important thing to remember is that the direct current electricity must flow *through* the circuit to be useful. Since the resistor is part of the circuit (meaning that there isn't another path for the current to take) it resists the overall flow, thereby helping to protect the LED. Whether before or after the LED, it would still be in the circuit, and would therefore still reduce current flow.

**Visualizing the Flow of Water**

Think of it like a water hose, where the LED is a flow meter and the resistor is your foot. If you step on the hose before the flow meter it will cause the overall flow to slow down. Stepping on the hose after the flow meter but before the nozzle will have the same result, as the water must pass through the entire length of the hose before being released.
> 6 votes

---
Tags: electricity
---


# Question
Title: Arduino LED matrix and 2D array, data seems to be corrupting
Duplicate of this question

I'm trying to drive an 8x8 LED matrix with an arduino nano, but I can't get the LEDs to display what I tell it to.

I'm using this LED Matrix

Here's my code:

```
int row1 = 2;
int row2 = 3;
int row3 = 4;
int row4 = 5;
int row5 = 6;
int row6 = 7;
int row7 = 8;
int row8 = 9;

int col1 = 10;
int col2 = 11;
int col3 = 12;
int col4 = 18;
int col5 = 14;
int col6 = 15;
int col7 = 16;
int col8 = 17;

void setup() {
  int i;
  for(i = 2; i <= 18; i++) {
    pinMode(i,OUTPUT);
  }
  for(i = 2; i <= 9; i++) {
    digitalWrite(i, HIGH);
  }
}

void loop() {

  int display [8][8] = {
  {1,0,0,0,0,0,0,0},
  {0,1,0,0,0,0,0,0},
  {0,0,1,0,0,0,0,0},
  {0,0,0,1,0,0,0,0},
  {0,0,0,0,1,0,0,0},
  {0,0,0,0,0,1,0,0},
  {0,0,0,0,0,0,1,0},
  {0,0,0,0,0,0,0,1}
  };

  updateScreen(display);
}

void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  for (i = row1; i <= row8; i++) {
    Serial.println(i-1);
    digitalWrite(i, LOW);
      digitalWrite(col8, screen[i-2][0]);
      Serial.print(screen[i-2][0]); Serial.print("|");
      digitalWrite(col7, screen[i-2][1]);
      Serial.print(screen[i-2][1]); Serial.print("|");
      digitalWrite(col6, screen[i-2][2]);
      Serial.print(screen[i-2][2]); Serial.print("|");
      digitalWrite(col5, screen[i-2][3]);
      Serial.print(screen[i-2][3]); Serial.print("|");
      digitalWrite(col4, screen[i-2][4]);
      Serial.print(screen[i-2][4]); Serial.print("|");
      digitalWrite(col3, screen[i-2][5]);
      Serial.print(screen[i-2][5]); Serial.print("|");
      digitalWrite(col2, screen[i-2][6]);
      Serial.print(screen[i-2][6]); Serial.print("|");
      digitalWrite(col1, screen[i-2][7]);
      Serial.println(screen[i-2][7]);
      delay(1);
      blank();
    digitalWrite(i, HIGH);
  }

}

void blank() {
  digitalWrite(col1, LOW);
  digitalWrite(col2, LOW);
  digitalWrite(col3, LOW);
  digitalWrite(col4, LOW);
  digitalWrite(col5, LOW);
  digitalWrite(col6, LOW);
  digitalWrite(col7, LOW);
  digitalWrite(col8, LOW);
}

```

And here is the output:

```
1
1|0|0|0|0|0|0|0
2
0|1|0|0|0|0|0|0
3
0|0|1|0|0|0|0|0
4
0|0|0|1|0|0|0|0
5
0|0|0|0|1|0|0¾j
6
0|0|0|0|0|1|0|0
7
0|0|0|0|0|0|1|0
8
0|0|0|0|0|0|0|1

```

So I can tell that the error (probably) isn't my wiring, because those array values are clearly wrong, I have no idea where the `¾j` is coming from.

# Answer
> 2 votes
Because of my psychic abilities\*, I am able to tell that you actually used `.` in a few places you should have used `,` in your array initialization. Replacing the `,`s with `.`s should fix the problem.

*Okay, okay, not really.

# Answer
> 2 votes
Your initial problem can be sorted out by using a longer `delay`.

```
void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  ........
      delay(100); //Longer time duration
      blank();
    digitalWrite(i, HIGH);
  }

}

```

As far as the chess pattern is concerned, it displays correctly for me.

```
void loop() {

  int display [8][8] = {
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1}
  };

  updateScreen(display);
}

```

Check your array declarations for errors.

---
Tags: programming, led, arduino-nano
---


title: Two Timer Interrupts, One Incorrect?

text:
# Question
Title: Two Timer Interrupts, One Incorrect?
I'm trying to replicate a waveform exactly using external and timing interrupts. I've got an external that's setup as a 0ms reference, TIMER1 which is used to determine on time, and TIMER2, which sets the low period. Unfortunately, I can't get the pin low for 2ms. TIMER2 must have something wrong with it, but I can't find it. Instead of banging my head against the wall, I thought I'd ask you guys. Anyone know the answer?

```
//3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19

//Current Serial Byte(Letter or Number)
char incomingByte = 0;
//Previous Byte in the Serial Chain
char previousByte = 0;

//Iterator for Interrupt Values
volatile unsigned int maincount = 0;

//Time of High Period or Timer Duration
volatile unsigned int timerhigh;

//Output Pin for Timer Waveform
volatile unsigned int waveout;

//Time for Timer Delay in milliseconds, default tim
volatile unsigned int groundtime = 0;

//Receiver Pins in an Array, except for 3, which serves as 0 source reference
int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void rising()
{
  // set up Timer 1
  TCCR1A = 0;  // normal mode
  TCCR1B = bit(WGM12) | bit(CS11);  // CTC, scale to clock / 8
  OCR1A = timerhigh;          // time before timer fires
  TIMSK1 = bit (OCIE1A);            // interrupt on Compare A Match
}

//Sets Pin Low, then sets up another timer interrupt for the jump back to high
ISR(TIMER1_COMPA_vect)
{
 //Brings Pin Low for Keypress
 //Serial.println("We're in Timer 1");
 pinMode(waveout,OUTPUT);
 digitalWrite(waveout, LOW);

 //Stop Timer 1
 TCCR1B = 0;                      // stop timer
 TIMSK1 = 0;                      // cancel timer interrupt

 //Disables Interrupts Before Messing
 cli();
 // set up Timer 2
 TCCR2A = 0;  // normal mode
 TCCR2B = 0;
 //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
 TCCR2A = (1 << WGM21); //Enables CTC for timer
 TCCR2B = (1 << CS21); //Sets 8 bit prescaler
 OCR2A = groundtime;          // time before timer fires
 TIMSK2 = (1 << OCIE2A);

 //Cancel Rising Interrupt on D3
 EIFR = bit (INTF1);
 //Reenables interrupts
 sei();
}

//Timer Interrupt for Low Period
ISR(TIMER2_COMPA_vect)
{
//Serial.println("WE'RE IN TIMER2");
//Brings Output pin high
digitalWrite(waveout, HIGH);

//Stop Timer 2
TCCR2B = 0;                      // stop timer
TIMSK2 = 0;                      // cancel timer interrupt

//Cancel Rising Interrupt on D3
 EIFR = bit (INTF1);
}

void setup() {
  // put your setup code here, to run once:

//Sets all the pins for output use
for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}

//Sets Reference Pin as Input
pinMode(3,INPUT);

//Begins Serial
Serial.begin(115200);

//Cancels Timer 1
TCCR1A = 0;  // normal mode
TCCR1B = 0;  // stop timer
TIMSK1 = 0;   // cancel timer interrupt

//Cancels Timer 2
 TCCR2A = 0;
 TCCR2B = 0;                      // stop timer
 TIMSK2 = 0;                      // cancel timer interrupt
detachInterrupt(1);

}

void loop() {

  //Time of Ground Drop(2 mS), Universal for all letters and offsets
  groundtime = 40000;     // spark time (4000 * 500 nS) = 2 mS

  // because of prescaler of 8, each unit is 500 nS (0.5 µS)

     if(Serial.available()> 0);
    {
   //Reads Serial Value and assigns to incomingByte
   incomingByte = Serial.read();
   attachInterrupt(1,rising,RISING);
    }
  //  noInterrupts ();  // atomic change of the time amount

   //In this area, we'll set the output pin to be used by the timing interrupt,
   //and the time delay off the default waveform present on pin 4

   //We can use switch case arrangement, don't know if that's the optimal setup though
 switch(incomingByte)
 {
   default:
   //Do Nothing
   break;

   //Cases FOR ALL THE LETTERS
   case 'a':
   break;
   case 'b':
   break;
   case 'c':
   break;
   case 'd':
   break;
   case 'e':
   break;
   case 'f':
   break;
   case 'g':
   break;
   case 'h':
   break;
   case 'i':
   break;
   case 'j':
   break;
   case 'k':
   break;
   case 'l':
   break;
   case 'm':
   break;
   case 'n':
   break;
   case 'o':
   break;
   case 'p':
   break;
   case 'q':
   break;
   case 'r':
   //Output pin 17 Frequency Pin 10
   //microseconds
   timerhigh=8000;
   waveout=9;
   break;
   case 's':
   break;
   case 't':
   break;
   case 'u':
   break;
   case 'v':
   break;
   case 'w':
   break;
   case 'x':
   break;
   case 'y':
   break;
   case 'z':
   break;

   //Cases FOR ALL THE NUMBERS
   case '0':
   break;
   case '1':
   break;
   case '2':
   break;
   case '3':
   break;
   case '4':
   break;
   case '5':
   break;
   case '6':
   break;
   case '7':
   break;
   case '8':
   break;
   case '9':
   break;

   //Cases FOR ALL THE PUNCTUATION
   case '.':
   break;
   case ',':
   break;
   case '!':
   break;
   case '"':
   break;
   case '#':
   break;
   case '$':
   break;
   case '%':
   break;
 }

//Enables Rising Interrupt for 0ms detection
//attachInterrupt(1,rising,RISING);

//Reenables interrupts after offset time change
//interrupts ();
}

```

# Answer
Turns out the problem was that timer 0 and 2 on the arduino uno are 8 bit. Set a different prescaler and I'm golden

```
// set up Timer 2
    TCCR2A = 0;  // normal mode
    TCCR2B = 0;
    //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
    TCCR2A = (1 << WGM21); //Enables CTC for timer

    TCCR2B |= (1 << CS21);
    TCCR2B |= (1 << CS22); //Sets 256 bit prescaler
    TCCR2B |= (0 << CS20);
    OCR2A = groundtime;    // time before rising edge
    TIMSK2 = (1 << OCIE2A);
    //Cancel Rising Interrupt on D3
    EIFR = bit (INTF1);
    //Reinables interrupts

```
> 5 votes

---
Tags: interrupt, timers
---


# Question
Title: Connecting Something Big to an Arduino - Sending more than 5V
So I am turning a relay on and off with my Arduino. I am using python to control it but wrote the simple basic code in the Arduino IDE. I am able to send 5 or 0 volts to the pin. My question is, how can I turn something on and off that requires more than 5 volts to turn on?

Thank you.

# Answer
Use a transistor, amplifier, opto-isolator or if you can drive a 5V relay use that relay to drive a higher voltage/current item item.
> 1 votes

---
Tags: relay, transistor
---


# Question
Title: How to interface to LPG consumption meter
I have sourced an LPG consumption meter from China with pulse output. I am looking to hook the output up to an arduino to get the consumption metrics. Unfortunately there is not too much documentation available on the unit that I can find. The suppliers inform me that:

1. Black wire(signal 1)
2. Black wire(signal 2)
3. Red wire(earth wire)

So that's a start, I know the unit pulses a signal for every cubic meter of gas consumed. What I'm wanting to know is:

1. What are the input \[likely\] voltages for the unit (or how could I establish this)?
2. How do I wire the unit to an arduino?
3. I can cook up a sketch to do the reading but what is the signal I am looking for?

The mechanical meter itself has a metallic strip on the 0 digit of the wheel (how it achieves the pulsing itself no doubt) so another approach would be something like this http://phk.freebsd.dk/Gasdims/ which is a more accurate option. For this option any suggestions on what photoreflectors are available for the Arduino which could do the job.

# Answer
> 2 votes
Start with earthing the red (!?) wire to the ground of the arduino. Apply 5 volts via a 10k resistor to one of the black wires and also connect the black wire to the arduino as well. Basically :

```
5V ----(10K resistor)---+---Black wire----( Gas Meter)-----ground
                        |
                        |
                        +--- arduino digital input

```

You should either get a high or a low signal. Try the other black wire, it might be inverted (as in high and then pulse low, vs low and then pulse high).

Failing that, pop the top off that cover and have a poke around. Might give you a clue as to what's what.

---
Tags: arduino-uno
---


# Question
Title: Is it possible to build a 1080p OSD webcam shield?
What do I need to build a shield capable of receiving 1080p video from USB camera, timestamp each frame and send the frame to memory card?

# Answer
None of the ATmega based boards have the hardware (in terms of acting as a USB host) or power (in terms of handling probably compressed 1080p video).

Potentially one of the ARM boards could do this. The Arduino Due can act as a host, but it sounds fairly experimental, and none of them will have drivers to connect to the camera.

If a shield was developed to do this, it would have so much more power than the Arduino that the Arduino would probably better be viewed as a slave to the other device.
> 5 votes

---
Tags: shields
---


# Question
Title: How to use a Pololu 5v AVR ISP Programmer to program an AVR at 3.3v
I have a Pololu 5v AVR ISP which I have successfully used to program several Arduinos (a Mega, an Uno and a Pro Mini 5v). I now have a new Arduino compatible clone which is basically a clone of the pro mini 3.3V.

I am wondering if anyone else has used this programmer to program a 3.3V board without issues. I've seen a forum post on pololu's forum which discusses modifications required - but I don't really understand what is necessary.

I've also found the software tool mentioned in the above forum post here and I have downloaded it and built it.

When I run the aforementioned tool I get these options:

```
PgmCmd: Configuration and status utility for the Pololu USB AVR Programmer.
Version: 1.0.1.0
Options:
 -l, --list             list available devices
 -d, --device SERIALNUM (optional) select device with given serial number
 -s, --status           display complete device status
     --freq NUM         sets the ISP frequency (in units of kHz)
     --linea ID
       or --lineb ID    set serial control signal associated with line A or B.
                        Valid IDs are: none, cd, dsr, ri, dtr, rts.
                        Warning: dtr and rts are outputs: -f option is required
     --swminor HEXNUM   AVR ISP software version minor (in hex, e.g. A)
     --swmajor HEXNUM   AVR ISP software version major (in hex)
     --hw HEXNUM        AVR ISP software hardware version (in hex)
     --vddmin NUM       set minimum allowed target vdd (units of mV)
     --vddmaxrange NUM  set maximum allowed target vdd range (units of mV)
     --restoredefaults  restore factory settings
     --bootloader       put device in to bootloader (firmware upgrade) mode

```

I then ran the --status option with the serial number of my programmer and got this:

```
Serial number:                  00048632
Firmware version:               1.07
Settings:
  ISP Frequency:                200 kHz
  Line A Identity:              None
  Line B Identity:              None
  AVR ISP hardware version:     F
  AVR ISP software version:     2.A
  Target VDD allowed minimum:   4384 mV
  Target VDD allowed max range: 512 mV
Last programming:
  Error: None
  Measured Target VDD Minimum:  N/A
  Measured Target VDD Range:    N/A
SLO-scope:
  State:                        Off
  Line A output:                Off
  Line B output:                Off

```

From this I deduced that my programmer is currently set at between about 4.38V and 4.89V which I presume corresponds to the 5V approximate voltage of the normal Arduino chips.

Given that the utility program allows me to set both the target minimum Vdd and the target Vdd max range should I therefore set it to something like a minimum of 2704 with a max range of 512 which should put the signal voltages at up to ~3.2V.

Is that all I have to do to get this to work?

# Answer
> 3 votes
Since AVR ISP is simply a modified form of SPI, the most universal way to handle this is to use a 3/1 level translator such as the MAX3392E. Once you provide it with 5V on VCC and 3V3 on VL it will translate the MOSI, SCK, and nRESET signals to 3V3 and the MISO signal to 5V.

---
Tags: uploading, voltage-level, isp
---


# Question
Title: attiny85 and arduino - analogRead + pwmOut
I am using the Arduino IDE to program the attiny85. I want to take an incoming analog reading, then based on that reading, output a specific PWM value. Here's my circuit:

and here's my code:

```
// to run on attiny85

const byte pwmPin = 0;
const byte analogInPin = A2;

void setup() {
  pinMode(pwmPin, OUTPUT);
}

void loop() {
  int analogIn = analogRead(analogInPin);
  analogWrite(pwmPin, analogIn);
}

```

should be very simple- I have no problems uploading code to the attiny85, and no problems with simple tests like outputting a specific PWM value (not based on the analog read). but when I try to combine the two- read, then write that value, I can't seem to get things to work. In this circuit for example- I get a reading of 1023 (5v) on the arduino micro- instead of a reading of ~ 790 (3.85v) which is what I should expect. I've used a multimeter to verify the voltages in this circuit- so I think I must either be doing something wrong with my expectations of how to wire up or program the attiny85.

# Answer
> 8 votes
Analog read is 10-bits (2^10 = 0-1023 range), analog write is 8-bits (2^8 = 0-255 range). Ditch the lower two bits of the result either by doing:

```
analogIn = analogIn >> 2;

```

which can be shortened to:

```
analogIn >>= 2;

```

Or you can use the rather complex map function:

```
analogIn = map( analogIn(0, 1023, 0, 255) )

```

# Answer
> 4 votes
i needed to re-range the 10bit input to 8 bit for the pwm out.

```
// to run on attiny85

const byte pwmPin = 0;
const byte analogInPin = A2;

void setup() {
}

void loop() {
  pinMode(pwmPin, OUTPUT);
  int analogIn = analogRead(analogInPin);
 analogIn = map(analogIn, 0, 1023, 0, 255);
 analogWrite(pwmPin, analogIn);
}

```

---
Tags: programming, pwm
---


title: XBee shield communication

text:
# Question
Title: XBee shield communication
I need to communicate between two Arduinos using XBee. I am new to XBee and hardware. The two Arduino Unos need to send a message (number) to each other and light an LED or play a sound, when they come close within a 10 meter distance.

So my doubt is which XBee shield and XBee module I need to purchase. I read about XBee series 2, XB24 etc.

# Answer
> 3 votes
The only way I can think of accomplishing this without some sort of proximity sensor is to measure the signal strength of the XBees.

From page 41 of the datasheet:

> **DB (Received Signal Strength) Command**
>
> **AT Command:** ATDB
>
> **Parameter Range \[read-only\]:** 0x17-0x5C (XBee), 0x24-0x64 (XBee-PRO)
>
> DB parameter is used to read the received signal strength (in dBm) of the last RF packet received. Reported values are accurate between -40 dBm and the RF module's receiver sensitivity. Absolute values are reported. For example: 0x58 = -88 dBm (decimal). If no packets have been received (since last reset, power cycle or sleep event), “0” will be reported.

You can use this as a **rough** estimate of the distance between two sensors. You will have to correlate signal strength to actual distance and obstructions and other factors will cause the reported value to be off.

How to measure XBee signal strength?

This page has an example using Processing (on the computer): XBee Signal Strength

# Answer
> 2 votes
The "XBee" brand has two major types. Series 1 are the original ones, and are often NOT referred to by their series number. Series 2 are the newer mesh network brethren.

Most XBee's and their clones are pin compatible (there is even a Bluetooth replacement 'Bee), thus any XBee shield or adapter can be used for either series.

The difference is largely in their communication protocols. The Series 2 allow more robust mesh networking options. But for a beginner - the original (S1) provide simpler out-of-the-box networking.

There are retail packages available that include a pair of S1 XBees, an Arduino compatible breakout board, and a USB adapter to program them. This allows you to get "on the air" and setup the XBees quickly. For communication between two arduinos, a pair of shields will make physical connectivity much easier.

# Answer
> 0 votes
Adding to Ron's answer, the Series 1 is a lot easier to use, because you have to flash firmware onto Series 2s and do all kinds of setup. The S1s work out of the box.

Another thing to keep in mind is that Xbees use 3.3v I/O pins, while the Arduino uses 5v. Most Xbee shields have a Logic Level Converter to handle this, but there are some that don't, and those could damage your Xbee.

---
Tags: arduino-uno, sensors, shields, proximity, xbee
---


# Question
Title: How to implement multiple LED modes in a sketch with potentiometers?
My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...

I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.

How do I implement? Mode selection via a potentiometer?

# Answer
Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using `analogRead()`, you just need to decide what to do with it.

Assume `potVal` has the value of the pot.;

```
if (potVal < 256) {
    // Pot is one quarter turn or less
} else if (potVal < 512) {
    // Pot is between 256 and 512, so its more than quarter but less than half
} else if (potVal < 768) {
    // Pot is between half and 3/4ths of the way there
} else {
    // Pot is greater than 3/4 of it's full range
}

```

So I have broken it down into four quadrants for you, but you can do it however you like.
> 6 votes

# Answer
It would be relatively simple to do a threshold test on analogRead() to switch modes *(e.g. if the value is above 512 (analogRead() gives values between 0-1023)* then you switch modes (probably with a boolean variable that you can then use to decide whether to strobe the LEDs).
> 1 votes

---
Tags: sketch, analogwrite, potentiometer
---


title: Attiny84 and 2-Axis Joystick

text:
# Question
Title: Attiny84 and 2-Axis Joystick
I have a Parallax 27800 2-Axis Joystick wired up to a AVR 14 Pin 20MHz 8K 12A/D - ATtiny84. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?

```
int UD = 0;
int LR = 0;

int DWN = 0;
int UP = 1;
int LEFT = 4;
int RT = 5;

int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, LOW);
  digitalWrite(UP, LOW);
  digitalWrite(LEFT, LOW);
  digitalWrite(RT, LOW);

  //calabrate center
  LRMID = analogRead(3);
  UPMID = analogRead(2);
}

void loop(){

  UD = analogRead(2);
  LR = analogRead(3);
  // UP-DOWN
  if(UD < UPMID - 5){
   digitalWrite(DWN, HIGH);
  }else{
   digitalWrite(DWN, LOW);
  }

  if(UD > UPMID + 5){
   digitalWrite(UP, HIGH);
  }else{
   digitalWrite(UP, LOW);
  }
  // LEFT-RIGHT
  if(LR < LRMID-5){
   digitalWrite(LEFT, HIGH);
  }else{
   digitalWrite(LEFT, LOW);
  }

  if(LR > LRMID +5){
   digitalWrite(RT, HIGH);
  }else{
   digitalWrite(RT, LOW);
  }

  delay(100);

}

```

# Answer
While @alexan\_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.

Instead of fixing this at runtime, as aleman\_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).

If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.
> 3 votes

# Answer
Several AVR devices including ATtiny 84, have a clock prescaler that can be used to lower the core frequency.

The divider can be controlled two ways.

The first way is the **CKDIV8** fuse that controls the default loaded value to CLKPR (Clock prescale register) to either

* **fuse disabled:** Clock Division Factor 1 (clk/1)
* **fuse enabled:** Clock Division Factor 8 (clk/8)

The fuse is enabled by default and applies the clk/8 setting, it can be changed with a programmer.

The second way is by changing the prescaler value during runtime. All you need to do is to include the following header

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

```

and call one of following functions with the appropriate value you want to use

```
   clock_prescale_set(clock_div_1);    // Clock Division Factor 1
   clock_prescale_set(clock_div_2);    // Clock Division Factor 2
   clock_prescale_set(clock_div_4);    // Clock Division Factor 4
   clock_prescale_set(clock_div_8);    // Clock Division Factor 8
   clock_prescale_set(clock_div_16);   // Clock Division Factor 16
   clock_prescale_set(clock_div_32);   // Clock Division Factor 32
   clock_prescale_set(clock_div_64);   // Clock Division Factor 64
   clock_prescale_set(lock_div_128);   // Clock Division Factor 128
   clock_prescale_set(clock_div_256);  // Clock Division Factor 256

```

power.h manual

Note that the above functions can be applied at any part of the program, for example you can lower the cpu frequency to reserve battery and then set it higher again for intensive tasks. Just be aware that all peripheral will work with the divided clock too so PWM, timers, SPI, UART etc will all be affected.

If the problem you are facing is caused by the clock divider being in the /8 setting then you can change it at runtime.

Add the header at the start of the sketch

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

```

And then set the prescaler value to 1 at the start of setup()

```
void setup() {
               clock_prescale_set(clock_div_1);  // set the clock prescaler to /1
}

```
> 1 votes

# Answer
* Are you absolutely sure your AVR is running at 8MHz, because default I believe it is scaling the 8MHz internal RC-oscillator down to 1MHz system clock. Change your F\_CPU macro to 1MHz to see what happens.
> 0 votes

---
Tags: programming
---


title: Digital RGB LED animation

text:
# Question
Title: Digital RGB LED animation
I've been trying to get colours fade into each other for a project I'm working on. I have achieved this with the rainbow effect that some from Adafruit's example code, however I want to be able to choose the colours (eg. dark blue into light blue).

I've got the colours changing and fading, however the fade turns off all the LEDs and starts to increase the brightness of the new colour. I need the colours to blend rather than fade out and increase in brightness.

Is anyone able to point me in the right direction?

```
#include "LPD8806.h"
#include "SPI.h"
#define stripSize 64

int nLEDs = 160;

int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(64, dataPin, clockPin);

// You can optionally use hardware SPI for faster writes, just leave out
// the data and clock pin parameters.  But this does limit use to very
// specific pins on the Arduino.  For "classic" Arduinos (Uno, Duemilanove,
// etc.), data = pin 11, clock = pin 13.  For Arduino Mega, data = pin 51,
// clock = pin 52.  For 32u4 Breakout Board+ and Teensy, data = pin B2,
// clock = pin B1.  For Leonardo, this can ONLY be done on the ICSP pins.
//LPD8806 strip = LPD8806(nLEDs);

void setup() {
  // Start up the LED strip
  strip.begin();

  // Update the strip, to start they are all 'off'
  strip.show();
}

void loop() {
  //turnAllOn(strip.Color(30,30,30),4000);
  fade(0, 127, 0, 100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(30,100,30),4000);
  fade(50, 127, 02,100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(100,30,100),4000);
  fade(50, 127, 50, 100); //red, green, blue, delay - fade up all pixels one color
}

void fade(uint32_t r, uint32_t g, uint32_t b, uint32_t wait) {
  int i, j;
  for (j=0; j < 384; j++) {
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, strip.Color((r*j)/1000,(g*j)/1000,(b*j)/1000));
    }
  strip.show();
  }
  delay(wait);
}

void turnAllOn(uint32_t c, uint32_t wait) {
  int i;
  for (i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);  // turn all pixels on
  }
  strip.show();   // write all the pixels out
  delay(wait);
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

```

# Answer
> 6 votes
Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.

The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.

One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.

This is how I'd probably write it:

```
void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
{
    // Guard against division by zero
    if (numSteps == 0) numSteps = 1;

    // Calculate how how much each colour needs to change on each step
    const float
        stepR = (newR - oldR) / (float)numSteps,
        stepG = (newG - oldG) / (float)numSteps,
        stepB = (newB - oldB) / (float)numSteps;

    // These values will store our colours on the way along
    float r = oldR, g = oldG, b = oldB;
    uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

    // Go through each fade step
    const uint16_t numPixels = strip.numPixels();
    for (uint32_t step = 0; step < numSteps; ++step) {
        // Move one step towards the target colour
        r += stepR;
        g += stepG;
        b += stepB;

        // Round the colours to integers here so we don't have to do it repeatedly in the loop below
        byteR = (uint8_t)(r + 0.5f);
        byteG = (uint8_t)(g + 0.5f);
        byteB = (uint8_t)(b + 0.5f);

        // Apply the colour to each pixel
        for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
            strip.setPixelColor(pixel, byteR, byteG, byteB);
        }

        strip.show();
        delay(waitPerStep);
    }
}

```

As you can see, you pass it the old colour (which you're fading *from*) and the new colour (which you're fading *to*). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.

I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.

To use this, you'd do something like this:

```
// Fade from black to red and pause briefly
fade(0, 0, 0,  255, 0, 0,  100, 10);
delay(500);

// Fade from red to purple and pause briefly
fade(255, 0, 0,   255, 0, 255,  100, 10);
delay(500);

// Fade from purple to green and pause briefly
fade(255, 0, 255,  0, 255, 0,  100, 10);
delay(500);

```

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.

I've also modified the `wait` parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.

In my example above, you can see the `100, 10` parameters at the end of each call to `fade()`. That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).

---
Tags: programming, led
---


title: Powering Arduino with Solar Panels

text:
# Question
Title: Powering Arduino with Solar Panels
Clearly, an Arduino can be powered with solar panels.

1. What is the most optimal configuration?
2. Can you recharge and discharge at the same time?
3. Is LiPO the best battery cache technology, or is there something more durable out there, for fielded deployment?
4. What are the most economic, and reliable ways to do this?

# Answer
> 8 votes
**First of all you want to buy some solar panels or cells.** Although they can be found on eBay for very cheap, but they not be as efficient as they say. I would say try to buy from a reputable dealer to see reviews on the product or trust that they work efficiently. Sparkfun datasheets are generally accurate and can be trusted.

* Most optimal configuration: **Do not use a regulator and some sort of step-up booster.** Try the TPS61200 or TPS61202 chips. They will not *regulate* the voltage, they *boost* the voltage dynamically. This is much more efficient and therefore generates less heat. They work like a reverse voltage regulator, taking .3V to 5.5V and turning it into anywhere from 1.8V to 5V (xxx0) or 5V exactly (xxx2). Hack a USB B end and just connect the power lines to the Arduino.
* Discharge/charge simultaneously: Yes, however I'm not sure how to. I believe that if you hook up a charger IC and a load, the voltage won't go through the battery, it will go through the path of least resistance. However, your battery wouldn't get charged then. This is outside the scope of the question, so I would recommend EE on how exactly to do this.
* Is LiPO the best: **Try a Lithium-Ion Battery.** (A.K.A. Li-ion) According to this site:

> Although the lithium-polymer battery is sleeker and thinner, lithium-ion batteries have a higher energy density and cost less to manufacture.

Therefore, it seems like Li-ion is the best choice for you. **Note: Since you are dealing with very dense batteries that if overvolted can go up into flames \[Note: please mute your speakers!\], make *sure* to go with Sparkfun/Adafruit/etc...**
* Economic way: If you don't mind a big "homemade" solar panel, go this way. Buy through eBay or a similar site solar *cells*. They are small plates that are connected to create a solar panel. Try looking for "grade B" or similar solar cells that work fine, they just may have minor imperfections. It won't be as pretty, but you'll save some cash.

See this EE.SE post for more information. One cool thing that I saw was:

> This is really cool. You can connect the Li-Ion voltage through an op-amp to generate a pulse wave, which can be picked up by your MPU to tell your bot to go charge – Raaj Oct 18 '13 at 18:44

I'm not exactly sure how to do this, but it might be useful. I couldn't find anything online about it.

# Answer
> 4 votes
I would actually suggest LiFePo4 for anything DIY. Not only is it safer so one false move won't cause an inferno, but it will last two to four times as long at the CONST of a little extra size and weight.

Since you are just running an arduino, I would use only 1 single cell, and avoid cell balance woes.

I would use a boost regulator to step up the voltage from the cell to the required 5v.

To actually charge the cell, I would probably use a cheap ebay CC-CV charger board, and set the voltage for about 0.15V below the max for your lifepo(you only lose 10% of the energy but You make the battery last much longer), and set the current as appropriate for your panel and battery.

If your circuit is drawing power while the charger is charging, your circuit will take what it needs and any extra the charger puts out will go into the battery.

You might need a diode, to make the battery not discharge back through the charger.

Use a protection pcb like you can get from batteryspace, or better yet a protected lifepo with the pcb built it.

Remember to size your solar panel so that there is enough energy to keep the circuit running. Even with the protected cells overdischarge kills.

What I'd really like to do is design a lifepo4 charge control board that had all this in one unit since everyone seems to want it...

---
Tags: power, solar
---


# Question
Title: Is my Arduino destroyed or are the pins destroyed?
I made a working model of Bluetooth light control with arduino and Bluetooth. Everything worked fine and then after some time I connected the circuit again it didn't work and the pins 7,10,11,12 aren't working . I was using a Bluetooth shield but I tried the simple LED flash program and even that's not working .

Please suggest any good way of making it working again or at least explain what happened with it.

# Answer
> 6 votes
Try running the blink LED, on a different terminals. If the LED is working properly, then most likely the pins are destroyed. Why are they destroyed? Most likely, you've withdrawn more current than the pins can actually provide.

According to the datasheet of the Arduino uno, the IO pins can handle up to 40mA.

The only possible way to solve this problem is to change the IC (Atmega328) by another one. It's not guranteed that it will work, but the microcontroller is reletively cheap.

The definite answer can not be determined unless you showed us a schematic of your connection.

---
Tags: pins
---


# Question
Title: Arduino error message that I don't understand
I downloaded Arduino code from this: https://github.com/BabyWrassler/MissionControl/ Github, and got the error message below.

It is designed to work with a Raspberry Pi, and I installed the two Adafruit libraries. I also have not hooked it up to either the Pi, or the two Adafruit devices, but that is partly because I cannot get it to run without the error message.

Update: Here is what was highlighted: `Adafruit_LEDBackpack matrixA = Adafruit_LEDBackpack();` The orange bar says: Variable or field ‘matrixOff‘ declared void I cannot tell what of the following was from before, but here is the entire console log:

```
    mcDesk.ino:2:53: error: Adafruit_LEDBackpack.h: No such file or directory
    mcDesk.ino:3:45: error: Adafruit_GFX.h: No such file or directory
    mcDesk:11: error: variable or field 'matrixOff' declared void
    mcDesk:11: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:11: error: expected primary-expression before 'buffer'
    mcDesk:12: error: variable or field 'ledOn' declared void
    mcDesk:12: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:12: error: expected primary-expression before 'buffer'
    mcDesk:12: error: expected primary-expression before 'cat'
    mcDesk:12: error: expected primary-expression before 'an'
    mcDesk:13: error: variable or field 'ledOff' declared void
    mcDesk:13: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:13: error: expected primary-expression before 'buffer'
    mcDesk:13: error: expected primary-expression before 'cat'
    mcDesk:13: error: expected primary-expression before 'an'
    mcDesk:14: error: variable or field 'dispMat' declared void
    mcDesk:14: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:14: error: expected primary-expression before 'buffer'
    mcDesk:17: error: variable or field 'threeDigitDisp' declared void
    mcDesk:17: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:17: error: expected primary-expression before 'buffer'
    mcDesk:17: error: expected primary-expression before 'cats'
    mcDesk:17: error: expected primary-expression before 'ans'
    mcDesk:17: error: expected primary-expression before 'number'
    mcDesk:18: error: variable or field 'digitDisp' declared void
    mcDesk:18: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:18: error: expected primary-expression before 'buffer'
    mcDesk:18: error: expected primary-expression before 'pos'
    mcDesk:18: error: expected primary-expression before 'cat'
    mcDesk:18: error: expected primary-expression before 'an'
    mcDesk:18: error: expected primary-expression before 'num'
    mcDesk:23: error: variable or field 'switchBars' declared void
    mcDesk:23: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:23: error: expected primary-expression before 'buffer'
    mcDesk:23: error: expected primary-expression before 'grphCats'
    mcDesk:23: error: expected primary-expression before 'grphAns'
    mcDesk:23: error: expected primary-expression before 'cmnd'
    mcDesk:23: error: expected primary-expression before 'offset'
    mcDesk:24: error: variable or field 'barDisp' declared void
    mcDesk:24: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:24: error: expected primary-expression before 'buffer'
    mcDesk:24: error: expected primary-expression before 'grphCats'
    mcDesk:24: error: expected primary-expression before 'grphAns'
    mcDesk:24: error: expected primary-expression before 'pos'
    mcDesk:24: error: expected primary-expression before 'offset'
    mcDesk:25: error: variable or field 'cBarDisp' declared void
    mcDesk:25: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:25: error: expected primary-expression before 'buffer'
    mcDesk:25: error: expected primary-expression before 'grphCats'
    mcDesk:25: error: expected primary-expression before 'grphAns'
    mcDesk:25: error: expected primary-expression before 'pos'
    mcDesk:25: error: expected primary-expression before 'offset'
    mcDesk:11: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:12: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:13: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:14: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk:15: error: 'Adafruit_LEDBackpack' does not name a type
    mcDesk.ino: In function 'void decodeCommand()':
    mcDesk:193: error: 'matrixE' was not declared in this scope
    mcDesk:193: error: 'ledOn' was not declared in this scope
    mcDesk:199: error: 'matrixE' was not declared in this scope
    mcDesk:199: error: 'ledOff' was not declared in this scope
    mcDesk:204: error: 'matrixC' was not declared in this scope
    mcDesk:204: error: 'cBarDisp' was not declared in this scope
    mcDesk.ino: In function 'void allMatrixOff()':
    mcDesk:213: error: 'matrixA' was not declared in this scope
    mcDesk:213: error: 'matrixOff' was not declared in this scope
    mcDesk:214: error: 'matrixB' was not declared in this scope
    mcDesk:215: error: 'matrixC' was not declared in this scope
    mcDesk:216: error: 'matrixD' was not declared in this scope
    mcDesk:217: error: 'matrixE' was not declared in this scope
    mcDesk.ino: At global scope:
    mcDesk:220: error: variable or field 'matrixOff' declared void
    mcDesk:220: error: 'Adafruit_LEDBackpack' was not declared in this scope
    mcDesk:220: error: expected primary-expression before 'buffer'

```

# Answer
It seems to me that those Adafruit libraries were not correctly installed on your PC or your sketch.

In addition to downloading and installing the library onto the Arduino library directory (on Windows, that's normally `C:\Users\UserName\Documents\Arduino\libraries`), when you want to use that library with Arduino IDE, you must add the library for your sketch with the menu command "**Sketch -\> Import Library...**"

**Important note**: it seems just adding `#include "library.h"` does not work with Arduino IDE, you absolutely need to use the menu.
> 4 votes

---
Tags: library, sketch
---


# Question
Title: Reading multiple bytes from *software* serial
I have Arduino Leonardo board operating lots of AC relays in quite noisy environment. USB works unstable, which sometimes causes the board to hang, so I decided to use secondary serial connection as "debug console":

```
  Serial1.begin(115200);
  .....
  .....
  if (Serial1.available()) {
    char ch = Serial1.read();
    if ( isalnum(ch) ) {
      switch (ch) {
        case 'M': {
          turnOn_pin_Motor();
          break;
        }
        case 'm': {
          turnOff_pin_Motor();
          break;
        }
        .......

```

My problem is that noise affects Serial1 the same way it messes USB (but at least it doesn't cause it to freeze). I'd like to use some sort of error checking to prevent Leonardo from acting on "phantom" commands. I could, for example, prefix each keyboard command my Arduino should receive with special symbol, maybe "!".

So I must be reading one char, checking if it is "!" and reading second character.

Unfortunately, I can't modify my code so it would use 2-character buffer and shift its contents as characters arrive, without locking the main loop while waiting for the next char. Any hints on what should I do in this case?

# Answer
Serial1 on the Arduino Leonardo is hardware serial, not software.

There are several ways to read in multiple bytes from Serial.

Instead of detecting `Serial.available()` (i.e. non-zero), change it to `Serial.available() >= 2`

```
if (Serial.available() >= 2) {
  for (int i=0; i<2; i++) {
    buffer[i] = Serial.read();
  }
}

```

Or you can leave it as it is, and read into the buffer one at a time.

```
static int bufferIndex;

if (Serial.available())
{
    buffer[bufferIndex++] = Serial.read()
}

```

You'll need to detect the contents of the buffer in another `if` statement, and also deal with the bounds of the index.

Honestly though, noise is your issue here - this is an example of an XY problem. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.
> 3 votes

---
Tags: serial
---


title: 3.3V, 5V and 9V pins on Arduino

text:
# Question
Title: 3.3V, 5V and 9V pins on Arduino
On my Arduino Uno R3 and Arduino Mega R3, there are 5V and 3.3V pins.

However on this page Introduction to the Arduino Board, there is a 5V and 9V pin but no 3.3V pin. The page at Arduino: What Adapter? also mentions a 9V pin.

Why is there a discrepency?

# Answer
The link you provide looks rather old and I don't think it applies to UNO Revision 3 as it has more pins than on the diagram you show.

I suggest you rather take a look at this Arduino UNO link which contains uptodate information about the UNO; in there you will see that for R3, the "power rail" has been extended and has the following pins, left to right:

* 1 unlabeled pin (can't remember what it is)
* 1 **IOREF** pin (used by shields to know if they should operate as 3.3V or 5V devices)
* **3.3V** regulated output
* **5V** regulated output
* 2 **GND** pins
* **Vin** pin: this pin can be used in 2 different ways:
    + either as a voltage supply input (instead of using the power plug or the USB); the input voltage should be in 7-12V range and will be regulated internally (by the board circuits) to 5V
    + or an output supply voltage (if you plugged voltage supply through the power plug or the USB plug) that is a "copy" of the voltage input through the power plug or USB plug (not regulated yet)
> 9 votes

# Answer
There are three power supply pins on the Arduino Uno and on the Mega:

* 5V - Labelled as 5V. Can be used to power other 5V devices.
* 3.3V - Labelled as 3.3V. Can be used to power other 3.3V devices.
* Vin - This also referred to as the 9V pin that is shown in the schematic. This is used to power the Arduino board itself, usually using a 9V battery.
> 8 votes

---
Tags: arduino-uno, pins, power, arduino-mega
---


title: Arduino Not Responding During Program

text:
# Question
Title: Arduino Not Responding During Program
I got an Arduino Uno to play around with, and started to actually dive in. During a program that I am writing for a friend, it suddenly stopped outputting to the serial monitor. When I comment out the part I added (the for loop for changing the names), it still doesn't respond.

```
#include <TrueRandom.h>
#include <EEPROM.h>
#define numPokemon 151
String nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
"Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
"Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
"Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
"Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
"Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
"Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
"Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
"Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
"Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
"Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
"Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew",
};
int a = 0;
int b = 0;
int value;
String pokemonName;
int currentID = TrueRandom.random(1,numPokemon+1);
// a = CurrentID
void setup(){
  Serial.begin(9600);
  if (EEPROM.read(a)!=0){
    currentID = EEPROM.read(a);
    Serial.print("The Stored ID is ");
    Serial.println(EEPROM.read(a));
    Serial.println("Stored = true");
  }else{
    value = EEPROM.read(a);
    Serial.println(value);
    EEPROM.write(a,currentID);
    value = EEPROM.read(a);
    Serial.println(value);
    Serial.println("Stored = false");
  }
  for (int i = 0 ; i < 152 ; i++){
      if (currentID = i){
        pokemonName = nameArray[i];
        Serial.print(pokemonName);
        break;
      }
   }
  //nameChange(currentID);
  //Serial.println(pokemonName);
}
void loop(){

}
void nameChange(int currentID){
   for (int i = 0 ; i < 152 ; i++){
      if (currentID = i){
        pokemonName = nameArray[i];
        break;
      }
   }
}

```

What is the problem with this code?

# Answer
> 2 votes
The primary reason that this isn't working is that you are using more RAM than the ATmega328 has (2Kbytes).

The array nameArray is huge. Each one of those characters is 1 byte, it's ~1.1k in itself. Add in Serial, TrueRandom and String, and you are over the limit. It could be you are right on the bounds and calling a single function pushes the stack over it's limit.

To save size, you can place the strings in flash. There is functionality to do this in Arduino, namely PROGMEM directive from underlying AVR-GCC and F() from Arduino. Making arrays of string is quite painful though, and using the Flash library helps here.

Personally I would avoid String for anything like this. The insides of String use dynamic memory allocation and when you are near the limits of RAM, it really isn't helpful. You lose a lot of ease of use by moving to arrays of char though.

You are also using assignment instead of comparison in your code:

```
if (currentID = i){
   pokemonName = nameArray[i];
   Serial.print(pokemonName);
   break;
}

```

This needs to be `currentID == i`.

I'm not confident what you are doing here though. If you want to get the *i* th element from the array, then just do

```
pokemonName = nameArray[currentID]

```

You also have an odd conditional at the beginning where you check for an EEPROM value being non zero, and then the else reads out the EEPROM value which by definition must be zero.

Also, you have a define for `numPokemon` but you aren't using it for the bounds on your for loops.

# Answer
> 1 votes
You have mixed up your comparison and assignment operators in two instances:

First is towards the end of `setup`.

```
  for (int i = 0 ; i < 152 ; i++){
      //if (currentID = i){ //This is assignment, not comparison
      //This is a comparison operation
        if (currentID == i){
        pokemonName = nameArray[i];
        Serial.print(pokemonName);
        break;
      }
   }

```

Second, is in the function definition of `nameChange`.

```
void nameChange(int currentID){
   for (int i = 0 ; i < 152 ; i++){
      //if (currentID = i){ //This is an assignment operation, not comparison.
      //This is a comparison operation
        if (currentID == i){
        pokemonName = nameArray[i];
        break;
      }
   }

```

Also, you have defined a constant `numPokemon` but are not using it at any point.

# Answer
> 0 votes
the string array is too big for ram, place it in flash with the fucntion F()

```
Serial.println(F("This string will be stored in flash memory"));

```

also a detailed example with array with explanation cn be found here

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


# Question
Title: Unrecognizable Message From PROGMEM char*
I'm using a PROGMEM char\* to store a massive array. When I try to print a certain part of the array, the message comes out mangled. How do I fix this?

The output should be "Poliwag", but it comes out as "arow".

```
#include <TrueRandom.h>
#include <EEPROM.h>
#define numPokemon 151
PROGMEM char* nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
"Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
"Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
"Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
"Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
"Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
"Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
"Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
"Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
"Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
"Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
"Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"
};
int a = 0;
int b = 0;
int value;
String pokemonName = "Missingno";
int currentID = TrueRandom.random(1,numPokemon+1);
// a = CurrentID
void setup(){
  Serial.begin(9600);
  if (EEPROM.read(a)!=0){
    currentID = EEPROM.read(a);
    Serial.print("The Stored ID is ");
    Serial.println(EEPROM.read(a));
    Serial.println("Stored = true");
  }else{
    value = EEPROM.read(a);
    Serial.println(value);
    EEPROM.write(a,currentID);
    value = EEPROM.read(a);
    Serial.println(value);
    Serial.println("Stored = false");
  }
  pokemonName = nameArray[currentID];
  Serial.println(pokemonName);
}
void loop(){

}

```

# Answer
The way you've written in, the *pointer* is stored in flash, but the strings are stored in *SRAM*. Read the appropriate documentation (also found in the Arduino reference) more closely, and do as it says.

```
char nmPokemon0[] PROGMEM = "MISSINGNO";
char nmPokemon1[] PROGMEM = "Bulbasaur";
 ...

PGM_P nameArray[] PROGMEM =
{
  nmPokemon0, nmPokemon1, ...
};

```

And don't forget to copy the string to SRAM as shown further down before outputting it, since `Serial.println()` can't work directly with flash.
> 5 votes

---
Tags: arduino-uno, progmem
---


# Question
Title: Most power efficient way to constantly save 2 kilobytes of data per second
I would like to constantly save data coming from sensors (for an activity tracker) while consuming as less battery as possible (I'd like to have a 4/5 days autonomy on a 3000 mAh battery) but I can't find the best way to save about 2 kBytes/s on a memory large enough to contain several days of data.

Sensors would be read at a rate of 20 times per second and produce about 100 bytes each time.

What options do I have in order to:

* store such an amount of data (hardware)?
* ensure the system can work properly with required autonomy?

# Answer
> 4 votes
There are two constraints here, and I think it might back you into a corner. Size and then power.

2Kbyte/s is 2\*60\*60\*24/1024 = 168.75Mbyte/day. This is a lot. The only readily available technology that can be used with a small microprocessor that can store this volume of data is an SD card. There are no serial EEPROM or flash chips this large, and the Arduino, as far as I know, can't deal with the NAND flash used in USB sticks and SD cards.

However, SD cards can be relatively power hungry. They draw between 5mA and 100mA when writing, typically around 30-50mA. The SD spec says the maximum is 200mA. Writing is also quite lengthy as they operate on blocks of data rather than individual cells. I've never done a full analysis of how much power they use, but it is not insignificant and much, much more than serial EEPROM or flash.

So your only choice, if you have to store that much, is to go with SD cards.

I would investigate compressing the data. Even very basic schemes can make a huge difference.

# Answer
> 1 votes
This would be possible with a standard SD card.

**Capacity**

Using some simple calculations, I was able to find that writing at 2kB/s for 5 days would only consume 0.8GB. You could probably get by with a 1 or 2 GB card.

**Speed**

I found this benchmark, which says it is possible to write SD card data from an Arduino at 192 kB/s, which should be more than enough for your needs.

There are a lot of great tutorials and examples out there for using an SD card with an Arduino. The official documentation is always a good place to start.

---
Tags: battery, system-design
---


title: PROGMEM char* mangled text

text:
# Question
Title: PROGMEM char* mangled text
I wrote a program using PROGMEM for massive string arrays. One of the arrays worked, but when I added the second one, the serial output only puts out "th".

Pastebin Code: http://pastebin.com/9U7QZQKn

# Answer
> 4 votes
Your declaration of char buffers is done like so:

```
char* move1 = "N/A";

```

This will only allocate 3 characters with an additional one for null termination i.e. not long enough to hold the name.

You need to do:

```
char buffer[16];

```

Where the length is long enough to hold your string.

# Answer
> 3 votes
I see one major flaw in your code, related to index usage on arrays.

Arrays in C and C++ are using a **0-based index**, meaning that, for an array containing `N` elements:

* the first element is accessible with index `0`
* the last element is accessible with index `(N-1)`

However, your code uses `TrueRandom.random(1,numPokemon+1);` which means you'll get an index between `1` and `numPokemon` (included), if you get the `numPokemon` value for your index, then you'll get garbage as it will try access some other part of memory.

Maybe that is not the only problem in your code, but this one is a major bug.

---
Tags: arduino-uno, progmem
---


# Question
Title: Can I program a 3.3v chip on a 5v board?
I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.

Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.

The problem is that my Uno operates at the more typical 5v / 16MHz.

Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?

# Answer
The clock speed selected will affect both `delay*()` and `millis()`/`micros()` as well as the functions in `<util/delay.h>`, therefore you *must* use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing `boards.txt` and copying an existing entry for the Uno and changing the value of the `f_cpu` parameter to match the target system (in this case, `12000000`).

The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.
> 10 votes

---
Tags: arduino-uno, safety, uploading, atmega328, oscillator-clock
---


# Question
Title: Expected Unqualified-ID Before 'do'(and 'while')
I am getting the error "error: expected unqualified-id before 'do'" multiple times for every do{ }while(); loop I have... Any help?

Pastebin:http://pastebin.com/DubuAEUs

# Answer
> 3 votes
The do whiles are outside of the setup() or loop(), so they won't work.

I would suggest doing a simple C/C++ tutorial like this one to get up to speed with how things work.

---
Tags: programming
---


# Question
Title: Arduino USB Power vs External Power Supply
Why is the Arduino able to accept ~5V from the USB, but requires a min of 7V when using an external power supply?

# Answer
The design assumes USB provides a regulated 5v so no further regulation is necessary. The power connecter is meant to accept a wider range of voltage and regulate it to 5v, and the kind of regulators used on the Arduino board need that much higher voltage to provide regulation. If you already have a regulated +5v source you can supply it to the 5v pin. You'll bypass the on-board regulator this way, so just know that it will then be up to you to provide clean power.
> 33 votes

# Answer
Above is an AA Battery voltage curve. Many people assume that 5\* 1.5V AA batterys would be enough to power the Arduino. As you can see the 1.5 is the maximum voltage and it quickly drops. Different brands have different values and sometimes this can drop below the value of the voltage regulator input. I usually tend to aim between 7 and 9 Volts for running from batteries, ie the nominal voltage of the batteries, eg 6 x 1.5V = 9V.

For wall socket charges, Buy a cheap one and hook it up to a volt meter, Many that say 5V actually have a range of values. Raspberry Pi users often have problems with power caused by manufacturers saying its 5v and it actually delivering something like 4.85 and fluctuating beacuse of the power demand of the pi
> 4 votes

---
Tags: arduino-uno, power, safety, voltage-level
---


# Question
Title: Is there a transmission protocol library for SPI?
When communicating over SPI, one byte is sent at a time. Is there a library (C or C++) that allows for sending strings? Essentially it would be a protocol library handling the start and the end of a message, as well as integrity checking. (I'm using an Arduino.)

# Answer
Each spi peripheral has its own protocol in the sense of commands and addresses if any and data. Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.

So a general purpose library doesnt make sense.

Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.

Your arduino spi master may have its limitations but that has nothing to do with spi in general.

Integrity testing is not part of the spi protocol, you get what you get. Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in. You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc). If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself. If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.
> 6 votes

---
Tags: spi, uart
---


# Question
Title: How to connect 5V sensors to 3.3V digital input (Due)?
I'm completely new with Arduino and microcontrollers in general.

I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?

```
$$\frac{5.0 - 3.3}{\text{Measured current}}$$
(5.0 - 3.3)/(Measured current)

```

# Answer
> 2 votes
Well if you're not sure of what you're doing, you can always go with **level-converters** for your sensors (that does not apply to shields though)

Level-converters (sometimes called **level-shifters**) come in different flavors:

* breakout board (the easiest to work with)
* IC
* DIY circuits with a few components

Some are "one-way": they have pin-pairs with converters 3.3V -\> 5V, and other pin-pairs with 5V -\> 3.3V conversion; others are bi-directional, i.e. you can use the same pair of pins in 2 directions 3.3V \<-\> 5V.

There are plenty of these converters, and they are rather cheap; here are just a few examples:

---
Tags: sensors, arduino-due
---


# Question
Title: What overheads and other considerations are there when using a struct vs a class?
C on embedded systems has traditionally use structs to hold structured data.

Arduino brings C++ to the table, so we can use classes instead.

Lets say we have two different data structures which could be considered very similar:

```
typedef struct
{
    int valueOne;
    int valueTwo;
    int valueThree;
} value_t;

```

and:

```
class Value
{
    public:
        int valueOne;
        int valueTwo;
        int valueThree;
}

```

In terms of memory, what difference will this make?

I still see the struct technique being used heavily - why is this?

# Answer
> 18 votes
As taken from the accepted answer from When should you use a class vs a struct in C++?

> The only difference between a class and a struct in C++ is that structs have default public members and bases and classes have default private members and bases. Both classes and structs can have a mixture of public and private members, can use inheritance, and can have member functions.
>
> I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private data and member functions.

Memory wise the access modifier makes no difference and given the memory constraints of the Arduino, people are less likely to use classes with complex hierarchies, but prefer the POD structs anyway.

# Answer
> 10 votes
Unlike C, an instance of a `struct` in C++ is an object in exactly the same way as an instance of a `class`. From the point-of-view of the compiled code, they are identical. Memory usage, alignment, access times etc. are exactly the same (i.e. there are no overheads).

From the programmer's point-of-view, there is a very minor difference. Members of a `struct` have public visibility by default, whereas members of a `class` have private visibility by default. Otherwise, all language features work the same on both, such as constructors/destructors, inheritance, polymorphism, templates, and operator overloading. You can even derive a `struct` from a `class`, and vice versa.

Despite the similarity, it's quite common to see people deliberately using a `struct` in C++ for very simple structures, e.g. where it only consists of a few data members, but no functions. A `class` would be used for anything more complex. This is purely a matter of convention or personal preference though, and can be used as a subtle indication of the structure's intended complexity.

# Answer
> 4 votes
As other answers have pointed out, your particular `struct` and `class` are indistinguishable performance wise (There are slight differences in the scopes of the type names, due to the way you defined your struct). The delineation in C++ is not between `struct` and `class`, but between types that are *POD (plain old data)* and types that are not, as explained in this discussion.

# Answer
> 3 votes
> In terms of memory, what difference will this make?

None. Structs and classes are the same thing, differing only in protection levels, and instantiating either creates an 'object'.

> still see the struct technique being used heavily - why is this?

Less typing if you're not trying to hide data members.

# Answer
> 2 votes
Note that

```
typedef struct { ... } Foo;

```

is obsolete in C++ and you should just use

```
struct Foo { ... };

```

It's not very clear in the answers but the other effect of structs is public inheritance by default vs private inheritance by default with classes.

As mentioned by others, using struct is generally a convention for POD types.

Also technically 'struct vs object' should be 'struct vs class' (as instantiating a struct or a class still gives an object).

---
Tags: programming, c++, struct, class
---


title: LCD scrolling down problem

text:
# Question
Title: LCD scrolling down problem
I have a list of set-ups and I only have 2 rows in the lcd , I'm trying to scroll down for the moment and I'm doing this by changing the row in the setcursor function to either 0 or 1.

However since that I'll be having about 10 set-ups I used an equation that will change the rows to 0 and one for the ones I want to display and a negative number for those that I don't want to appear. The problem is when setting the cursor's row to -1 or 2, it will ignore the one with row one (which is the 2nd row).

Is there a way that I can overcome this problem ? by setting it to a row that will not appear on my LCD? I'm using `#include <LiquidCrystal.h>` and I already set `lcd.begin(16, 2);`

```
int  colom[5] = {
    0-goDown,1-goDown,2-goDown,3-goDown,4-goDown  };
for (int i = 0; i < 4; i++) {
    if (colom[i] > 1) colom[i] = -1;
}

  lcd.setCursor(0, colom[0]);
  lcd.print("choise 1 ");
  lcd.setCursor(0, colom[1]);
  lcd.print("choise 2 ");
  lcd.setCursor(0, colom[2]);
  lcd.print("choise 3 ");
  lcd.setCursor(0, colom[3]);
  lcd.print("choise 4 ");
  lcd.setCursor(0, colom[4]);
  lcd.print("choise 5 ");

```

So here goDown is 0 so choice 1 and 2 should appear, but I'm only getting choice 1 and in the second row it's changing quickly between 2 and 5, it's not constant.

I thought about doing an if condition for each choice but that will be a lot of code to write and it won't be efficient for my application.

# Answer
This is a bad strategy in general. You should not be issuing print calls for things you *don't* want to print and relying on the lcd library to filter for you because they're out of bounds.

Call print for only the choices you want to display.

```
char* menu[] = {
    "choice 1",
    "choice 2",
    "choice 3",
    "choice 4",
    "choice 5",
};
const int numMenuItems = sizeof menu / sizeof *menu;
const int numLcdRows = 2;

// start out at the top of the menu
int scrollPos = 0;

void drawMenu() {
    for (int i=0; i < numLcdRows; ++i) {
        lcd.setCursor(0, i);
        lcd.print(menu[i + scrollPos]);
    }
}

```

To scroll up or down, just adjust the scroll offset:

```
inline void scrollUp() {
    if (scrollPos > 0)
        scrollPos--;
}

inline void scrollDown() {
    if (scrollPos < numMenuItems - numLcdRows)
        scrollPos++;
}

```

Note this is untested code written for a library I've never seen (just inferring how it works from your post); it's for illustration purposes only.
> 4 votes

# Answer
I have written some abstraction code for handling LCD menus, located here: https://github.com/red-green/Arduino\_Mobile\_OS

Here is the main snippet:

```
byte menu(String title,const String* strings,byte length) {
  boolean select, esc; static byte item, selection;
  select = false;
  esc = false;
  item = 1;
  lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(title);
    lcd.print(": ");
    lcd.print(item);
    lcd.setCursor(0,1);
    lcd.print(strings[item]);
    delay(100);

  while (!select) {
    uint8_t buttons = lcd.readButtons();
    if (buttons) {
    if (buttons & BUTTON_UP) {
      item--;
    }
    if (buttons & BUTTON_DOWN) {
      item++;
    }
    if (buttons & BUTTON_LEFT) {
      esc = true;
    }
    if (buttons & BUTTON_SELECT) {
      selection = item;
      select = true;
    }

    item = constrain(item,1,length - 1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(title);
    lcd.print(": ");
    lcd.print(item);
    lcd.setCursor(0,1);
    lcd.print(strings[item]);
    if (esc) {
      select = true;
      selection = 0;
    }
    delay(100);

  }
  }
  return(selection);
}

```

You may need to change the button handling to work with your setup. To call, have an array of items before setup, like this:

```
const String utilmenuitems[6] = {"back","Random Numbers","Uptime","Device Info"};

```

You can then call it like:

```
byte return = menu("Utilities",utilmenuitems,4);

```
> 1 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Arduino Mega not flashable with XBee PRO S2B
I have an Arduino Mega 2560 with a libelium XBee Shield. If I have an XBee S2 mounted on it and set the two jumpers to the USB setting or remove them, I am able to flash a program onto my Arduino.

However, when I'm mounting one of my XBee PRO S2B (I have three of them available and all behave the same) on the Arduino, no matter how I set the jumpers, it is not possible to flash anything on it. I always see `avrdude: stk500v2_getsync(): timeout communicating with programmer` in the Arduino IDE.

Is the XBee PRO S2B incompatible with the Arduino or what might be the issue? I also tried to add an external power source additionally to the USB, but it didn't help either.

**Update**

After some more experimenting, I found out new details. I tried to disconnect each pin of the shield individually. While doing it, I discovered that disconnecting the `reset` pin from the arduino makes it possible to flash it - take a look at the XBee shield schematic, it's pin 5 from the ICSP connector; Photo:

I used a multimeter and discovered that the XBee PRO S2B CTS / DIO7 port is high, while the one from the XBee S2 is low, and so constantly resetting the arduino. I mounted the XBee PRO S2B onto the Sparkfun XBee Explorer USB and opened a serial port with PuTTY. In contrast to the S2, the PRO S2B provides a menu with several options:

```
B-Bypass Mode
F-Update App
T-Timeout
V-BL Version
A-App Version
R-Reset
>

```

As soon as I type B, the CTS port goes low, and would prevent the arduino from resetting. Also this mode is needed to detect the module via XCTU. However, with an unmodified arduino, I wouldn't have a chance to send this letter, since the XBee is constantly resetting it. What is this menu, can it be disabled somehow?

# Answer
I don't have a PRO to play with, but I just looked at the datasheet and it appears that it SHOULD timeout after 60 seconds

> If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid application image and enter bootloader mode. (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

> XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry mechanism that uses module pins DIN (pin 3), DTR / SLEEP\_RQ (pin 9), and RTS (pin 16). To invoke the bootloader, do the following:
>
> 1. Set DTR / SLEEP\_RQ low (TTL 0V) and RTS high.
> 2. Send a serial break to the DIN pin and power cycle or reset the module.
> 3. When the module powers up, DTR / SLEEP\_RQ and DIN should be low (TTL 0V) and RTS should be high.
> 4. Terminate the serial break and send a carriage return at 115200bps to the module.
> 5. If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
> 6. Commands can be sent to the bootloader at 115200bps.
>
> **Note:** Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.
> 2 votes

---
Tags: programming, serial, xbee
---


title: XBee+Arduino communication problem

text:
# Question
Title: XBee+Arduino communication problem
I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.

We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield. We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.

We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!

This is how I have my XBees configured (series 1) both in AT mode:

> **Transmitting XBee**:
> Channel:10
> Pan id: 1234
> MY: 10
> DL: 11
>
> **Receiving XBee**:
> Channel:10
> Pan ID: 1234 MY: 11
> DL: 10

Transmitting Arduino code:

```
void setup() {
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pins
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  // print out the value you read:
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);
  Serial.println(sensorValue3);
  delay(1);
}

```

Receiving Arduino code:

```
int received1=8;
int received2=9;
int received3=10;
void setup(){
  pinMode(received1, OUTPUT);
  pinMode(received2, OUTPUT);
  pinMode(received3, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  if(Serial.available() )
  {
    byte output1 = Serial.read();
    byte output2 = Serial.read();
    byte output3 = Serial.read();
    digitalWrite(received1, HIGH);
    digitalWrite(received2, HIGH);
    digitalWrite(received3, HIGH);
  }
}

```

# Answer
> 3 votes
There are several things here:

1. Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.
2. You're reading in analog inputs which will be in the range of `0-1023` but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.
3. You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:

```
1:259
2:0
3:1019

```

or even some other delimiter:

```
259:0:1019

```

But I would probably lean towards byte encoding:

```
byte0 :0xEA    // just some custom header for yourself
byte1H:0x01
byte1L:0x03
byte2H:0x00
byte2L:0x00
byte3H:0x03
byte3L:0xFB
byte4 :0xXX    // checksum

```

Or you could `map` the inputs down to a range of `0-255` for single byte transmission.

Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.

***edit:** I've removed the code sample that was here and replaced it with two working sketches below.*

---

I have two XBees, running in AT mode, mine are Series 2, but programatically *I THINK* they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.

What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the `#define TESTAPP` instead of using these values, it can pull three analog values from `A0`-`A2` instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).

```
/* * * * * * * */

XBEE SENDER (131)

#define TESTAPP        // Just serial data based on time

#define PACKETLENGTH   7
#define LED            13

/* * * * * * * */

void setup(){
    Serial.begin(9600);
    Serial.println("\nSender");
    randomSeed(analogRead(0));
    pinMode(LED,OUTPUT);
}

unsigned long m1 = 0;
unsigned long m2 = 0;

void loop(){
    m1 = millis()/1000;
    if(m2 != m1){
        m2 = m1;

#ifdef TESTAPP
        uint8_t  s = m1 % 60;           // how many seconds on millis()
        m1 /= 60;                       // now we're working with minutes
        uint8_t  m = m1 % 60;           // how manu minutes on millis()
        uint8_t  r = 100; //random(256);
        Serial.print("x.x");            // this is just pre-pended data for testing
        Serial.print('<');
        Serial.write(m);
        Serial.print('-');
        Serial.write(s);
        Serial.print('-');
        Serial.write(r);
        Serial.print(">  x-x");        // we want to ignore these chars
#else
        Serial.print('<');
        Serial.write(map(analogRead(A0),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A1),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A2),0,1023,0,255));
        Serial.print('>');
#endif
        digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
    }
    // do other stuff here...
}

```

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:

```
/* * * * * * * * */

XBEE RECEIVER (121)

#define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

//#define DEBUG  // uncomment this line to see all the data stream coming in

#define PACKETLENGTH  7

/* * * * * * * * */

int LED[3]={9, 10, 11};

void setup(){
  Serial.begin(9600);
  Serial.println("\nReceiver");
}

byte  buffer[PACKETLENGTH]; // what holds our serial data
byte  idx         = 0;      // the index for the buffer character being written
byte  validBuffer = 0;      // flag to tell us if we're ready to go

void loop(){
  if(validBuffer){
      #ifdef TESTAPP
          // we're just going to print it out in a different format
          validBuffer=0;
          #ifdef DEBUG
              Serial.print('\n');
          #endif
          Serial.print("Data: (");
          if (buffer[1]<10) Serial.print("0");
          Serial.print(buffer[1]);
          Serial.print(":");
          if (buffer[3]<10) Serial.print("0");
          Serial.print(buffer[3]);
          Serial.print(") (");
          Serial.print(buffer[5]);
          Serial.println(")");
      #else
          // this is the more practical side of things
          // instead of serial.printing, change the brightness
          // on three attached LEDs via PWM Pins (9, 10, 11)
          analogWrite(LED[0],buffer[1]);
          analogWrite(LED[1],buffer[3]);
          analogWrite(LED[2],buffer[5]);
      #endif
      memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
      idx = 0;                          // and reset the index marker
  }
}

// This is where the real magic is done. We have a buffer of
// PACKETLENGTH that takes in all Serial data and waits until
// it finds PACKETLENGTH characters in the format we're after
// Probably not the best method, but it would be unlikely to
// stumble across this pattern, although not impossible :)
// use at your own risk

void serialEvent(){
    if(validBuffer) return; //we don't want to process new Serial
                            //until we've processed the buffer
    buffer[idx] = Serial.read();
        #ifdef DEBUG
        Serial.write(buffer[idx]);
        #endif

    if (++idx==PACKETLENGTH){
        // we have enough bytes for testing, this next part could be handled better
        if(  buffer[0]=='<' &&
             buffer[2]=='-' &&
             buffer[4]=='-' &&
             buffer[6]=='>' ) { // we have a valid data packet
               validBuffer=1;
        } else {    // we don't have valid data yet, but keep
                    // what we have, shift it all over one byte and
                    // we'll check again once the next byte is received
            memmove(buffer, buffer + 1, PACKETLENGTH-1);
        }
        idx--;
    }
}

```

---
Tags: programming, serial, xbee
---