# Question
Title: Put ATmega328 in very deep sleep and listen to serial?
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.

So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.

I am using a custom PCB (not the UNO), with ATmega328p.

Setting the chip to deep sleep:

```
 set_sleep_mode (SLEEP_MODE_PWR_DOWN);
 sleep_enable();
 sleep_cpu ();

```

would not wake it up with serial communication,according to this.

You will need to put it in `IDLE` mode, to listen to serial, but this would consume a few mA -bad.

I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.

I also read this article of Gammon, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:

```
 power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_timer2_disable();
      power_twi_disable();

```

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation? For example, waking up with **long serial data** input?

# Answer
A board we make does this.

* The RX pin is wired to INT0
* INT0 pin set to input or input pullup depending on how the RX line is driven
* On sleep, INT0 low level interrupt is enabled

```
//Clear software flag for rx interrupt
rx_interrupt_flag = 0;
//Clear hardware flag for rx interrupt
EIFR = _BV(INTF0);
//Re-attach interrupt 0
attachInterrupt(INT_RX, rx_interrupt, HIGH);

```
* INT0 interrupt service routine sets a flag and disables the interrupt

```
void rx_interrupt()
{
    detachInterrupt(INT_RX);
    rx_interrupt_flag = 1;
}

```
* On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character `>` and end character `\r`. e.g. `>setrtc,2015,07,05,20,58,09\r`. This give some basic protection against losing messages, as incoming characters are not processed until a `>` is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send `>wakeup\r` hehe.

The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.

This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.

**Update**

At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)

Thus another method without wires may be

* Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.
* Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)

Ideally this is how I would have designed our board but what we have works.
> 12 votes

# Answer
The code below achieves what you are asking:

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

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;

ISR (PCINT2_vect)
{
  // handle pin change interrupt for D0 to D7 here
}  // end of PCINT2_vect

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  Serial.begin (9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;
    // pin change interrupt (example for D0)
    PCMSK2 |= bit (PCINT16); // want pin 0
    PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    UCSR0B &= ~bit (RXEN0);  // disable receiver
    UCSR0B &= ~bit (TXEN0);  // disable transmitter

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
    PCICR  &= ~bit (PCIE2);   // disable pin change interrupts for D0 to D7
    UCSR0B |= bit (RXEN0);  // enable receiver
    UCSR0B |= bit (TXEN0);  // enable transmitter
  }  // end of time to sleep

  if (Serial.available () > 0)
  {
    byte flashes = Serial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

```

I used a pin-change interrupt on the Rx pin to notice when serial data arrives. In this test the board goes to sleep if there is no activity after 5 seconds (the "awake" LED goes out). Incoming serial data causes the pin-change interrupt to wake the board. It looks for a number and flashes the "green" LED that number of times.

## Measured current

Running at 5 V, I measured about 120 nA of current when asleep (0.120 µA).

## Awakening message

A problem however is that the first arriving byte is lost due to the fact that the serial hardware expects a falling level on Rx (the start bit) which has already arrived by the time it is fully awake.

I suggest (as in geometrikal's answer) that you first send an "awake" message, and then **pause** for a short time. The pause is to make sure the hardware does not interpret the next byte as part of the awake message. After that it should work fine.

---

Since this uses a pin-change interrupt no other hardware is required.

---

# Amended version using SoftwareSerial

The version below successfully processes the first byte received on serial. It does this by:

* Using SoftwareSerial which uses pin-change interrupts. The interrupt which is caused by the start bit of the first serial byte also wakes the processor.
* Setting the fuses so that we use:

+ Internal RC oscillator
    + BOD disabled
    + The fuses were: Low: 0xD2, High: 0xDF, Extended: 0xFF

Inspired by FarO in a comment, this lets the processor wake up in 6 clock cycles (750 ns). At 9600 baud each bit time is 1/9600 (104.2 µs) so the extra delay is insignificant.

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

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;
const byte RX_PIN = 4;
const byte TX_PIN = 5;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  mySerial.begin(9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
  }  // end of time to sleep

  if (mySerial.available () > 0)
  {
    byte flashes = mySerial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

```

Power consumption when asleep was measured as 260 nA (0.260 µA) so that is very low consumption when not needed.

Note that with the fuses set like that, the processor runs at 8 MHz. Thus you need to tell the IDE about that (eg. select "Lilypad" as the board type). That way the delays and SoftwareSerial will work at the correct speed.
> 8 votes

---
Tags: serial, atmega328, sleep
---


# Question
Title: Sleep mode and months of operation on small battery
In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to **sleep and power down modes,** so as to run on **one set of battery for months**, appreciate idea and comment.

Initially, I looked at web postings and get the following general idea. Did I miss anything?

Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.

Are there several such library?

How are they?

Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)

Many thanks in advance

# Answer
Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.

http://jeelabs.org

There is also a library based on this project called Jeelib:

http://jeelabs.net/pub/docs/jeelib/

Jeelib contains a class called `Sleepy` that allows for easy sleeping.

Rocketscream did a thorough test of the current consumptions with the different modes here:

http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/

According to them, you can get the ATMega328P down to 1.7uA.

Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:

Arduino powering from 9V battery
> 4 votes

# Answer
I could reproduce these power requirements - main thing is to get rid of the Arduino board and start with a Bareduino or sth similar. (find a detailed description here)
> 1 votes

# Answer
As a rule-of-thumb, you should be able to achieve 100 nA of current consumption, and still be "alive" and able to respond to external events, like button-presses (eg. a calculator or TV remote). To wake periodically (without an external event) takes more current, because you need the watch-dog timer to be active, but that can still be as low as 6 µA.
> 1 votes

---
Tags: power, sleep
---


title: Array values won't tokenize

text:
# Question
Title: Array values won't tokenize
```
char *p = I2CinBuffer; // array contains "string" "," "string"

```

but

```
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
char *str;       // Temp store for each data chunk
int count = 0;

while ((str = strtok_r(p, ",", &p)) != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
}

```

does not enter while loop.

Many thanks but the hard coding of the values "6,100" give correct results as it stands. However, I am now aware that the Arduino code is working in C strings and I2CInBuffer is a C string on which the "strtok" or "strok\_r" functions will NOT work. My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

# Answer
You're not using strtok\_r properly. You have to treat the first call to strtok\_r differently to all subsequent calls, and I don't know what you're trying to do with the `&p` parameter - that could never work since you're breaking the source pointer with that.

According to the manual page:

> The strtok\_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok\_r() in order to maintain context between successive calls that parse the same string.
>
> On the first call to strtok\_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Unless you're doing concurrent tokenising of multiple strings there is no reason to use the reentrant version of strtok. Instead you should just go:

```
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;

char *str = strtok(p, ",");
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",");
}

```

Note how the first call, outside the while loop, passes the string to parse. All subsequent calls (inside the while loop) pass `NULL` as the string to parse so it continues from the last point in the string rather than starting the string afresh every time from the start (with a broken string since `strtok()` is a destructive function).

> A sequence of calls to strtok() that operate on the same string maintains a pointer that determines the point from which to start searching for the next token. The first call to strtok() sets this pointer to point to the first byte of the string. The start of the next token is determined by scanning forward for the next nondelimiter byte in str. If such a byte is found, it is taken as the start of the next token. If no such byte is found, then there are no more tokens, and strtok() returns NULL. (A string that is empty or that contains only delimiters will thus cause strtok() to return NULL on the first call.)

It is considered *destructive* because:

> The end of each token is found by scanning forward until either the next delimiter byte is found or until the terminating null byte ('\0') is encountered. If a delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; that pointer will be used as the starting point when searching for the next token. In this case, strtok() returns a pointer to the start of the found token.

So in other words, your string that started out as:

```
foo,bar,baz\0

```

ends up, after tokenizing, as:

```
foo\0bar\0baz\0

```

So after the first tokenizing, if you try and pass the string again as the first parameter, instead of "foo,bar,baz", it actually only sees "foo" since the string now ends after `foo`.

If you wanted to use the reentrant version you'd need to create a separate pointer variable for the save pointer and pass that as the third argument:

```
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;
char *saveptr;

char *str = strtok_r(p, ",", &saveptr);
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",", &saveptr);
}

```

Note that you still need to use the same "pass the string on the first call and pass NULL on all other calls" methodology since it is still destructive.
> 1 votes

# Answer
> My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

Example code:

```
int parseit (char * p, int * results, const int maxSize)
{
  int count = 0;
  char *str = strtok (p, ",");   // separate at each "," delimiter
  while (str != NULL && count < maxSize)
    {
    results [count++] = atoi (str);      // Add to array
    str = strtok(NULL, ",");
    }  // end of while
  return count;
}  // end of parseit

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  const int MAX_INTEGERS = 5;
  int inParse [MAX_INTEGERS];
  char  I2CinBuffer [50];

  strcpy (I2CinBuffer, "6,100");
  int found = parseit (I2CinBuffer, inParse, MAX_INTEGERS);
  for (int i = 0; i < found; i++)
    {
    Serial.print (i);
    Serial.print (" = ");
    Serial.println (inParse [i]);
    }  // end of for

}  // end of setup

void loop ()
{
  // rest of code here
}  // end of loop

```

Results from running it:

```
0 = 6
1 = 100

```
> 0 votes

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


title: Global Arrays read as Zero

text:
# Question
Title: Global Arrays read as Zero
I have written a code for my Arduino which spans multiple files, In the file containing the main task, i have a Global Array like this

```
addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

```

where

```
#define NUM_CHILDS  0x02
#define CHILD1_I2C_ADDR         0x10
#define CHILD2_I2C_ADDR         0x02

```

Now to debug my issue, in my Task i do this

```
Serial.print(childAddr[0]);
Serial.print(childAddr[1]);

```

All i receive is

```
00

```

I looked at the issue online, someone pointed it towards overshooting the RAM, I am working on a Pro Mini with ATmega328P with 2K RAM.

# Answer
Since `addr_t` is a character type, I suspect `Serial.print()` is trying to output the ASCII character representation of your two values. ASCII codes 0x10 and 0x02 are non-printing characters, so it might just be outputting 0's for lack of anything better to do.

To output the data as actual numbers, try casting them to integers:

```
Serial.print( static_cast<unsigned int>(childAddr[0]) );
Serial.print( static_cast<unsigned int>(childAddr[1]) );

```
> 2 votes

# Answer
You should try to post a minimal piece of code that reproduces your problem. From what you posted I assembled this:

```
typedef unsigned char addr_t;

#define NUM_CHILDS  0x02
#define CHILD1_I2C_ADDR         0x10
#define CHILD2_I2C_ADDR         0x02

addr_t childAddr[NUM_CHILDS] = { CHILD1_I2C_ADDR, CHILD2_I2C_ADDR };

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println(childAddr[0]);
  Serial.println(childAddr[1]);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Output is:

```
16
2

```

Clearly the problem isn't where you think it is.

---

By the way, in your file `Project.h` you have this:

```
#include "Project.h"

```

Why is it including itself?

---

```
void commRxISR(int count){
    /*
        ISR for the dats received on the I2C bus
    */
    Serial.write("Inside serial receive ISR\n");
    while (1);
    while (0 < Wire.available()){
        MyNode.commChild.commWriteInBuffer(Wire.read());    // Project specific implementation
    }
}

```

The infinite loop in the ISR is interesting. Also don't do Serial prints inside an ISR. They can (almost certainly will) hang the system.
> 0 votes

---
Tags: c++, i2c
---


title: Arduino Micro and MPU-9150

text:
# Question
Title: Arduino Micro and MPU-9150
I'm trying to connect an Arduino Micro to MPU-9150 using the MPU6050\_DMP6 example. It runs for couple of seconds then the board Hangs, I sometimes see the "FIFO overflow" message. The same code runs well when i connect the MPU-9150 to Arduino UNO and Arduino Duemilanove. I tried to lower the serial baud rate but no success with that. I even tried connecting an external 12V to the Micro but it's the same.

should I lower the i2c clock (not sure how to do it)?

another interesting thing i have noticed is that with the Duemilanove i can use a longer line for the i2c (5m of cat5e), with the Uno it only works with less then 2m cables, can anyone tell why?

# Answer
> 1 votes
I have seen a lot of variations with the 6050. Code I know works fine for me, will not run on someone else's system. Code fixes suggested by others has zero effect for me. My understanding is the DMP code is a reverse engineered sample that the manufacturer will not release actual documentation on. So it is a gamble to begin with.

That being said, I usually reset the FIFO buffer after every read. I get an occasional over flow (1-2 per minute) with a lot of other code running at the same time, and NOT using interrupts. The resulting AHRS data is reliable and solid (UNO) at default rate (100hz). Ive lowered the AHRS rate (you have to modify data tables in a .H file) and I get the same error rate, it seems to have no effect.

As far as line lengths go, it is I2C. It is some magical combination of wire size and length, internal pull up resistors plus external ones. I have usually heard people have success adding some pull-up resistors I2C is a ground sink signal - so it doesn't care if it is 5 volts or 3.3 - only that everything on the bus be the same. Obviously you will do better at 5V on a longer line vs 3.3V. Some will argue the pull ups need to be at termination, some say it doesn't matter. I don't know anything other than the spec is very hard to understand and I have not had problems, especially the kind that require some of the elaborate schemes some people come up with (replacing caps and resistors).

Anyhow, 2 meters would seem to be pushing an Integrated circuit to Integrated circuit spec beyond what it was intended for, communication within a board. You might get it to work, but you also might rethink it.

---
Tags: arduino-micro, mpu6050
---


title: 0 value integer does not enter If

text:
# Question
Title: 0 value integer does not enter If
I'm sure this is a very basic coding mistake...

I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.

I also want it only to write to the Serial Monitor for the first time that the value falls to 0.

I don't understand why, when the value for SensorValue = 0, the if is not performed.

This is my code:

```
boolean must_print = true;
int sensorValue = 0;

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue = 0) {

     if (must_print = true)
    {
     must_print = false;
     Serial.println(sensorValue);
    }
  else
    must_print = true
  }

   delay(500);        // delay in between reads for stability
}

```

Thanks!

# Answer
```
  if (sensorValue = 0) {

```

That assigns zero to sensorValue, which then tests false. You want:

```
  if (sensorValue == 0) {

```
> 1 votes

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


# Question
Title: Counting revolutions of a DC motor with a Photo Interrupter
I have a DC motor which is rated at 11 200 RPM.

I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)

I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.

All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.

This is my code:

```
int must_print = 1;
int sensorValue = 0;

//the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue > 0)
    {
      if (must_print == 1)
      {
        must_print = 2;
        Serial.println(sensorValue);
      }
    }

  if (sensorValue == 0) {
    must_print = 1;
  }

  delay(100);        // delay in between reads for stability
}

```

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:

```
354

```

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:

```
298
312
328
336
349
360
366
371

```

Thanks!

# Answer
> 3 votes
You shouldn't use an analog pin with a photointerruptor. The photointerruptor is a digital device. Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.

---
Tags: programming, motor, sketch
---


# Question
Title: Reading iBeacon Data using HC-05 bluetooth module
I have bought a HC-05 bluetooth module for Arduino.

My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

# Answer
> 2 votes
The HC-05 doesn't support BLE, which is used for iBeacons.

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Triggering the push button on the analog input of the L293D motorshield
I'm trying to drive a **12v dc motor** using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.

However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.

The Arduino is powered by a **9v** battery and **motor shield \**L293D** with an external power.

```
#include <AFMotor.h>

    AF_DCMotor motor(1);

    int val;

    #define btnleft A0
    #define btncenter A1
    #define btnright A2

    void setup()
    {
      pinMode(btnleft, INPUT);
      analogWrite(btnleft, HIGH);
      pinMode(btncenter, INPUT);
      analogWrite(btncenter, HIGH);
      pinMode(btnright, INPUT);
      analogWrite(btnright, HIGH);
    }

    void loop()
    {
     val=digitalRead(btnleft);
       if(val!=1)
        {
        Serial.print("LEFT: ");
        motor.setSpeed(255);
        motor.run(FORWARD);
        delay(3800);
        }

     val=digitalRead(btncenter);
       if(val!=1)
        {
        Serial.print("CENTER");
        motor.setSpeed(255);
        motor.run(BACKWARD);
        delay(3800);
        }

     val=digitalRead(btnright);
       if(val!=1)
        {
        Serial.print("RIGHT");
        motor.run(RELEASE);
        delay(3000);
        }
    }

```

# Answer
As noted in Nick Gammon's comment, `digitalWrite(btnleft, INPUT)` (etc.) would make a lot more sense than does `analogWrite(btnleft, INPUT)` (etc.).

---

*Edit:* `INPUT` is a constant defined in `wiring.h` (as in following extract), and is intended for use in `pinMode()` calls that set an IO pin's mode to one of `INPUT`, `OUTPUT`, or `INPUT_PULLUP`. It's inept to use it in a call of either `digitalWrite()` or `analogWrite()`.

```
    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1
    #define INPUT_PULLUP 0x2

```

---

Note that `digitalWrite` to an input-mode pin leaves the pin in input-mode, while an `analogWrite` to an input-mode pin changes the pin to output-mode.

When you want a pin to be input-mode with pullup, it is simpler to use `INPUT_PULLUP` as the mode parameter, rather than using two separate calls. That is, instead of saying `pinMode(pin, INPUT);` followed by `digitalWrite(pin, HIGH);`, just say

```
pinMode(pin, INPUT_PULLUP);

```
> 1 votes

---
Tags: arduino-motor-shield
---


# Question
Title: How can I pass an object as a parameter to a function?
I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this:

```
class Highscore {
public:
  String name;
  int score;

  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

setup() { // etc

```

Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:

```
void writeHighscore(Highscore hs) {
  File f = SD.open("high.txt", FILE_WRITE);
  // Do stuff

```

The complation error is as follows:

> sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void
> sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope
> sketch.ino: In function ‘void setup()’:
> sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope

After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the `writeHighscore()` function, but how can I pass objects to it?

**Edit 1 - Object creation**

```
Highscore hs = Highscore("John", 975);
Serial.println(hs.toString()); // Prints "John - 975" as expected
writeHighscore(hs); // Error

```

# Answer
You are doing everything right, but you need to move the class outside of your .ino file for this to work.  ~~I'm not sure why the arduino IDE makes you do this~~  (see edit) , but it is something I've run into before.

I just tested this, and moving the class declaration outside the ino and into a header file in the project folder makes it compile correctly. Just remember to include the header you make in the ino and to `#include "Arduino.h"` in the header to get access to "String" again.

Technically, only a forward declaration of the class needs to be in a different file.

**Edit:**

I'm relatively sure what is happening is the IDE is generating forward declarations for all your functions but not the class, which are placed before your class definition. This means that breaking the function regex the IDE uses with a dummy "throw()" fixes your problem. for example:

```
void writeHighscore(Highscore hs) throw() { ...

```

should work just fine (it worked for me)
> 6 votes

# Answer
This is a classic example of the IDE "helping" you by generating function prototypes, and not doing it very well. Example code to reproduce:

```
class Highscore {
public:
  String name;
  int score;
  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

void setup () { }
void loop () { }

void writeHighscore(Highscore hs)
{
// do stuff
}

```

This gives the error:

```
sketch_jul06b:4: error: variable or field ‘writeHighscore’ declared void
sketch_jul06b:4: error: ‘Highscore’ was not declared in this scope

```

---

If you look at the output of the IDE preprocessor (you can do this by turning on verbose compilation, and finding out the name of the file it is actually compiling) you see this:

```
#line 1 "sketch_jul06b.ino"
#include "Arduino.h"
void setup ();
void loop ();
void writeHighscore(Highscore hs);
#line 1
class Highscore {
public:
  String name;
  int score;
  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

void setup () { }
void loop () { }

void writeHighscore(Highscore hs)
{
// do stuff
}

```

The important part is that it put:

```
void writeHighscore(Highscore hs);

```

**before** where the class is declared.

---

You can fix the error by simply generating your own function prototype like this:

```
void writeHighscore(Highscore hs);  // function prototype
void writeHighscore(Highscore hs)
{
// do stuff
}

```

Now it compiles without errors. It detects your *own* function prototype, and therefore does not generate its own. The first few lines of the generated file are now:

```
#line 1 "sketch_jul06b.ino"
#include "Arduino.h"
void setup ();
void loop ();
#line 1

```

That troubling prototype has gone.
> 2 votes

---
Tags: c++
---


# Question
Title: Sending a double message for action to occur
I'm currently designing a system for my GCSE coursework. For the coursework, I am making a bollard system, controlled by the internet / traffic lights.

I've been experimenting with an Arduino Uno and Ethernet shield, in order to fulfill the control by the internet.

When I telnet into my Arduino, and send it the command "S#UP", the red LED comes on, and stays on for 30 seconds. If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively. Also, if I were to send a different command, for example "S#DOWN", the LED does not even turn on, no matter how many times I send it.

Does anyone have any ideas for my? Anything I've blatantly missed or got myself confused on?

```
#include <SPI.h>
#include <Ethernet.h>
String authcode, newstatus, command;
bool UP, DOWN, EMERGANCY;
long UPTime, DOWNTime, EMERGANCYTime, LastFlash;
bool NextFlash;

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

IPAddress ip(192, 168, 1, 177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

EthernetServer server(1265);

char serverHost[] = "LambdaLaptop";
EthernetClient phpClient;

int R = 8;
int G = 9;

void setup() {
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  Serial.println("=----------------------=");
  Serial.println("=- Traffic Management -=");
  Serial.println("=-    System Loaded   -=");
  Serial.println("=----------------------=");

  Serial.println("");

  authcode = String("4b4fec50eaa13b98934c36863293b5cf");
  LastFlash = millis();
  NextFlash = HIGH;

  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);
}

void loop() {
  EthernetClient client = server.available();
  if (client) {
    if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );
    }else{
     if(command.length() > 0 ){
       command = String("");
     }
    }
  }
  if( UP ){
    if( UPTime > millis() ){
      digitalWrite(G, HIGH);
    }else{
      UP = false;
      digitalWrite(G, LOW);
    }
  }else if( DOWN ){
    if( DOWNTime > millis() ){
      digitalWrite(R, HIGH);
    }else{
      DOWN = false;
      digitalWrite(R, LOW);
    }
  }else if( EMERGANCY ){
   if( EMERGANCYTime > millis() ){
     if( LastFlash + 100 < millis() ){
       digitalWrite(R, NextFlash);
       if(NextFlash == LOW){
         NextFlash = HIGH;
       }else{
         NextFlash = LOW;
       }
     }
    }else{
      EMERGANCY = false;
      NextFlash = HIGH;
      digitalWrite(R, LOW);
    }
  }
}

void ProcessCMD( String CMD ){
  if(CMD == "S#UP"){
    UP = true;
    UPTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#DOWN"){
    // Make the thing go DOWN.
    // GREEN LIGHT
    DOWN = true;
    DOWNTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#EMERGANCY"){
    // Make the thing go DOWN.
    // Flash RED beacon.
    EMERGANCY = true;
    EMERGANCYTime = millis() + 15000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "TEST"){
    UP = true;
  }else if(CMD == "TEST2"){
    UPTime = millis() + 30000;
  }else{
    if(CMD.length() > 11){
      command = String("");
    }
  }
}

void SetStatus( String newstatus ){
  if (phpClient.connect(IPAddress(192,168,1,10), 80)) {
    phpClient.println(String("GET /setstatus.php?authcode=") + authcode + String("&status=") + newstatus + String(" HTTP/1.1"));
    phpClient.println("Host: LambdaLaptop");
    phpClient.println("User-Agent: arduino-ethernet");
    phpClient.println("Connection: close");
    phpClient.println();
    phpClient.stop();
  }
  else {
    Serial.println("Couldn't connect to the system!");
    phpClient.stop();
  }
}

```

# Answer
> 0 votes
It would be far better to use char arrays instead of the String class (perhaps 11 bytes, if that is the largest command?).

eg.

const int MAX\_COMMAND = 11;

char command \[MAX\_COMMAND\];

---

```
 if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );

```

You appear to be processing the command for every received byte. This means you will process "S", "S#", "S#D", "S#DO" etc. You need to wait until the whole command has arrived.

Then, once the command has been processed, empty out the command ready for next time.

---

```
void ProcessCMD( String CMD ){

```

Also all upper-case is usually reserved for constants, not variables like CMD.

---

Finally, your detection of end-time by addition will fail when millis() wraps. This might not matter in a small test, but you may as well teach the right way. Instead of adding an interval, remember the start time and detect when the interval is up, eg. instead of:

```
if( UPTime > millis() ){

```

You would write:

```
if (millis () - UPTime >= 30000) {

```

Where UPTime is now the *start* of the interval (that is, you remember when the interval starts, and do the above subtraction to find the end of it).

---

## References

# Answer
> 0 votes
I do not have and ethernet shield at this moment to test on it your code but hopefully the next observations will help to solve your issue.

> If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively.

It seems that your string is not correctly processed, probably caused by "garbage" from previous received string or incomplete string. I think is from this part of the code

```
 if (client.available() > 0) {
  char thisChar = client.read();
  command += thisChar;
  ProcessCMD( command );

```

You are trying to append a char (one byte) to your command string; by doing this you are not getting the received string necessarily because the "+=" is for retrieve char by char (for example, inside a while loop). First try to print thisChar variable to ensure what are you getting and also you can print client.available() to see how many bytes you got.

Second, for your `ProcessCMD` function it could be better to use pointers to handle the `command` variable, meanwhile you must clean `command` variable always (and not only when `CMD.lenght > 11` ), i.e,

```
if(CMD.length() > 11){
  command = String("");
}

```

must be at the end of the ProcessCMD function

```
  command = String("");

```

Also you can ensure that when you set `UP=true`, also set `DOWN=false` and so on. I prefer the Switch-Case structure to handle commands.

Try to follow arduino examples to better understand.

Cheers.

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


# Question
Title: What's taking up so much RAM in an almost empty sketch?
I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:

```
int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

```

My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:

```
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

```

I've changed SERIAL\_BUFFER\_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:

```
struct ring_buffer
{
  unsigned char buffer[SERIAL_BUFFER_SIZE];
  volatile unsigned int head;
  volatile unsigned int tail;
};

ring_buffer rx_buffer = { { 0 }, 0, 0};
ring_buffer tx_buffer = { { 0 }, 0, 0};

```

So when the SERIAL\_BUFFER\_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= **73 bytes**)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.

# Answer
First off, a sketch that uses `Serial` **cannot really be considered an empty sketch** as `Serial` drags along a lot of function definitions, at least one `Serial` class instance (more on Arduino Mega, for instance), plus probably some more global variables...

`sizeof Serial` may be interesting to display as `Serial` is not limited to the TX and RX buffers, as you seem to believe. Its class also has a couple of **additional data members** on its own, plus members inherited from its superclasses, `Stream` and `Print`.

In addition, the Arduino IDE comes with the various "utilities" which you normally can't get rid of, like the **millisecond timer** that uses at least 9 bytes (see reference in `wiring.c` file).

So in the end, even an empty sketch (even without `Serial`) takes some SRAM space for global variables.

I think there is some way, with `avr-size`, to check out, with fine details, the size of data (not accounting for the runtime stack) after the sketch has been fully built.

Arduino IDE already displays some of this static memory information (at the end of "verification").

For example, on my IDE (1.5.8) for Arduino UNO, **a really empty sketch, once compiled is mentioned to use 9 bytes of SRAM**. Actually those 9 bytes are for 3 global variables, used by the millisecond timer. This number, of course, does not account for runtime memory usage, in particular the stack.

Then, **just adding `Serial.begin(9600);` makes it use 182 bytes** (ie 173 more bytes than an empty sketch). So you get the culprit.
> 11 votes

# Answer
I investigated this at some length a while back. On this page about putting constant data into program memory I obsessively tracked down every last byte of memory used in a small sketch. This was the sketch:

```
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

```

memdebug.h came from Andy Brown - Debugging AVR dynamic memory allocation.

That particular sketch actually used even more RAM:

```
Free memory = 1702

```

So where did the 346 bytes go? Here:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers
* 9 bytes for keeping track of millis / micros
* 4 bytes for memory allocation (\__malloc\_heap\_start, \__malloc\_margin)
* 128 bytes for the heap safety margin
* 6 bytes for a few nested function calls (main -\> setup -\> getFreeMemory)
* 16 bytes for the compiler vtable for HardwareSerial
* 4 bytes for variables \__brkval and \__flp (used in memdebug)
* 2 bytes pushed onto the stack in main (to save registers)
* 2 bytes pushed onto the stack in setup (to save registers)
* 4 bytes pushed onto the stack in getFreeMemory (to save registers)
* 1 byte because the stack pointer starts at 0x8FF rather than 0x900

(That's 346 bytes accounted for)
> 9 votes

---
Tags: arduino-uno, serial, sketch, sram
---


# Question
Title: How to use Arduino Nano with Arduino Uno
I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?

It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.

Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

# Answer
try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.
> 1 votes

# Answer
Be careful not to power any sort of motor directly from an Arduino (or any of it's siblings directly) without a transistor or H-bridge in between, unless you know exactly how much current your motor draws, peak, and how much your arduino can supply on any given pin. The same applies to any other high-draw device too.

If you are using LEDs, make sure you have a resistor in series with the LED - google "LED resistor calculator" to help you figure out which resistor you need.

Also, when you upload the program, it uses two of the pins - rx and tx, should be digital pins 0 & 1 on a Uno (any other, check your docs).
> 0 votes

# Answer
Maybe it is a very good idea to connect Arduino UNO's only one DIGITAL out point among other digital output pins. This pin can trig Arduino Nano's analog input pins so that you can work your task for further you needed. But you have to seperate your shields or your motors or other things. Like this:

By the way, if you get an upload error, please plug out your shileds or motors or LEDs then try to upload your code again into Arduino UNO.
> 0 votes

---
Tags: arduino-uno, arduino-nano
---


title: Arduino Mega XBee Limited inputs

text:
# Question
Title: Arduino Mega XBee Limited inputs
I'm currently using an Arduino Uno with the Wireless SD shield with an XBEE attached so I can wirelessly send voltages from sensors to a computer. This works great but I am limited to 5 analog inputs. I am thinking of using a Mega but the Wireless SD Shield is the same for both models. Are there any shields/techniques were I can wirelessly transmit up to 15 analog inputs to a PC using XBEE or otherwise,

Many Thanks,

AH

# Answer
> 0 votes
See 74HC4051 multiplexer / demultiplexer. That describes how you can use a multiplexer chip to multiplex analog inputs.

The 74HC4051 multiplexes 8 inputs into one, and the 74HC4067 multiplexes 16 inputs into one. Thus you would only use one analog input, plus 3 or 4 pins to tell the chip which input you want at a particular moment.

The general way a multiplexer works is like this:

By outputting a binary pattern to the A/B/C pins you select which input you want active at a particular moment. That is then copied to the output pin (pin 3 in this case). You would connect that to your analog port on the Arduino.

The code would rotate between each of the 8 pins (or 16 pins with the bigger chip), and then do an analogRead.

---

## Example wiring

---

## Example code

```
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

const byte addressA = 5; // the multiplexer address select lines (A/B/C)
const byte addressB = 6;
const byte addressC = 7;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

```

---

That only does 8 ports, but the 16-port chip would be conceptually similar.

---
Tags: arduino-mega, xbee, wireless
---


# Question
Title: Why do sketches take up so much space and memory?
When I compile this sketch for the Yún:

```
int led = 7;

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

void loop() {
  digitalWrite(led, HIGH);
}

```

I get:

> Sketch uses 5,098 bytes (17%) of program storage space.
>
> Maximum is 28,672 bytes. Global variables use 153 bytes (5%) of dynamic memory, leaving 2,407 bytes for local variables. Maximum is 2,560 bytes.

Even when I compile the BareMinimum sketch:

```
void setup() {
  // setup
}

void loop() {
  // loop
}

```

I get:

> Sketch uses 4,548 bytes (15%) of program storage space.
>
> Maximum is 28,672 bytes. Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

Why does a bare minimum sketch take up 15% of the program storage space allocated? And why does a very simple sketch take up 17% of the program storage space? According to the Arduino website:

> It's easy to use it all up by having lots of strings in your program. For example, a declaration like: `char message[] = "I support the Cape
>  Wind project.";` puts 33 bytes into SRAM (each character takes a byte, plus the '\0' terminator).

However, there aren't any strings declared in either of these sketches.

It seems as if they might import or use other libraries/classes that I don't specify. Maybe it imports a system default library? Or is it something else?

# Answer
The YUN is a combo. Part Arduino and Part OpenWRT(Linux). Your question is in reference to the Arduino. Where this is actually a ATmega32u4 similar to a Leonardo and not an UNO(ATmega328p). The 32u4(Leo) communicates via Virtual Serial Ports over the USB *(short answer: this needs to be supported)* , where the UNO has a real Serial Port (aka UART). Below are builds statistics of the different boards types for the AVR processors.

Note on the UNO there is an external chip that converts USB to the Serial port's DTR pin which toggles the ATmega328's reset pin when connected causing a reboot to the bootloader. In contrast the Leo/Yun's USB to Serial is in implemented in the firmware of the 32u4. Hence in order to remotely reboot the Leo or YUN's 32u4 chip the firmware loaded must always support the USB client side driver. Which consumes approximately 4K.

If the USB was NOT needed and no other library resources were called as in the case of BareMinimum.ino on an UNO, only approximately 466 bytes are needed for the core Arduino Library.

compile stats of BareMinimum.ino on a UNO(ATmega328p)

```
Sketch uses 466 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.

```

compile stats of BareMinimum.ino on a Leonardo(ATmega32u4)

```
Sketch uses 4,554 bytes (15%) of program storage space. Maximum is 28,672 bytes.
Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

```

compile stats of BareMinimum.ino on a Yun(ATmega32u4)

```
Sketch uses 4,548 bytes (15%) of program storage space. Maximum is 28,672 bytes.
Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

```
> 7 votes

# Answer
Arduino compiles in a lot of standard libraries, interrupts, ... etc. For example the pinMode and digitalWrite functions use a lookup table to figure out at run time which GPIO registers to write data to. Another example is that Arduino keeps track of time, it defines some interrupts by default and all this functionality requires some space. You'll notice that if you extend the program, the foot print will only change slightly.

I personally like to program controllers with bare minimum, without "bloat", but you'll quickly enter the world of EE.SE and SO because several easy to use functions will no longer work out of the box. There are some alternative libraries for pinMode and digitalWrite that compile into a smaller footprint, but come with other disadvantages like for example static compiled pins (where `led` cannot be a variable, but is a constant).
> 7 votes

# Answer
You already have some perfectly good answers. I am posting this only to share some stats I did one day I asked myself the same sort of questions: What is taking so much space on a minimal sketch? What is the minimum needed to achieve the same functionality?

Below are three versions of a minimal blinky program that toggles the LED on pin 13 every second. All three versions have been compiled for an Uno (no USB involved) using avr-gcc 4.8.2, avr-libc 1.8.0 and arduino-core 1.0.5 (I do not use the Arduino IDE).

First, the standard Arduino way:

```
const uint8_t ledPin = 13;

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

void loop() {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
    delay(1000);
}

```

This compiles to 1018 bytes. Using both `avr-nm` and disassembly, I broke down that size into individual functions. From largest to smallest:

```
 148 A ISR(TIMER0_OVF_vect)
 118 A init
 114 A pinMode
 108 A digitalWrite
 104 C vector table
  82 A turnOffPWM
  76 A delay
  70 A micros
  40 U loop
  26 A main
  20 A digital_pin_to_timer_PGM
  20 A digital_pin_to_port_PGM
  20 A digital_pin_to_bit_mask_PGM
  16 C __do_clear_bss
  12 C __init
  10 A port_to_output_PGM
  10 A port_to_mode_PGM
   8 U setup
   8 C .init9 (call main, jmp exit)
   4 C __bad_interrupt
   4 C _exit
-----------------------------------
1018   TOTAL

```

In the list above, the first column is the size in bytes, and the second column tells whether the code comes from the Arduino core library (A, 822 bytes total), the C runtime (C, 148 bytes) or the user (U, 48 bytes).

As can be seen in this list, the largest function is the routine servicing the timer 0 overflow interrupt. This routine is responsible of tracking time, and is needed by `millis()`, `micros()` and `delay()`. The second largest function is `init()`, which sets the hardware timers for PWM, enables TIMER0\_OVF interrupt and disconnects the USART (that was used by the bootloader). Both this and the previous function are defined in `<Arduino directory>/hardware/arduino/cores/arduino/wiring.c`.

Next is the C + avr-libc version:

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

int main(void)
{
    DDRB |= _BV(PB5);     /* set pin PB5 as output */
    for (;;) {
        PINB = _BV(PB5);  /* toggle PB5 */
        _delay_ms(1000);
    }
}

```

The break-down of the individual sizes:

```
104 C vector table
 26 U main
 12 C __init
  8 C .init9 (call main, jmp exit)
  4 C __bad_interrupt
  4 C _exit
----------------------------------
158   TOTAL

```

This is 132 bytes for the C runtime and 26 bytes of user code, including the inlined function `_delay_ms()`.

It could be noted that, since this program does not use interrupts, the interrupt vector table is not needed, and regular user code could be put in its place. The following assembly version does exactly that:

```
#include <avr/io.h>
#define io(reg) _SFR_IO_ADDR(reg)

    sbi io(DDRB), 5  ; set PB5 as output
loop:
    sbi io(PINB), 5  ; toggle PB5
    ldi r26, 49      ; delay for 49 * 2^16 * 5 cycles
delay:
    sbiw r24, 1
    sbci r26, 0
    brne delay
    rjmp loop

```

This is assembled (with `avr-gcc -nostdlib`) into only 14 bytes, most of which are used to delay the toggles so that the blink is visible. If you remove that delay loop, you end up with a 6-byte program that blinks too fast to be seen (at 2 MHz):

```
    sbi io(DDRB), 5  ; set PB5 as output
loop:
    sbi io(PINB), 5  ; toggle PB5
    rjmp loop

```
> 5 votes

# Answer
I wrote a post about Why does it take 1000 bytes to blink one LED?.

The brief answer is: "It doesn't take 2000 bytes to blink **two** LEDs!"

The longer answer is that the standard Arduino libraries (which you don't have to use if you don't want to) have some nice functionality to simplify your life. For example, you can address pins by number at runtime, where the library converts (say) pin 8 to the correct port and correct bit number. If you hard-code port access you can save that overhead.

Even if you don't use them, the standard libraries include code to count "ticks" so you can find out the current "time" (by calling `millis()`). To do this it has to add the overhead of some interrupt service routines.

If you simplify down (on the Arduino Uno) to this sketch you get the program memory usage down to 178 bytes (on IDE 1.0.6):

```
int main ()
  {
  DDRB = bit (5);
  while (true)
    PINB = bit (5);
  }

```

OK, 178 bytes isn't that much, and of that the first 104 bytes are the hardware interrupt vectors (4 bytes each, for 26 vectors).

So arguably, there are only 74 bytes required to blink an LED. And of that 74 bytes most are really the code generated by the compiler to initialize global memory. If you add enough code to blink two LEDs:

```
int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

```

Then the code size increases to 186 bytes. So therefore you could argue that it only takes `186 - 178 = 8` bytes to blink an LED.

So, 8 bytes to blink an LED. Sounds pretty efficient to me.

---

In case you are tempted to try this at home, I should point out that whilst the posted code above blinks two LEDs, it does so very rapidly indeed. In fact, they blink at 2 MHz - see screenshot. Channel 1 (yellow) is pin 12, channel 2 (cyan) is pin 13.

As you can see, the output pins have a square wave with a frequency of 2 MHz. Pin 13 changes state 62.5 ns (one clock cycle) before pin 12, due to the order of the toggling of the pins in the code.

So unless you have much better eyes than mine, you won't actually see any blinking effect.

---

As an amusing extra, you can actually toggle **two** pins in the *same* amount of program space as toggling one pin.

```
int main ()
  {
  DDRB = bit (4) | bit (5);  // set pins 12 and 13 to output

  while (true)
    PINB =  bit (4) | bit (5); // toggle pins 12 and 13
  } // end of main

```

That compiles into 178 bytes.

This gives you a higher frequency:

Now we are up to 2.66 MHz.
> 3 votes

---
Tags: programming, compile
---


# Question
Title: Arduino can't see any library I have installed for nrf905?
nrf905\ nRF905-All-In-One-Shield\ RadioHead-master\ RadioHead\

None any of them are compiled with their examples without getting errors.

*Error message:*

```
nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
compilation terminated.
Error compiling.

```

Libraries used:

Elechouse RadioHead Github RadioHead Doxygen zkemble/nRF905

# Answer
The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.

So what you need to do is to create a new folder in the libraries folder for each library.

**Note**: you cannot do the standard `libraryName\src\foo.cpp` as this seems to give errors for these libraries (in that it does not find them).

What you need to do is to make a file in the `libraries` directory; for the *zkemble* one you can create a main folder called `nRF905`, then take the files under `nRF905/arduino/nRF905` from github and place them in the folder created earlier. It should look like this:

You should repeat this for the Elechouse one as well as it solved the problem too. i.e.

* `C:\\...\libraries\NRF\examples\`
* `C:\\...\libraries\NRF\NRF905.cpp`
* `C:\\...\libraries\NRF\NRF905.h`
* `C:\\...\libraries\NRF\keywords.txt`

Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is

```
PROGMEM unsigned int freq_tab[10] = {

```

and to this add `const`, like so:

```
PROGMEM const unsigned int freq_tab[10] = {

```
> 1 votes

---
Tags: library, nrf24l01+, wireless
---


# Question
Title: What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?
-Are there any changes in Bootloader? -Why is the coding different for same chip in different softwares? -How to upload the program from Atmel Studio?

# Answer
Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.

The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.

The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.

It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.

There is another option in Atmel Studio however it might not be what you require ...

You can install the Visual Micro plugin for Arduino from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.

The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)

The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.

More about Visual Micro is here

Tutorials are here

Debugger overview is here

Update:

There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.

The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.
> 2 votes

---
Tags: arduino-uno, arduino-ide, atmel-studio
---


# Question
Title: digitalRead(A0) returns true when A1 is HIGH
I have an Atmega328P-AU with 16Mhz crystal(schematics). And its analog pins A0 to A3 are connected to button inputs. All these pins are pulled-down(10K res). And in code, I have digitalRead(A0) to digtalRead(A3).

When I press button attached to A3 and A2. They works as they should. But when I press any button attached to A0 or A1, both their `digitalRead()` returns true.

I checked 3 times, all resistors and buttons wires are well connected and are not shorted.

Here is test code

```
void setup()
{
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A1, INPUT);
    pinMode(A3, INPUT);
    pinMode(A2, INPUT);
}

void loop()
{
if (digitalRead(A0))
    Serial.println("A0");
if(digitalRead(A1))
    Serial.println("A1");
if (digitalRead(A2))
    Serial.println("A2");
if (digitalRead(A3))
    Serial.println("A3" );
delay(400);
}

```

Here are outputs.

When pressed `A0`

```
A0
A1

```

When pressed `A1`(same result)

```
A0
A1

```

When pressed `A2`

```
A2

```

When pressed `A3`

```
A3

```

I'm wondering what could be causing this problem ?

Edit: Test

* When I press A1 button, the A1 pin is high with 4.8V as well as A0 pin is high with 2.6V to 3.8V.
* When nothing is pressed, A1 has 180mV while A0 has -180mV.

simulate this circuit – Schematic created using CircuitLab

# Answer
Assuming you've not activated any ADC functionality in your Arduino code (i.e. assuming the sample code you've posted here is 100% what you've tried, and no analogReference(); statement), then I still think your problem is a partial short between AO & A1. If my above assumptions are not the case, then there are other possibilities.

With a 5.0V Vcc rail, anything more than 0.5Vcc (i.e. 2.5V) will register as a high/1 (datasheet section 30 - Electrical characteristics, 30.2 DC Characteristics), so based on the measurements you posted to the edit of your question, your code is indeed correctly reporting a 1 on A0 when you push A1 button.

But it's only barely a 1/high, and as you've said, it varies from 2.6 to 3.8, another classic sign of a soldering or partial short circuit somewhere.

If you're able to remove the '328 from the circuit, use your multimeter to read resistance between A0 & A1. Also try a new/different '328, maybe you damaged one of its input in the past.
> 2 votes

# Answer
I recreated this experiment on my Arduino and it worked like it should. This should work the way you want it to. The only thing I can think of is maybe the chip possibly being partially fried or the pullup resistors not being adequet (not having a low enough resistance) for the job. The resistors I used are 1k. Other than that there is not much else I can think of.
> 0 votes

# Answer
Ok so it could be a number of factors. You are sure that the pins are 5V tolerant in the mode you're using? It's possible to burn out pins if they don't have internal current regulation. You said analog pin which is weird since a button will cause lots of debouce, but it looks configured digital. Debounce is still an issue on digital circuits with buttons.
> -1 votes

---
Tags: c++, hardware, digital
---


# Question
Title: Get the distance to non perpendicular surface
So I'm using the HC-SR04 modules to get the distance to objects, the problem is that if it's not a perpendicular surface I dont get any reading, and I assume that the reason is that the ultrasounds get reflected in another direction, so they don't come back to the sensor. What's the way to get over this issue?

Thanks in advance

# Answer
> 1 votes
Use a Infrared Proximity Sensor

or

Something like a LidarLite

They measures distance by measuring the offset (parallax) from a projected point of light. This will not suffer from echo restrictions, like Ultrasonic Sensors do.

# Answer
> 1 votes
You mean to say that you get proper reading when the surfaces are FLAT? Ultrasonic sensors have this property that the waves emitted from then are only 15 degree from the line of sight, but this means that you can surely calculate distance of objects having a curved shape. The only condition is the object should be directly in a straight line

# Answer
> 0 votes
Coming in late but seeing no solutions offered yet, I'll take a stab at it:

Assume your vehicle is traveling obliquely toward the wall. Assume you can find and measure the perpendicular distance to the wall. Then you can calculate the travel distance from those two measurements:

Next we need to find the angle between the vehicle's heading (center-line) and the perpendicular. A rotating sensor that senses return-signal strength could probably give good results but is mechanically more complicated. Given that the ultrasonic sensors have a somewhat broad sensing angle, 3 or 5 fixed sensors (1 straight ahead and 1 or 2 to either side) may work well enough if you're just trying to avoid hitting the wall. In that case you could measure with all of the sensors, take the least distance measurement as 'p' and the known angle of that sensor as 'theta'.

What's left is to decide how to make the calculation and work with cosines. For the rotating sensor case, you'll have to find the angle of the sensor at the time of it's smallest reading, and look up in a table (or calculate) the cosine of that angle. For the multiple fixed sensors case, you already know the sensors' angles and therefore, their cosines.

If you have enough code memory it would easy to write your calculations in floating point, certainly for some quick and dirty testing. If not, or you need to speed up the calculations, you can do it in fixed point with less code. it's a little bit harder for the programmer but much easier and quicker for the MCU.

---
Tags: sensors
---


# Question
Title: Sodaq Moja — Accessing SW2/SW3 user switches
I have a Sodaq Moja, from supporting the project on Kickstarter, and I didn't have much time until now to play with it. Unfortunately, the online documentation for the Moja has disappeared, and only the docs for the new version, the Mbili, is accessible. And nowhere can I see where to access the user switches. Which, to boot, have been reordered in the Mbili, can cut down from 3 to 2.

Would anyone have an idea?

Cheers,

# Answer
According to the schematics and pictures of the Moja, the Sodaq Moja has no "User Switches".

There are 2 buttons and 1 switch. The switch is a general power on-off switch. One button (SW2) is the master reset button for the ATMega328P. The other button, SW3, is the reset for the X-Bee daughter board.

None of those can be used programmatically.
> 1 votes

---
Tags: documentation
---


# Question
Title: What is the use of decoupling capacitor?
I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea\>?

# Answer
Quite simply put, it's a little reservoir of energy for a chip or other device to dip into when it needs to get a little extra power.

In Electronics *nothing* happens instantly. When a chip needs more power it has to get it from the power source. The power source then has to respond to that by providing more energy, and that then has to make its way down the wires or traces to where it needs to be.

By placing a small capacitor near where the power is consumed the capacitor can respond to that call for more power much faster than the power supply.
> 3 votes

# Answer
Every time a logic circuit switches from a 0 to a 1 or a 1 to a 0, the 1 and 0 transistors are on at the same time for a short period of time. In MOS circuits, this is combined with the need to charge the gate of the 1 or 0 transistor (Charge is what capacitors store, gates of MOS transistors are capacitors!).

Since all wiring is inductive, the faster the current, the higher the impedance from the main power supply and the switching device (Your processor or sensor etc). The terms bypass and decoupling mean the same thing: You are providing a local charge well to supply fast current demands by bypassing the main power system, i.e. supplying current via a different path and thus decoupling the switching device from the inductively isolated main supply.

This is also why we used to use two types of capacitors for decoupling: A 0.1uF ceramic and a 1uF electrolytic for instance... You couldn't get the whole 1uF in a low resistance ceramic to cover both the Low and High speed transients without paying a lot so you used two or more parts, each covering a portion of the spectrum. Nowadays a single SMT ceramic with low ESR, low ESL and no lead wires can do the whole job and is usually pretty economical.

Another factor is radiation: A ringing voltage transient current through inductive wiring acts just like an antenna.
> 1 votes

---
Tags: electronics
---


# Question
Title: Arduino Mega vs. RasPi Pro Cons in 3D Printing
Recently I tooked a look at cheaper China 3D Printers and noticed they're all based on RepRap (mostly using Ramps for the electronics part) and the next day i saw a 2d Plotter based in the pi. Then I asked myself why the Pi isnt used in 3d printers.

Question: Why is the Arduino Mega/Due more used in 3D Printing than the RasPi? What are the Pro's and Con's for 3D Printing on the two systems?

# Answer
A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.

It is possible to use realtime extensions to the Linux kernel to get reasonable performance. And it is also possible to run something simpler than Linux on the pi.

However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a dollar or three more expensive than it "should be"). If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .

People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive. In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job.

Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.
> 2 votes

---
Tags: arduino-mega
---


title: Using Arduino to learn AVR programming

text:
# Question
Title: Using Arduino to learn AVR programming
I want to learn AVR C programming instead of arduino programming. I have an arduino UNO board and few Atmega328 chips that I bought, and Atmel studio for programming. Can I use Arduino Uno board as programmer to flash the chips from Atmel Studio? Or any other alternatives?

# Answer
> 1 votes
If your chips have a bootloader already installed in them, you can use any USB -\> Serial cable (FTDI cable) to program them in-circuit on their Rx/Tx pins. If not, you can use the Uno to program a boot loader into them (one time) and program them with the cable from then on.

To use standard C, you can use the bare chips or the UNO. You'll want a different environment than the Arduino IDE, though. That can be anything from an editor, the the gnu compiler tools run from a command line, to almost any other IDE. A number of people, myself included, use the Eclipse IDE with an AVR plug-in and do almost everything from writing the code to programming the AVR from within it. (I say 'almost' only because I personally prefer a full-blown programming editor, run outside of the IDE, for initial creation of sizeable projects or major edits and rewrites. That isn't necessary, though).

# Answer
> 1 votes
If you're starting out then Atmel Studio is a good option - it's very easy to install and get up and running, and I use it.

To use an Arduino as an ISP you're going to need to use AVRDude. You can configure Atmel Studio to flash chips using AVRDude - I struggled with this but eventually got it working, you can look here if it will help - not specifically for the Arduino as ISP, but should get you started.

Finally you should also double-check whether you have ATmega328-PU or ATmega328P-PU - AVRDude doesn't support the ATmega328-PU (without the P) so you'll need to do a workaround (again something that I've been caught out with in the past, \[here's how I worked around it\] (http://www.crash-bang.com/resource/bootload-atmega328/)

Good luck - programming the AVR directly is more challenging but gives you more control.

# Answer
> 0 votes
> I want to learn AVR C programming instead of arduino programming.

It's not really clear what you think the difference is. You can use the Arduino IDE to do "straight AVR" programming, for example:

```
int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

```

The AVR register names (eg. DDRB, PINB, PORTB and so on) will be included by the IDE, however you don't have to use a single Arduino library or function if you don't want to.

# Answer
> 0 votes
You can use the Atmel Studio + Visual Micro plugin to easily get started with atmega328 + support for the uno board (easily program, use arduino libraries etc). Checkout here. http://www.visualmicro.com/page/Arduino-for-Atmel-Studio.aspx

---
Tags: arduino-uno, avr, programmer, atmel-studio
---


# Question
Title: How come people connect their arduinos to buzzers without any coil protection?
If you connect your arduino to a motor you use this schematic:

However, when it comes to buzzers, which also have a coil, no one protects the circuit:

What the hell is going on? Are these just buzzers "coiless"? How can I find the type of buzzer I have?

# Answer
> 2 votes
That kind of "buzzer" doesn't have a coil. It is a "Piezo Transducer" and uses a crystal to produce the sound.

When you're using a real speaker and producing sound you are doing it very differently to switching a motor or a relay on and off. You're generating a much smoother waveform and you don't have the sharp "ON-OFF" that causes a collapse of the magnetic field. You're actually gradually reducing the power and then reversing it to remove the magnetic field then apply a new one in the opposite direction (if you have wired it right of course).

Also the currents involved in driving a speaker like that are minuscule compared to switching a relay, especially when driven direct from the Arduino. For louder volumes you will use an amplifier, and that deals with the whole protection within itself since it is designed to drive a speaker.

---
Tags: arduino-uno, motor, electronics
---


# Question
Title: Getting random values on Arduino Duemilanove 328
I am using Arduino Duemilanove 328,and running the AnalogReadSerial example sketch.

Even when nothing is connected to the Arduino board it still shows a value of about 350 out of 1023. Ideally it should have shown 0 out of 1023 when nothing is connected to Arduino.

So how can I solve this problem?

# Answer
Why do you think it should show 0 when not connected to anything?

Does the antenna of your radio give a zero signal just because the end isn't connected to anything? An Arduino's input pin (either analog or digital) is just the same. If it isn't connected to anything then it just picks up noise - be that radio transmissions, induction from nearby mains wiring, neutrinos from Alpha Centauri... Basically if it's not connected to anything then there is *no way* you can possibly know what the value should be since there *is no set value*.

In order to read 0 on the ADC the ADC has to be connected 0V. That means connect it to ground.
> 1 votes

---
Tags: arduino-uno
---


title: Need help shrinking a code

text:
# Question
Title: Need help shrinking a code
I'am new to Arduino and c++

i get his code from the INTERNET

```
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}
int f = 0, pos;
void loop() {
    boolean has_request = false;
    String in = "";
    if (Serial.available()) {
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
    }
    if (has_request) {
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "<html>\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.</html>";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

```

see this link if you cant see the code formated here in the site

this code is used for the Arduino uno wifi shield it is working perfectly except it is too complicated for me while loop inside a while loop

and i don't want to do frequency i only need to send turn on or off without any complexity

anyone could help me ?

# Answer
> 0 votes
I would recommend starting out with some easy stuff you understand or making code yourself... Starting out with code you don't understand will backfire you.

**I'll explain the code for you anyway.**

This part will "set everything up". The serial connection and the direction (in/output) of the pin(s).

```
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

```

Somehow did the person who made this think it was logical to put this here instead of on the very top of code. There are 2 integer variables declared here of which one is initialized with 0. (f).

```
int f = 0, pos;

```

This part of the code (untill the very last bracket) will be ran continiously, in a "loop". Many, if not all, embedded systems will run "forever".

```
void loop() {

```

This is basically a "flag", it indicates if something has, or has not happened. At this point it's only initialized.

```
    boolean has_request = false;

```

Also we're keeping a buffer (text string) of the characters we receive.

```
    String in = "";

```

Check if there are characters in our serial buffer.

```
    if (Serial.available()) {

```

If so, we empty our own buffer.

```
        in = "";

```

And keep doing this code.

```
        while (true) {  // should add time out here

```

We wait until the next character is ready.

```
            while (Serial.available() == false) {}

```

And add it to our buffer.

```
            in += (char)(Serial.read());

```

But when we see our buffer ends with \r\n\r\n (carriage return, line break x2).

```
            if (in.endsWith("\r\n\r\n")) {

```

We're going to set te flag, indicating that we have received a message. And we stop the: "Keep doing this code".

```
                has_request = true;  break;
            }
        }//(this is actually the parenthesis of the while(true) which we break out.

    }

```

So we had this message, right? Let's do the following:

```
    if (has_request) {

```

Parse the variable in the GET request (f=??) to an int.

```
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }

```

Send a 200OK (with body) back to the thing that sent the http request (actually pretty neat to do so.)

```
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "<html>\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.</html>";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }

```

We also keep doing this blinking. (Fun fact: While receiving/sending stuff, your blinking will stop/desync. This is because the receive/send code is blocking the blinking code. Making the blinking hardware and/or receive/send interrupt based will improve the systems reaction time and efficiency.)

```
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

```

**But how will we make this better? Or atleast easier to read?** By using functions, you can split up the code, and giving the functions a logic name, it all becomes quite obvious. The whole thing is doing 3 jobs: Blinking a led on a given frequency. Receiving requests/commands through serial (handling serial). And handling these requests afterwards.

```
void BlinkLed(int f);
void HandleRequest();
void HandleSerial();

int f = 0, pos;//Pos doesn't have to be a global variable...

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    boolean has_request = false;//Reset the flag every loop.
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        HandleSerial();
    }
    if (has_request) {
        HandleRequest();
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

void HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
}

void HandleRequest(void){

        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "<html>\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.</html>";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
}

```

V2 (more likely to compile, but kinda changes the structure):

```
void BlinkLed(int f);
void HandleRequest();
boolean HandleSerial();

int f = 0;//Frequency of the led (blinking)

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        if(HandleSerial()){
            HandleRequest();
        }
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

boolean HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                return true;
            }
        }
        return false;
}

void HandleRequest(void){
    int i1 = in.indexOf("GET /blink?f="), i2;
    if (i1 != -1) {
        i2 = in.indexOf(" ", i1+13);
        f = in.substring(i1+13, i2).toInt();
    }
    Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
    String sr = "<!DOCTYPE HTML>\n";
    sr += "<html>\n";
    sr += "LED frequency: ";
    sr += f;
    sr += "Hz.</html>";
    Serial.print("Content-Length: ");
    Serial.print(sr.length());
    Serial.print("\r\n\r\n");
    Serial.print(sr);
}

```

We can even make it more nicer by:

* using hardware (PWM) to toggle/time the led.
* rewriting the serial handling code... (https://www.arduino.cc/en/Serial/ReadStringUntil)
* Using printf() to format the serial.prints on one line...
* Make the receive/send code interrupt based, so that it will only take short amounts of time of your code, instead of continously waiting in a while, you can do stuff in the meanwhile ;)
* using classes.

# Answer
> 3 votes
There is only one "while loop inside a while loop" and that is hardly complex:

```
while (Serial.available() == false) {}

```

All that means is "Wait for something to become available on the serial". That is ALL it does.

There is nothing even remotely complex there. True, it may not be very well written (as is the case with lots of code on t'interwebs). It's time to start learning how the code works so you can write your own.

# Answer
> 1 votes
Here is my take at this. I realize that I did not really make the program simpler, but hopefully better in some respects, as it avoids blocking reads and heap memory allocation. Be warned however that I did not test it. It compiles fine though.

Preamble, hopefully simple enough that it requires no comments:

```
const uint8_t led_pin = 13;

void setup() {
    Serial.begin(57600);
    pinMode(led_pin, OUTPUT);
}

```

Next, here is a function to read the HTTP request. A few things are worth noting in this function:

* It is non-blocking: if there is not data in the serial buffer, it will return `NULL` immediately. This is to prevent the whole program from hanging if the client does not terminate its request.
* It only saves the first 31 bytes of the request. This is because browsers tend to add lots of useless headers, which can be unfriendly to the memory of a small Arduino. And the only interesting piece of data is at the very beginning anyway.
* The request terminating sequence (CR LF CR LF) is detected without having to store it in the buffer, just by counting how many consecutive bytes of that sequence we have already received.
* Declaring the function as `static` makes it possible for the compiler to inline it, which it does as it is only called from one place. This makes for a smaller executable.

```
/*
 * Non-blocking read. Returns the first bytes of the request in a static
 * buffer, or NULL if we do not have a complete request yet.
 */
static char * read_request() {
    static char buffer[32];
    static uint8_t pos;
    static uint8_t crlf_bytes;  // bytes of "\r\n\r\n" received

    while (Serial.available()) {
        char c = Serial.read();

        // Store the received byte if there is enough room.
        if (pos < sizeof buffer - 1)
            buffer[pos++] = c;

        // Update the count of consecutive CRLF bytes received.
        if ((c == '\r' && crlf_bytes % 2 == 0)
         || (c == '\n' && crlf_bytes % 2 == 1))
            crlf_bytes++;
        else
            crlf_bytes = 0;

        // Return the buffer if we have a complete request.
        if (crlf_bytes == 4) {
            buffer[pos] = '\0';  // terminate the string
            pos = 0;
            crlf_bytes = 0;
            return buffer;
        }
    }
    return NULL;
}

```

Parsing the request is done by a different function. Here, I do not search for the "GET /blink?f=" string, because it *must* be at the very beginning for the request to be valid.

```
/*
 * Returns the requested frequency, or 0 if nothing valid is found.
 */
static int parse_request(char *request) {

    /* The "GET" should be at the very beginning. */
    if (strncmp(request, "GET /blink?f=", 13) != 0)
        return 0;

    return atoi(request + 13);
}

```

Now we can send the response to the client, telling it how we parsed the frequency. I avoid using `String`, as it involves heap allocation, and I put the bulk of the response in PROGMEM (`F()` macro) to save RAM. I also added a `<title>` to make it valid HTML.

```
/*
 * Tell the client how we understood the requested frequency.
 */
static void send_response(int freq) {
    char freq_str[12];
    itoa(freq, freq_str, 10);
    Serial.print(F("HTTP/1.1 200 OK\r\n"
                   "Content-Type: text/html\r\n"
                   "Content-Length: "));
    Serial.print(84 + strlen(freq_str));
    Serial.print(F("\r\nConnection: close\r\n\r\n"
                   "<!DOCTYPE html>\n"
                   "<html><head><title>Blink</title></head>\n"
                   "LED frequency: "));
    Serial.print(freq_str);
    Serial.print(F(" Hz.\n</html>\n"));
}

```

The next function blinks the LED in a rollover-safe fashion. Storing the current LED state in a static variable avoids a call to `digitalRead()`.

```
static void blink_led(unsigned long toggle_time) {
    static uint8_t led_state;
    static unsigned long last_toggle;
    unsigned long now = millis();
    if (now - last_toggle > toggle_time) {
        led_state = !led_state;
        digitalWrite(led_pin, led_state);
        last_toggle = now;
    }
}

```

Putting it all together, the main `loop()` ends up being quite straight forward:

```
void loop() {
    static unsigned long period = 1000;
    char * request = read_request();
    if (request) {
        int freq = parse_request(request);
        if (freq > 0) period = 1000 / freq;
        send_response(freq);
    }
    blink_led(period);
}

```

**PS**: My version is significantly larger than the original at the source level (66 v.s. 44 source lines of code), but the compiled program is smaller in both flash and RAM usage:

```
text    data     bss     version
5646     168     197     original
3316      40     218     my version

```

---
Tags: arduino-uno, shields, wifi
---