# Question
Title: Requesting references for learning about the upload process
I would like to know of references that discuss the process of uploading code onto an Arduino board. I have read this reference on hacking the Arduino and an outline of the build process. I also found this segment on creating Arduino libraries informative.

Overall I am interested in tracing through an upload process to learn more detail about how the programming works. I would like to understand which C-libraries are used. I would like to understand how the code is uploaded onto the Arduino. One example that I would like to see is an direct upload of C or C++ code without using the IDE gui. I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++). I would ideally like to read about something like this which makes use of the Arduino libraries.

Looking forward to hearing back responses, and being a part of this community. Any references and comments appreciated.

---

**Edit #1** (request for more information from the accepted answer):

*How does the main sketch trace through the C/C++ code?*

For example, in the make file shown in the accepted answer:

```
$(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o

```

*Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?*

I would think so, being that it is compiled every time we change the main sketch.

*Lastly, how is the outputted .hex file uploaded to the board?*

---

**Edit #2** Trouble compiling with make method

I am having issues with the manual compiling process, I am using *Arduino 1.6.5 r5*. It seems that *malloc.c* and *realloc.c* are not in the same place as they were in IDE 1.0.6.. Here is the makefile.

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

The build fails unless the lines involving those two functions are commented out. I searched in the directories but had no luck in finding the libraries, so I decided to move forward in testing things out.

Here is the file I am using as *Blink.cpp*.

```
#include <Arduino.h>

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

void loop(){
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);              // wait for a second
}

```

Again, the *build does compile* ignoring *malloc* and *realloc*. I am unsure of whether these are critical libraries as I am not very familiar with C/C++. While the libraries do compile, *there is an error* derived from the `delay()` function in *Blink.cpp*.

Here is that:

```
"/home/wiz/programs/arduino-1.6.5-r5/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o Blink.cpp.elf Blink.cpp.o core.a -lm
core.a(wiring.c.o): In function `delay':
/home/wiz/programs/arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/wiring.c:113: undefined reference to `yield'
collect2: error: ld returned 1 exit status
make: *** [build] Error 1

```

I am unsure at this point whether or not this error is related to the fact that *malloc* and *realloc* have not been compiled. I have traced back into the *wiring.c* file to find out where `yield()` was. That file starts with an `#include "wiring_private.h"` and here is the delay function and yield:

```
void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                yield();
                if (((uint16_t)micros() - start) >= 1000) {
                        ms--;
                        start += 1000;
                }
        }
}

```

Here are the include statements from the *wiring\_private.h* header.

```
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <stdarg.h>

#include "Arduino.h"

```

Perhaps on of these contain the `yield()` function, which is not being seen correctly?

Does anyone have any advice for what I am doing wrong regarding building manually with 1.6.5? Any comments or further comments will be appreciated.

---

**Edit #3** Identified where `yield()` function is located.

*Project directory:*

```
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── Blink.cpp
├── Blink.cpp.d
├── Blink.cpp.o
├── CDC.cpp
├── CDC.cpp.d
├── CDC.cpp.o
├── Client.h
├── core.a
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.cpp.d
├── HardwareSerial.cpp.o
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── HID.cpp.d
├── HID.cpp.o
├── hooks.c
├── IPAddress.cpp
├── IPAddress.cpp.d
├── IPAddress.cpp.o
├── IPAddress.h
├── main.cpp
├── main.cpp.d
├── main.cpp.o
├── new.cpp
├── new.cpp.d
├── new.cpp.o
├── new.h
├── Printable.h
├── Print.cpp
├── Print.cpp.d
├── Print.cpp.o
├── Print.h
├── run.mk
├── run.mk~
├── Server.h
├── Stream.cpp
├── Stream.cpp.d
├── Stream.cpp.o
├── Stream.h
├── Tone.cpp
├── Tone.cpp.d
├── Tone.cpp.o
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.cpp.d
├── USBCore.cpp.o
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── WInterrupts.c.d
├── WInterrupts.c.o
├── wiring_analog.c
├── wiring_analog.c.d
├── wiring_analog.c.o
├── wiring.c
├── wiring.c.d
├── wiring.c.o
├── wiring_digital.c
├── wiring_digital.c.d
├── wiring_digital.c.o
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.c.d
├── wiring_pulse.c.o
├── wiring_pulse.S
├── wiring_shift.c
├── wiring_shift.c.d
├── wiring_shift.c.o
├── WMath.cpp
├── WMath.cpp.d
├── WMath.cpp.o
├── WString.cpp
├── WString.cpp.d
├── WString.cpp.o
└── WString.h

```

`yield()` is located in *hooks.c*. I do not understand why the function is not available to *wiring.c*.

---

**Edit #4** Compilation working

Structure of *arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino*:

```
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── CDC.cpp
├── Client.h
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── hooks.c
├── IPAddress.cpp
├── IPAddress.h
├── main.cpp
├── new.cpp
├── new.h
├── Printable.h
├── Print.cpp
├── Print.h
├── Server.h
├── Stream.cpp
├── Stream.h
├── Tone.cpp
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── wiring_analog.c
├── wiring.c
├── wiring_digital.c
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.S
├── wiring_shift.c
├── WMath.cpp
├── WString.cpp
└── WString.h

```

The reason the `yield()` function was not recognized was because I was not compiling with *1.6.5* correctly. Below is an updated *makefile* that compiles the *Blink.cpp* seemingly correct. I have yet to verify the sketch works on upload to the Arduino (via `avrdude`). The mistake was that I did not compile `abi.cpp`, `HardwareSerialx.cpp`(0-3), and `hooks.c`. `hooks.c` is where the `yield()` is located.

Updated *makefile*:

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)hooks.c -o hooks.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)abi.cpp -o abi.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial0.cpp -o HardwareSerial0.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial1.cpp -o HardwareSerial1.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial2.cpp -o HardwareSerial2.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial3.cpp -o HardwareSerial3.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a hooks.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a abi.cpp.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HardwareSerial0.cpp.o
    $(AR) rcs core.a HardwareSerial1.cpp.o
    $(AR) rcs core.a HardwareSerial2.cpp.o
    $(AR) rcs core.a HardwareSerial3.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

Are *malloc.c* and *realloc.c* being used anymore? I searched across *1.6.5* for a directory similar to *avr-libc*, I couldn't find anything. I'm guessing they are no longer in use.

---

**Edit #5** Upload via *avrdude*

Basically this command worked for my board (Arduino Uno SMD):

```
avrdude -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:/path/to/Blink.cpp.hex:i

```

This is all to say that the latter makefile in this post correctly builds the *.hex* file. Which can then successfully be uploaded onto the board. (Using Arduino 1.6.5).

# Answer
> I am interested in tracing through an upload process to learn more detail ...

I covered the uploading process in some detail here: What happens when code is uploaded using the bootloader?

---

> I would like to understand which C-libraries are used

See my post about How the IDE organizes things

---

> One example that I would like to see is an direct upload of C or C++ code without using the IDE gui.

I wrote a simple Makefile on the Arduino Forum:

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

There are quite a few more complex ones around.

---

> I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++).

Here:

```
int main ()
 {
 }

```

---

> Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
>
> I would think so, being that it is compiled every time we change the main sketch.

I'm not sure I understand the part about "transfer through" but basically functions which are needed in the main sketch are linked into the combined file by the linker.

Effectively these are the main parts:

```
# Compile main sketch
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o

# Compile libraries
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
...

# Remove temporary "combined libraries" file
    rm core.a

# Add compiled libraries into combined file "core.a"
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
...

# Link main sketch to combined libraries (linker will discard things not needed)
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm

# Make an .eep (EEPROM) file
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep

# Make the main .hex file
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

---

> Lastly, how is the outputted .hex file uploaded to the board?

There are various ways of achieving this. The IDE calls the program `avrdude` which is designed to upload a .hex file to a processor. You can also just copy the .hex file to an SD card and upload it using a board programmer.

---

> Are malloc.c and realloc.c being used anymore?

They **are** being used, the trick is to find them.

I can't see them being directly linked in a 1.6.5 compiler output, so I am assuming (I can't prove it right now) that they are linked in by default from libc.a (the default C library). Being a default library it is not mentioned on the linker line.

In my (Linux) installation I found that library here:

```
~/Development/arduino-1.6.5-r5/hardware/tools/avr/avr/lib/libc.a

```

If you do a `nm` on it you find this (amongst other things):

```
malloc.o:
00000002 C __brkval
         U __do_clear_bss
         U __do_copy_data
00000002 C __flp
00000146 T free
         U __heap_end
         U __heap_start
00000000 T malloc
00000000 D __malloc_heap_end
00000002 D __malloc_heap_start
00000004 D __malloc_margin
0000003e a __SP_H__
0000003d a __SP_L__
0000003f a __SREG__
00000000 a __tmp_reg__
00000001 a __zero_reg__

```

From `man nm`:

```
  "D"
  "d" The symbol is in the initialized data section.
 ...
  "T"
  "t" The symbol is in the text (code) section.

```

---

See http://www.linuxtopia.org/online\_books/an\_introduction\_to\_gcc/gccintro\_17.html :

> The C standard library itself is stored in '/usr/lib/libc.a' and contains functions specified in the ANSI/ISO C standard, such as 'printf'---this library is linked by default for every C program.

---

I am guessing here that `malloc` and `free` moved into the standard (default) library since version 1.0.6 (or they wanted to override it with a bugfix) and it is now being found, by default, in the standard C library as described above.

You should be able to find more about AVR libc at its page: http://www.nongnu.org/avr-libc/
> 2 votes

---
Tags: uploading, core-libraries
---


title: atmega328 raspberry pi 2 communication

text:
# Question
Title: atmega328 raspberry pi 2 communication
I have an atmega328p (running on it's internal 8mhz clock) receiving data over rf. I need the data received to be communicated to the raspberry pi 2 using its gpio pins, I cannot use USB. I don't have the budget for a gertduino. Is there any way to do this directly? I only need to be able to receive serial output on the pi, no uploading sketches.

# Answer
> 1 votes
Both the Arduino and the Raspberry PI have interfaces like SPI, I2C and UART. These interfaces will make it easy for you to communicate between the two. I suggest you search for UART unless you need a very high data throughput, then you need to go for SPI. But unless you want to send over a thousand messages per second UART will work just fine.

---
Tags: serial, atmega328
---


# Question
Title: How to read the serial data from a ATMEGA8 on a PC using Arduino?
I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?

I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?

I have the AVR code which was burned on the IC, so I can provide you with more information if you need.

# Answer
> 1 votes
If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.

# Answer
> 0 votes
You can download this example code to your Arduino UNO...

https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

Make sure the baud rate on the line `mySerial.begin(4800)` to match the baud rate your device is sending.

Then run "Serial Terminal" from the Arduino IDE and connect the output of your device to pin 10 on the Arduino.

If the baud rate is correct, you should see the Serial output from your device in the serial terminal window.

## Why you might not want to direct connect

Here is the schematic of the serial port section of the Arduino UNO...

The TX pin on the header is connected directly connected to the TXD/PD1 pin on the ATMEGA chip as highlighted in red. This pin will be actively driven if any of the following happen...

1. There is a sketch running on the Arduino than enables the serial port (i.e. includes `Serial.begin()`).
2. There is a sketch running on the Arduino that enables pin 1 as output (i.e. includes `pinMode(1,OUTPUT);`).
3. The Arduino reboots and runs the bootloader, which always briefly enables the serial port on startup.

There are some devices that can be permanently damaged by having their serial output tied to an actively driven signal, especially a +5 volt one like we have here. The BBB is one of them (I know from experience!).

One response suggested downloading the `BlinkMe` sketch into the Arduino, presumably to make sure there is not another sketch running that could enable the serial port. This is the right idea, but you have to keep in mind that the UNO will reboot anytime the RTS line is toggled. Here is a not-so-far-fetched scenario...

1. You load `BlinkMe` into the UNO.
2. You connect the device to the TX pin on the UNO.
3. You launch `Tools-Serial Monitor` from the Arduino IDE to see the serial data.
4. The Serial Monitor window opens and toggles the RTS line (does this every time you launch it).
5. The UNO reboots.
6. The bootloader runs and enables the serial port on the ATMEGA.
7. The connected device is cooked.

Also keep in mind that even if the attached device can tolerate being connected to an actively driven signal, once you connect another signal to the Arduino TX pin then you loose the ability to communicate with the Arduino.

Loading the `Softserial` sketch takes the same number of steps as loading the `BlinkMe` sketch, reduces the chance of of damaging the connected device, and also allows you to keep access to the Arduino while you are doing all this.

---
Tags: uart
---


# Question
Title: Dimming 6W (24V DC 0.25A) LEDs using Arduino
I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A

I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.

Would a TIP122 transistor be ok?

Any tips for keeping the transistor off until the dimming process starts?

# Answer
I would suggest using the CAT4101 constant current sink PWM LED driver. It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you. You can then control it through the PWM input pin direct from the Arduino.
> 1 votes

---
Tags: led, pwm, transistor, arduino-duemilanove, heat
---


# Question
Title: Debouncing a limit switch in Arduino ISR with delays
I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.

As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.

```
const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
    pinMode(lsOuterLeftIn, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void  loop() {
    if (lsEngaged) digitalWrite(LED, HIGH);
    else digitalWrite(LED, LOW);
}
void ISR1(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}

```

But, here is my problem. I came upon this Arduino documentation page, and it says

```
"Since delay() requires interrupts to work, it will not work if called inside an ISR. "

```

But, I do make use of `delay()` inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the `delay()` function could malfunction on me as the documentation says?

# Answer
What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.

Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.
> 1 votes

---
Tags: arduino-uno, arduino-mega, interrupt, button, debounce
---


# Question
Title: Can I connect an output pin to an input pin to measure it's voltage on a single board?
So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through `Serial` and then plot it in python.

Sorry if this is a basic question. Thanks

# Answer
PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.

Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.

You could Google "Active low pass filter" for a lot of schematics and formula.

BUT

To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.

If your sample rate is close to Nyquist rates, you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.

Or preferably have a sample rate \> 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.
> 2 votes

---
Tags: pins, pwm
---


# Question
Title: Are DAC pins useful for anything besides working with audio?
Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?

# Answer
DACs have many uses outside the realm of audio.

Basically a DAC is used any time you want to generate a specific voltage for whatever you need it for - that could be to generate a waveform for audio, or it could be for any other situation, such as:

* Setting an offset point for an op-amp
* Creating a comparison voltage for comparing another signal to
* Controlling the bias voltage of a transistor
* Generating a specific reference voltage for an external (or even the internal) ADC

The list goes on. There are many places you would want to use a DAC. And why a DAC above PWM? Well basically it boils down to:

* Precision - the DAC can generate a more precise voltage than a filtered PWM signal
* Noise - the DAC generates a much smoother voltage with better response than filtered PWM which either has switching noise and fast response or less switching noise and delays in voltage level changes.
> 3 votes

# Answer
They are incredibly useful. They are essentially how you deal with the analog world.

For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna... The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!

So, yes, they are very useful. :)
> 4 votes

---
Tags: arduino-due, digital-analog-conversion
---


title: How to put arduino in sleep mode?

text:
# Question
Title: How to put arduino in sleep mode?
I need to put arduino in sleep mode. I did not find the library avr/sleep.h . From where to download it.

# Answer
`avr/sleep.h` is part of the compiler. You don't need to download it.

There are other libraries that act as a wrapper to it to make life easier:
> 3 votes

---
Tags: sleep
---


title: Cast from long to int

text:
# Question
Title: Cast from long to int
How does arduino uno cast from **long** to **int**?

Does it truncate the bits? (Does it just delete the 16 most left bits?)

# Answer
> 5 votes
Yes, it just blindly chops off the upper 16 bits. That means that the sign can change between the two.

For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.

To see that in more detail, look at the binary. 123456789 in binary is:

```
0000 0111 0101 1011 1100 1101 0001 0101

```

Truncate that at 16 bits and you get:

```
1100 1101 0001 0101

```

And of course the high (sign) bit is set, so the value is negative.

---
Tags: data-type
---


# Question
Title: Arduino WiFIWebSever - why client.println()?
I need to modify the WiFiWebServer example on the Arduino website but I am having some trouble understanding the code. I am hoping to get some advice from the community on the client-server relationship in this example so I can better modify it to suit my needs.

The problem I am having is the jump between server commands and client commands. Initially I see server commands; server.begin() in setup and server.available() in the loop. The commands quickly shift, however, as nearly all the other commands in the loop become client.println()'s.

I understand the initial client commands that deal with whether the client is available and whether it is still connected. The part I don't understand, however, are the client.read and client.println commands. Even client.read makes some sense to me since I want some communication from the client side but why does the example use client.print? The Arduino webpage defines the WiFiClientPrintln as data you write from the client to the server that it is connected to. Wouldn't I want to use server.print since the Arduino in this example is the server and the client is the computer I use to view the webpage that I built on the server?

I am using the WiFIWebServer example as a template for my project. The goal is to have the Arduino take sensor readings and post them on a webpage it hosts by acting on the server. This is quite similar to the example but I notice that I have slow update/transmission speeds and errors when a different client connects to the server. For example, if I view the website on my computer, I get the data fairly consistently If somewhat slow. If I try to view the same website off my mobile device, however, I have problems connecting, may need to refresh several times and the webpage crashes on the computer.

I am trying to troubleshoot the issue but going through the code I can't figure out the reason for the client.println()'s instead of server.println(). Even if that isn't the cause of my multi-client issue, I would like a better understanding of the code before going forward so would appreciate any guidance you can provide.

# Answer
> 1 votes
The confusion you have arises from the context of the command.

The server.\* commands manipulate the server instance - that is, the actively listening socket that is waiting for connections.

The client.\* commands change their meaning depending on if you are a server waiting for connections or a client that is making a connection.

In the latter case client.print() sends data to the server.

In the former case, on a server, the client.\* commands refer to a specific client that has made a connection to the server. Using client.print() in this instance sends data *to* the currently connected client.

So "client" can be thought of as "the connection between me and the remote end" however that connection was created - either by "me" specifically connecting to the remote end, or the remote end connecting to my "server" instance and a new "client" being spawned from it for this one connection.

Remember - a client can only connect to one server, but a server can have many connections from many different clients, and it is those *client* connections that you talk to.

# Answer
> 0 votes
client.println() is sending data to a specific client.

server.println() is sending data to every client that is connected to the server.

Also, i believe that the arduino keeps sending data to the client instead of stopping the request. You should have some javascript that updates the value say... every 5 seconds or so... Or you could have a

```
<meta http-equiv="refresh" content="5">

```

inside the part which would tell the browser to refresh the page every 5 seconds instead of using the header

See http://tentencraft.net/demo1.php vs http://tentencraft.net/demo2.php

---
Tags: wifi, web-server
---


# Question
Title: Accuracy of liquid level measurement using sonar sensor
Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?

I have a cylinder shaped **horizontal** 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen.

**UPDATE! Today I found this helpful page: Home Heating Hacking Part 1 or How to Measure an Oil Tank. I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.**

# Answer
I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good. Couple of points:

1.polling occurs hourly.

2.I only power the ultrasonic sensor just before taking a reading.

3.Has a sound detection sensor to alert on water pump overrun, ie a leak.

good luck
> 5 votes

---
Tags: home-automation
---


# Question
Title: pushing accelerometer data in packets from an arduino due to the pc and unto processing
I'm quite a newbie to this and I've been struggling for sometime now with my school project, trying to find a way to send accelerometer data from my MMA7361 in data packets, I understand that I have to send the data in packets, but I'm having problems going about it. One of the requirements of the project is that I have to send the data in array-packets of all the individual axes (e.g. a buffer array to hold the x-axis value, another for the y-axis value and also for the z-axis value). I have read quite a lot of documentation on the internet about this but putting it together is a challenge. Below is the infamous MMA7361 code sketch, do please help out if you can thankyou.

```
    #include <AcceleroMMA7361.h>

    AcceleroMMA7361 accelero;
    int x;
    int y;
    int z;

    void setup(){
        Serial.begin(9600);
        accelero.begin(13, 12, 11, 10, A0, A1, A2);
        accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
        accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
        accelero.calibrate();
    }

    void loop(){
        x = accelero.getXRaw();
        y = accelero.getYRaw();
        z = accelero.getZRaw();
        Serial.print("\nx: ");
        Serial.print(x);
        Serial.print("\ty: ");
        Serial.print(y);
        Serial.print("\tz: ");
        Serial.print(z);
        delay(500);                                     //(make it readable)
    }

```

# Answer
It's pretty simple to store the x, y and z co-ordinates in three separate arrays. Instead of storing them in single `int` variables you can just store them in `int` arrays. You can make three arrays that are of size 1000 a store the raw values there. In order to iterate through the arrays within `loop()` you can set up `i` at global scope and include an if statement that will know when the arrays are filled, for example `if (i == 1000)` and within this if statement you can set up a `for` loop that will iterate through the arrays and print their values and after reset `i` to `0` and then reset the buffer arrays i.e. fill them with zeroes. This last step is not needed since they will be overwritten anyway but it is good to have so you don't accidentally use old values.

Also the `for` loop that will print the values will take 8 minutes with that `delay(500);` You can make this delay smaller or print the value before each `if` statement as the data comes in.

```
#include <AcceleroMMA7361.h>

AcceleroMMA7361 accelero;
int xAxisBuffer [1000] = {0};
int yAxisBuffer [1000] = {0};
int zAxisBuffer [1000] = {0};

int i = 0;

void setup(){
    Serial.begin(9600);
    accelero.begin(13, 12, 11, 10, A0, A1, A2);
    accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
    accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
    accelero.calibrate();
}

void loop(){
    // This stores the x, y and z values in their
    // respective arrays
    xAxisBuffer[i] = accelero.getXRaw();
    yAxisBuffer[i] = accelero.getYRaw();
    zAxisBuffer[i] = accelero.getZRaw();
    ++i; // moves to the next position

    if (i == 1000){ // the arrays are full
        // prints the (x, y, z) values
        // because the delay is .5 seconds it will
        // take about 8 minutes to print all 1000
        for (int j = 0; j < 1000; j++){
            Serial.print("\nx: ");
            Serial.print(xAxisBuffer[j]);
            Serial.print("\ty: ");
            Serial.print(yAxisBuffer[j]);
            Serial.print("\tz: ");
            Serial.print(zAxisBuffer[j]);
            delay(500); //(make it readable)
        }
        // restart at beginning of the arrays
        i = 0;
        // reset the arrays
        memset(xAxisBuffer,0,sizeof(xAxisBuffer));
        memset(yAxisBuffer,0,sizeof(yAxisBuffer));
        memset(zAxisBuffer,0,sizeof(zAxisBuffer));
    }
}

```
> 0 votes

---
Tags: c++, arduino-due, datalogging, processing-lang
---


# Question
Title: Writing data from multiple sensors in burst mode to an Arduino Due
I need help developing a simple sketch that can read data simultaneously from 3 analog accelerometers and send it in 'burst mode' to be stored on an SD card, to reduce the effect of latency.

I used this library to get my accelerometers to work properly, but I'm just having difficulty coming up with a sketch in the code to getting all the acceleration data out in bursts.

Your help will be much appreciated.

What I meant by 'burst mode' is that all acceleration data from all three sensors connected to the Arduino should be saved at once to the file on the SD card (a temporary measure, as I'll have to send this data via Bluetooth to a base station as I build the system up to be able to receive more data from multiple Arduinos).

Although there would be a delay of about 1/10th of a second between each reading from the three sensors, the idea behind it is to be able to read and write off the data in this said simultaneous burst mode at a high sample rate (this will be adjusted with an oscilloscope at a later stage) to prevent data from being lost or chunked up.

Here is a link to the datasheet as requested.

# Answer
What you need to do instead is to declare an array buffer of the data type you need to send, and send it through Serial. The array buffer could be of any length of your choosing, then you reiterate through on a for loop till all the contents of the buffer are read out which is essentially the burst mode you require.
> 1 votes

---
Tags: sensors, bluetooth, arduino-due, sd-card
---


# Question
Title: How to switch program in arduino using android app?
I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze. Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

# Answer
Once I made a sketch to run multiple programs. I wrote a `setup` and `loop` function for every different "program", (e.g. `setup_p1`, `setup_p2`, ... `loop_p1`, ...) and then wrote a simple `main` sketch to handle them all.

In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.

I choose to use a callback because it's faster than just checking the mode every time, at least in my case

```
// callback for loop function
typedef void (*loopfunction)();
loopfunction currentloop;

void setup()
{
  // Set dip-switch pins as input
  pinMode(MODE_PIN2,INPUT_PULLUP);
  pinMode(MODE_PIN1,INPUT_PULLUP);
  pinMode(MODE_PIN0,INPUT_PULLUP);

  // Concatenate the dip-switch values
  byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

  // choose the correct mode
  switch(mode)
  {
    case 0: // Shutdown - do nothing
            break;
    case 1: // Program 1
            setup_p1();
            currentloop = loop_p1;
            break;
    case 2: // Program 2
            setup_p2();
            currentloop = loop_p2;
            break;
    ...
  }

  // Not a valid program: halt
  if (!currentloop)
  {
    while(1);
  }
}

void loop()
{
  // Execute the current loop
  currentloop();
}

```
> 1 votes

---
Tags: robotics
---


# Question
Title: Arduino keypad matrix example? ( teensyduino )
I'm a beginner using Arduino with a Teensy 3.2 board and programming it as a usb keyboard. I have two 4 button membrane switches. Their button contacts are on pins 1-8, and the 9th pin holds a soldered together wire of both membrane switches' "ground" line or whatever it's true name is; the line that completes the circuit.

Basically when you press the buttons they are supposed to simply type "a, b, c..." respectively. I've been told I need to use a matrix for this.

I'm looking for an example of how to code a keyboard matrix that effectively supports a one row/9 column line (or vice versa?) I've been unable to find that solution online.

All I have so far is this code which, when the button on the second pin is pressed, sends tons of "AAAAAAAAAAAAAAAA" keystrokes.

```
void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send an ASCII 'A',
    Keyboard.write(65);
  }
}

```

Would anyone be able to help?

# Answer
By your description, you don't have a matrix. You have them wired as just 8 straight switches.

A matrix would be if you had the 4 switch pins of one keypad wired to the same switch pins of the other keypad, and the two common connections from the keypads wired to two separate IO pins.

At the moment your code is responding whenever a button is in the low state. Instead it needs to respond only when the button *transitions* from the high state to the low state. To do that you need to know what state all the buttons were in the previous pass through loop to compare them to what they are in this pass through loop - and if any have changed then they have either been pressed or released.

You should also implement debouncing to that you don't get false presses.

If you don't want to learn how to do all that yourself I have a handy library that will do it all for you:

If you want to convert your setup to an actual matrix to save on IO pins you want to read the Arduino Keypad tutorial:
> 1 votes

---
Tags: pins, teensy, keyboard
---


title: Arduino Pro Mini lower BOD problem

text:
# Question
Title: Arduino Pro Mini lower BOD problem
I am planing to build a project where an arduino pro mini 3.3V runs on 2 aa batteries. The standard brown out detection shuts it down at about 2.7/2.8V where it could run on lower voltages too. So I changed the efuse to get the BOD down to 1.8V. I connected a serial to usb converter and used avrdude:

```
avrdude -c avrisp -p m328p -P COM5 -b 19200 -U lfuse:w:0xff:m -U hfuse:w:0xda:m -U efuse:w:0x06:m

```

Then I tried to upload a program using the arduino 1.0.3 IDE but I got this error:

```
avrdude: stk500_getsync(): not in sync: resp=0x1c

```

With 1.6.4 I got another error:

```
    avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x75
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

```

After some googling I tried some lower baud rate (the standard seems to be 57600). With 19200 everything worked with avrdude, so I created a new entry in the boards.txt

```
    ##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328 BOD 1.8V

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=19200

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x06
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

```

And burned a bootloader using the 1.0.3 IDE again. After that I could upload a blink program. My goal is to upload a mysensors sketch though and that doesn't work. I am getting an error

```
avrdude: verification error, first mismatch at byte 0x0002
         0x69 != 0x61
avrdude: verification error; content mismatch

```

Mysensors seems to have general problems with old arduino IDEs so I tried to use the newer 1.6.4 but I can't define my own board there and if I try it without I get hte out of sync error (because it's still using the wrong baudrate I guess).

I also tried using another arduino uno as ISP =\> same results

How can I fix this? Is there a way to define my own board for 1.6.x? Whats the standard way of doing this and why does the change of the efuse results in me not beeing able to program the mini any longer?

Thanks for every answer/help!

# Answer
> 1 votes
When you go below (or above) the manufacturer's voltage/clock specifications, expect some problems. One chip may work another will not. Remember the lower the voltage normally the slower the clock needs to be. The CPUs are cut from a wafer (size and geometry specific) which may contain many thousand CPU die, they are at different locations on the wafer they will be a little different and they make more then one wafer.

Check the data sheet, it will show what clock speed will work at what voltage. As the CPU clock changes so will your baud rate so plan on recalculating that if you change the clock. Example: If you are operating with a 16MHz clock and change it to 8MHz the baud will be exactly 1/2. If at 9600 it will be 4800 unless you modify the clock dividers.

Your error indicates a potential baud rate problem. One of the funny things that happens when the voltage is above/below the manufacturer's speck not all instructions operate properly over temperature. Clock problems should be expected.

---
Tags: arduino-pro-mini, avrdude, isp, arduinoisp
---


# Question
Title: Can anyone explain how this code can be converted to work on a Arduino Uno
I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.

```
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time

# this many mm per bucket tip
CALIBRATION = 0.200
# which GPIO pin the gauge is connected to
PIN = 17
# file to log rainfall data in
LOGFILE = "log.csv"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# variable to keep track of how much rain
rain = 0

# the call back function for each bucket tip
def cb(channel):
    global rain
    rain = rain + CALIBRATION

# register the call back for pin interrupts
GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

# open the log file
file = open(LOGFILE, "a")

# display and log results
while True:
    line = "%i, %f" % (time.time(), rain)
    print(line)
    file.write(line + "\n")
    file.flush()
    rain = 0
    time.sleep(5)

# close the log file and exit nicely
file.close()
GPIO.cleanup()

```

# Answer
> 0 votes
This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes. if there is a specific programming problem it should be addressed separately instead of handing out working code.

```
const int CALIBRATION = 0.200;   //Calibration Constant
int pin = 2;                     //Pin it's on, this is int0 for uno.
volatile int rain = 0;           //Used in interrupt routine

void setup() {
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
}

void loop() {

     /* Output OR LOG DATA HERE
        Also You need a Time Library and RTC (Real Time CLock) the above
        code is for a raspberry pi that has all that. */

}

void cb() {
    rain = rain + CALIBRATION;
}

```

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


title: CAN Bus without Transceivers

text:
# Question
Title: CAN Bus without Transceivers
I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)

**Here is the detail of my effort:**

I have used this(1) library, and I want to run the CAN\_EchoTest example(2). As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.

I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:

```
CANTX1 in the schematics, refers to PIN with the label '53' on the board.
CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

```

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.

what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.

Thank you in advance

(1) github.com/collin80/due\_can

(2) github.com/collin80/due\_can/tree/master/examples/CAN\_EchoTest

(3) www.mikrocontroller.net/attachment/28831/siemens\_AP2921.pdf

(4) electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus

(5) www.keil.com/download/files/canprimer\_v2.pdf

(6) www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

# Answer
You will have to play some games to make it work. CAN is a bus with dominate and recessive states. This is how it arbitrates. When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive. At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.

You can simulate this with a few transistors (not real CAN but will work). Monitor the bus with the receive side and drive it with the transistor with a pull up resistor. When the transistor is on that is the dominate state when the transistor is off that is the recessive state. This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send. Transceivers are very cheep on eBay and they have the Maxim chip which is very good. Good Luck, Gil
> 2 votes

---
Tags: pins, arduino-due, can-bus
---


title: H-Bridge L298N motor driver

text:
# Question
Title: H-Bridge L298N motor driver
I have 2 motors connected to a dual H-Bridge motor driver and the H-bridge connected to an arduino uno, It was working fine at first but now my motors are spinning very slow and the car bearly moves, I have changed the batteries but still moves slow and with no power, please help

# Answer
You can try to bisect the problem.

Remove the Arduino and drive the motors with wires: replace the input for the pwm signal with a +Vcc and you will get the same as if the Arduino was outputting a PWM with 100% duty cycle.

This should allow you to diagnose if there is a problem with the driver/motors.

If that shows no problem and the wheels spin as expected, then you have some issue (either sw or electrical with the Arduino).

But at least you can halve the complexity of the problem.
> 3 votes

---
Tags: arduino-uno, motor, shields
---


# Question
Title: Is there a way to use functions defined in a library in any class?
I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit\_ST7735 + Adafruit\_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.

So... For example there's a function public void drawRect(); in Adafruit\_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?

Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.

I've tried a bunch of different things but I've come to a dead end.

EDIT:

main program:

```
#include "_v0_0_0.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

#include "Point.h"
#include "Rectangle.h"
#include "SomeView.h"

#define     TFT_CS  4
#define     TFT_RST 0
#define     TFT_DC  10

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
SomeView a_view;

void setup()
{
    tft.initR(INITR_BLACKTAB); // initializes the display
}

void loop()
{
    a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
    while (true) {}
}

```

SomeView.h:

```
#include "Rectangle.h"

class SomeView {
private:
    Rectangle a_rectangle;
public:
    SomeView();
    void draw();

    const Rectangle& getRectangle() const {
        return a_rectangle;
    }

    void setRectangle(const Rectangle& rectangle) {
        a_rectangle = rectangle;
    }
};

```

SomeView.cpp:

```
#include "SomeView.h"

SomeView::SomeView() :
        a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
}

void SomeView::draw() {
    a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
    a_rectangle.draw();

    a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
    a_rectangle.draw();
}

```

Rectangle.h:

```
#include "Point.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

class Rectangle{
private:
    Point p1;
    Point p2;
public:
    Rectangle();
    Rectangle(Point& p1, Point& p2);
    void setCorners(const Point& p1, const Point& p2);
    void draw();

    // ... getters and setters for the points
};

```

Rectangle.cpp:

```
#include "Rectangle.h"

Rectangle::Rectangle() : p1(), p2()
    {
    }

Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
    {
    }

void Rectangle::setCorners(const Point& p1, const Point& p2) {
    this->p1 = p1;
    this->p2 = p2;
}

// this is where I want to use a function from the adafruit library
void Rectangle::draw() {
    Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

}

```

# Answer
There are two basic methods to do what you want:

1. Inheritance
2. Pointer passing

Inheritance involves making your new class a *child* class of the Adafruit TFT class. You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class *plus* your extra functions overlaid over the top:

```
class Rectangle : public Adafruit_ST7735 {
    ...
};

```

You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class *instead* of the Adafruit class in your sketch.

That is fine if you just want one class that uses the functions from the Adafruit class. The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time. For instance, you might have:

```
class Rectangle {
    private:
        Adafruit_ST7735 *_tft;

    public:
        Rectangle(Adafruit_ST7735 &tft) : _tft(&tft) {}
};

```

Then in your function you can use:

```
void Rectangle::draw() {
    _tft->drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);
}

```

You would, of course, construct your class with:

```
Adafruit_ST7735 myTFTScreen(blah blah blah);
Rectangle myRect(myTFTScreen);

```

Then call `myRect.draw();`.
> 0 votes

# Answer
Yes, there is a way.

However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.

Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.

Your PC, for example.

C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly. From that perspective, C++ can be seen also as a superset of C, only much more complex.

Have a look at this explanation, for example. It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.

If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.

For a more systematic approach, try this.
> 0 votes

---
Tags: c++
---


# Question
Title: Is setup and loop provided for convenience?
Arduino sketches usually feature a `setup` and `loop` function. Are these functions only provided for convenience or do they actually have special purposes? (e.g.: are some operations disallowed or allowed in setup and loop)

Are these two pieces of code equivalent:

**Classic**

```
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
}

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

```

**Without loop**

```
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);

    while(true) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay(1000);
        digitalWrite(LED_BUILTIN, LOW);
        delay(1000);
    }
}

void loop() {
}

```

Is it possible to write code without either setup or loop, providing, for example, a `main` method or other entry point?

# Answer
Those pieces of code are pretty much the same.

If you look at the Arduino source code you'll see:

```
setup();

for (;;) {
  loop();
  if (serialEventRun) serialEventRun();
}

```

(I'm not sure what `serialEventRun()` does.)

I don't think you can 'overload' the `main` function declaration. Also note that the main function calls `init`, which e.g. configures the timers, so `millis()` etc. will work.
> 10 votes

# Answer
> Are these functions only provided for convenience or do they actually have special purposes?

The Arduino libraries do a tiny bit of housekeeping with `loop()`, related to serial handling.

> Are these two pieces of code equivalent:

Only if you never use serial events.

> Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Not while strictly using the Arduino libraries via the IDE; the linker will complain of either duplicate `main` definitions or of missing `setup` or `loop` definitions.
> 9 votes

# Answer
> Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

The last time I used the IDE, you could have a project with no `.ino`/`.pde` file, only `.cpp`files; since it's the mangling of the `.ino` into a `.cpp` that defines the `main` function, if you bypass that step then you can define your own `main`.

If the IDE no longer allows this (as I've heard) you can still do the same thing with e.g. a Makefile-based build outside the IDE, without giving up the Arduino libraries. The caveats that I know of are:

* You should `#include "Arduino.h"` if you want access to the library functions.
* You should call `init()` if you want the library to set up peripherals the way you're used to.
* You should put the `serialEvent` code that Gerben points out in your mainloop if you want a `serialEvent` handler to run (but you probably don't need this anyway if you want to write your own mainloop).
> 2 votes

# Answer
> Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes?

They throw in an extra function call to `init` which initializes the timers which let `millis`, `micros` and `delay` work without further effort. Other than that, no.

This code compiles (and runs) under the IDE:

```
int main ()
  {
  }

```

Effectively the IDE generates code like this:

```
int main ()
  {
  init ();  // set up timers
  setup (); // your own initialization
  while (true)
    loop ();  // stuff you want to keep doing
  }

```

They have fiddled with it since then, as Ignacio Vazquez-Abrams said, but basically you can ignore that. There is nothing particularly special about `setup` and `loop`.

You can use `main` like I showed above. You can do everything in `setup` if you want. You can do everything in `loop` if you want (if you never return from it).

Remember, you are dealing with a C++ compiler here. Functions don't have some magic significance based on their names.
> 1 votes

---
Tags: programming, c++
---


# Question
Title: What is the purpose of the howMany integer in the wire.onReceive() function from the example code?
In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.

```
 void setup() {
   Wire.begin(8);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Serial.begin(9600);           // start serial for output
}

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
   char c = Wire.read(); // receive byte as a character
   Serial.print(c);         // print the character
}
 int x = Wire.read();    // receive byte as an integer
 Serial.println(x);
}

```

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

# Answer
It tells you how many bytes have been received, and consequently how many you can read with `Wire.read()`.

Before you have read anything with `Wire.read()` `Wire.available()` will return the same value. As you read from the buffer `Wire.available()` will decrease, but `howMany` will stay the same.
> 2 votes

# Answer
The reference page https://www.arduino.cc/en/Reference/WireOnReceive states:

> Parameters
>
> handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: `void myHandler(int numBytes)`

I suggest you look at the reference pages for the functions in future before asking what they do.
> 1 votes

---
Tags: i2c
---


# Question
Title: Problem assign float to an embed class within the Linked-list libary
I have successfully implemented some code which uses a linked-list. Everything is working, except assigning a value to a float within the embeded class. When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect. However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug. I am using codebender on Chrome, and I have tried Firefox (both given same results).

Main Sketch https://codebender.cc/sketch:175995

Example of library working https://codebender.cc/sketch:176008

Can anyone help?

```
typedef void(*GF)(void);

#include "LinkedList.h"

class CsC {
    public:
        float PerS;
        GF FunctionToCall;
};

LinkedList<CsC*> TaskList = LinkedList<CsC*>();

void LEDON()
{
    digitalWrite(13,HIGH);
}
void after(float interval, String intervalDescription, GF func);

void after(float interval, String intervalDescription, GF func)
{
    float multi = 1;
    if(intervalDescription == "mins") multi *= 60;
    float delayMS = multi * interval;
    CsC *c;
    //Error if either of these lines uncommented
    //c->PerS=10000;
    //c->PerS=delayMS;
    c->FunctionToCall=func;
    TaskList.add(c);
    Serial.print(".");
}

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Serial.println("Start write task list");

    after(35,"secs",LEDON);

    Serial.println("Done");
    Serial.println("Start prog");
}
void loop()
{
    Serial.print("List=");
    Serial.print(TaskList.size());
    while(TaskList.size()>0){
        CsC *c=TaskList.shift();
        long timeout=millis()+10000;
        //long timeout=millis()+((long)(c->PerS*1000.0));
        while(millis()<timeout){
            //To indicate it is running, and to save time, I have used a delay here
            digitalWrite(13,HIGH);
            delay(250);
            digitalWrite(13,LOW);
            delay(250);
        }
        c->FunctionToCall();
    }
    Serial.print(".");
    Serial.println("complete");
    while(1){}
}

```

# Answer
One possible error is a memory leak as you did not allocate the memory to the class Try

```
CsC *c=new CsC();

```
> 1 votes

---
Tags: c++, library, class, float
---


title: Formatting and code errors?

text:
# Question
Title: Formatting and code errors?
Hello I have managed to get both the Adafruit Datalogging shield walk-through and this individual code working http://www.learn.parallax.com/reed-switch-arduino-demo separately, but trying to combine the two together I get these errors. I think I have it all arranged correctly but any help would be greatly appreciated. Board Arduino Uno and Adafruit Datalogger shield.

Errors:

```
Temp_and_Reed_Switch_data_logging_shield.ino:55:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:58:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:61:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:66:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:70:1: error: expected unqualified-id before 'for'
Temp_and_Reed_Switch_data_logging_shield.ino:70:21: error: 'i' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:70:30: error: 'i' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:80:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:84:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:85:1: error: 'Serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:87:1: error: 'Wire' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:88:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:95:1: error: 'logfile' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:97:1: error: 'serial' does not name a type
Temp_and_Reed_Switch_data_logging_shield.ino:98:1: error: expected unqualified-id before 'if'
Temp_and_Reed_Switch_data_logging_shield.ino:104:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:105:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:107:8: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:108:13: error: expected constructor, destructor, or type conversion before '(' token
Temp_and_Reed_Switch_data_logging_shield.ino:114:1: error: expected declaration before '}' token
Multiple libraries were found for "SD.h"

 Used: C:\Users\Andrew\Documents\Arduino\libraries\SD

 Not used: C:\Program Files (x86)\Arduino\libraries\SD

'Serial' does not name a type

```

Program:

```
//  SD card datalogger
// SD card attached to SPI bus as follows:
// MOSI - pin 11
// MISO - pin 12
// CLK - pin 13
// CS - pin 10

#include "SD.h"
#include <Wire.h>
#include "RTClib.h"
#include <SPI.h>

#define LOG_INTERVAL  1000 // mills between entries
#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 4
#define greenLEDpin 5

// The analog pins that connect to the sensors

#define tempPin 1                // analog 1

RTC_DS1307 RTC; // define the Real Time Clock object
const int chipSelect = 10;
const int switchPin = 2;     //     // Reed switch to digital pin 2

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while (1);
}
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println();
  //If we set WAIT_TO_START to anything but 0, the Arduino will wait until the user types something in.
#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START
}

// initialize the SD card
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(10, OUTPUT);

// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
  Serial.println("Card failed, or not present");
  // don't do anything more:
  return;
}
Serial.println("card initialized.");

// create a new file on SD Card called Logger number
char filename[] = "LOGGER00.CSV";
for (uint8_t i = 0; i < 100; i++) {
  filename[6] = i / 10 + '0';
  filename[7] = i % 10 + '0';
  if (! SD.exists(filename)) {
    // only open a new file if it doesn't exist
    logfile = SD.open(filename, FILE_WRITE);
    break;  // leave the loop!
  }
}

if (! logfile) {
  error("couldnt create file");
}

Serial.print("Logging to: ");
Serial.println(filename);

Wire.begin();
if (!RTC.begin()) {
  logfile.println("RTC failed");
#if ECHO_TO_SERIAL
  Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
}

logfile.println("millis,time,temp,reedswitch");
#if ECHO_TO_SERIAL // attempt to write out the header to the file
serial.println("millis,time,temp,reedswitch");
if (logfile.writeError || !logfile.sync()) {
  error("write header");
#endif   //ECHO_TO_SERIAL
}

pinMode(redLEDpin, OUTPUT);
pinMode(greenLEDpin, OUTPUT);

pinMode(switchPin, INPUT);        // switchPin is an input
digitalWrite(switchPin, HIGH);    // Activate internal pullup resistor
long lastDebounce1 = 0;
long debounceDelay = 500;    // Ignore bounces under 1/2 second

// If you want to set the aref to something other than 5v
//analogReference(EXTERNAL);
}

void loop(void)
{
  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.get()); // seconds since 2000
  logfile.print(", ");
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
#if ECHO_TO_SERIAL
  Serial.print(now.get()); // seconds since 2000
  Serial.print(", ");
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
#endif //ECHO_TO_SERIAL

  delay(10);
  int tempReading = analogRead(tempPin);

  // converting that reading to voltage, for 3.3v arduino use 3.3
  float voltage = tempReading * 5.0 / 1024;
  float temperatureC = (voltage - 0.5) * 100 ;

  logfile.print(", ");
  logfile.println(temperatureC);
  logfile.print(", ");
  logfile.print(reedswitch);
#if ECHO_TO_SERIAL

  Serial.print(", ");
  Serial.println(temperatureC);
  Serial.print(", ");
  Serial.print(reedswitch);
#endif //ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);
}

```

# Answer
Everything you have written between the end of `setup()` (line 55) to the start of `loop()` (line 117) is not in a function.

If you are struggling to combine two or more programs, start small and work your way to the full code.
> 2 votes

# Answer
Building furhter onto @CharlieHanson's answer, what you should do in order to fix this is probably following changes (*please note that I wrote this in order to try to get rid of the errors, the flow of the program may still not be correct, that depends entirely on how you put together the code from the files*):

**1.** Remove the bracket at line 52, just a few lines down in the `setup()`-method, below this code:

```
#endif //WAIT_TO_START

```

**2. (Maybe not nessecary, but for manageability)** Move this code:

```
long lastDebounce1 = 0;
long debounceDelay = 500;

```

-from where it currently is (just a few lines above the beginning of the `loop()`-method) to the other variable declarations (above the `error()`-method).
> 0 votes

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


title: How to resolve my Timer Interrupt issue

text:
# Question
Title: How to resolve my Timer Interrupt issue
I am trying to work with arduino timer1 interrupts to make an led blink every bit on an 8 bit number, depending on whether its a 1 or 0. However, im trying to make a basic blinking program, and it does not seem to be working.

```
#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=1;
}

void loop()
{
    digitalWrite(13,val);
    while(!val);
    val=0;
}

```

The LED doesnt blink at all! Any help would be appreceitated! thanks!

# Answer
> 1 votes
Try this instead.

```
#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=!val;
}

void loop()
{
    digitalWrite(13,val);
}

```

# Answer
> 0 votes
I'm not surprised the LED doesn't blink - the entirety of your logic in the loop() function is so bizarre as to elicit the question:

# WTF?

Let's take a look at it line by line:

```
digitalWrite(13,val);

```

Set the LED to whatever `val` is - `val` starts as 0, so the LED is off.

```
while(!val);

```

While `val` is not anything except 0, so while val is zero, do nothing. (The interrupt would escape you from this if your `val` was `volatile`)

```
val=0;

```

Set `val` to 0.

So how can `val` be anything except 0 when you do the digitalWrite?

---
Tags: arduino-uno, timers
---


# Question
Title: How can I connect more sensors when my lcd is blocking pin access?
So, I have a lcd that takes up the whole board of an arduino mega. I want to connect a temperature sensor and make a really lame weather station, but the lcd screen is totally in the road. It's a shield so this is to be expected.

I've come up with wacky ideas, like soldering to the rear of the board but I think that's a bad idea. Surely there must be a better way? The lcd shield exposes no pins.

# Answer
What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.

They are generally available as "screw terminal" shields, such as this one from iTead:
> 1 votes

# Answer
Sandwich an arduino protoshield in between and add the sensors to this board, or add some wires, so the sensor can be places "outside".
> 1 votes

---
Tags: shields
---


title: GPS coordinates

text:
# Question
Title: GPS coordinates
how do I compare coordinates I receive from the GPS module with the coordinates that I had hardcoded into the arduino, for example:

if (GPS reading \<= hardcoded) movecarforward(); else movecarback();

the coordinates I get keep going up and down which makes it difficult for me to compare and excute the function below.Please help.....

# Answer
You could check out the codes for this reverse geocaching project at https://learn.adafruit.com/reverse-geocache-engagement-box/software or the dog collar project at https://learn.adafruit.com/gps-dog-collar to get some help. For my GPS project I just wanted to display the distance and speed, so all I had to do was save the current location, subtract it from the previous location and add it to distanceTraveled. It'd be helpful if you could share your code here.
> 1 votes

---
Tags: arduino-uno, tinygps
---


title: Gain on a receiver

text:
# Question
Title: Gain on a receiver
I'm doing a project on the arduino with simple 433MHz antenna modules. And I was wondering if someone could offer clarifications on how receivers work.

I read that high gain receivers can pick up a very narrow beam of radio power and thus, can transfer data at high rates. Given that this signal is tightly focused to the transmitting end.

And a low gain receiver can pick up a much wider beam of radio power.

My question is the following. When they say "narrower beam" does that represent the amplitude of the signal or the number of different waves that are being transmitted? OR does it refer to the number of DIFFERENT frequencies it can pick up? Sorry, if my question is confusing. Happy to clarify any part of it.

My Source: http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html

# Answer
> 1 votes
Think of the receiver as a camera with a telephoto lens.

With the lens zoomed out you can see a large area. You get visual information from all over.

With the lens zoomed in you can only see a very small area. The visual information you receive is only from a very small *field of vision* and things outside that field never get to you.

It's exactly the same with radio waves except that the shape of the antenna affects the zoom instead of lenses.

---
Tags: hardware, communication, electronics
---


title: Read function in Software Serial

text:
# Question
Title: Read function in Software Serial
I have a question regarding how the read function works in Software Serial.

recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8\_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte. For instance: int x = rx.read(); //if the read is supposed to read 60, x prints 111100 int x = rx.read(); //if the read is supposed to read 226, x prints 11100010

How come the first statement doesn't print 00111100?

Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing.

# Answer
For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.
> 1 votes

---
Tags: arduino-uno, softwareserial
---


title: TMP36 probe reading 0 on analog

text:
# Question
Title: TMP36 probe reading 0 on analog
I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.

Here is an image of my circuit:

and my code:

```
int length = 5;
float airTemp = 32;

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

void loop()
{
  // loads current temperature into array
  int reading;
  float voltage;
  float temp[length];
  for (int i = 0; i < length; i++)
  {
    reading = analogRead(i);
    Serial.print(reading);
    voltage = reading * 5.0;
    voltage /= 1024;
    temp[i] = (voltage - 0.5) * 100;
  }

  // turns on/off fans based on current temperature
  for (int i = 0; i < length; i++)
  {
    pinMode(i, OUTPUT);
    if (temp[i] > airTemp)
    {
      digitalWrite(i + 8, HIGH);
    }
    else if(temp[i] <= airTemp)
    {
      digitalWrite(i + 8, LOW);
    }
  }
  delay(1000);
}

```

I learned how to read the temperature from here. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.

# Answer
> 1 votes
The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.

In other words, it is wired wrongly.

# Answer
> 0 votes
Make sure your breadboard isn't one of the ones with split power rails. If the coloured lines on the + and GND rails have a break in them you will need to bridge that break with wire.

Solid rail:

Split rail:

# Answer
> 0 votes
I figured it out. I had the temperature sensors wired wrong.

Old (Bad):

Good:

---
Tags: arduino-uno, sensors, sketch, temperature-sensor
---


# Question
Title: When I connect the Vcc and GND of my circuit to my Arduino, it is powered off?
When I connect the Vcc and GND of my circuit to the 5v and GND in my Arduino, it is powered off and stops working. What is the reason and how shall I fix it?

Reference: Serial to Parallel Shifting-Out with a 74HC595

# Answer
Note: if you are changing something have the power off.

The first thing to try is unplug the IC. If it powers up after the IC is removed it is Possibly the IC is bad; However measure the Voltages on the proto board where the IC is inserted, be sure Pin 16 is +5V when referenced to pin 8. Check the data sheet for the correct pinout, I do not know what IC you are using. If the voltage is correct it is pointing more to a bad IC.

The final check for the IC is to insert the IC and remove the ground lead to the LEDs. If the system comes up then the problem is not enough power to drive the LEDs as is. If it does not come up replace the IC. Even a momentary reverse voltage or a ESD (Electro Static Discharge) incident will damage the IC, we know is is going to fail, we do not know when.

Be sure your resistors are at least 300 Ohm or higher, with that resistance the LEDs when all on will draw a total of 80mA. If you want to do the calculations try this link: "http://www.onlineconversion.com/ohms\_law.htm".

If you want to check the LEDs, remove the IC and connect +5V one at a time to the wire that goes to the resistor from the IC. Good Luck, Gil
> 1 votes

---
Tags: power, shift-register
---


title: Sketch upload freezes during write

text:
# Question
Title: Sketch upload freezes during write
I'm trying to upload a huge sketch to my **Uno R2**. It's compiling just fine but it fails to upload at 94% of writing to flash...

The program is so large because of a big array of data in a separate .h file:

```
#include <avr/pgmspace.h>
const unsigned char PROGMEM data[] = {
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

```

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.

Unless i'm missing something, this should technically work.

Command:

```
    /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

```

Output:

```
avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/hatagashira/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         Setting bit clk period        : 5.0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 3.3
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
avrdude: writing flash (30110 bytes):

Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding

```

# Answer
My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.
> 0 votes

---
Tags: arduino-uno, uploading, sketch
---


title: How to extract number from a string?

text:
# Question
Title: How to extract number from a string?
Using LabVIEW I am sending string of data through Xbee like,

* u123
* r64
* r89
* u34
* r179

And my arduino is receiving this data. I want my arduino to read this data as a string and I want to extract numbers from these strings and feed it into two different servos. For example from u123 I want to extract 123 and feed it to servo1 and from r64 I want to extract 64 and feed it to servo2 and so on.

Arduino IDE Serial Monitor is showing nothing but Arduino's Xbee is receiving and sending data. Don't know why :(

# Answer
First collect all of the characters up to the new-line (\`\n' or line-feed) into an array of characters, and put a zero byte after the last one.

Since It looks like all of the strings you need to parse consist of one a single letter followed by the value you want, `value = atoi(inputArray[1];` will return the value as a 16-bit int. If it could be larger than 32767 but less than 65536 (probably not if you're driving a servo with it), then cast the value to unsigned.

If there might be an unknown number of characters (non-digits) preceeding the value, the C function `size_t strcspn(const char *string, const char *cset)` will return the length of the leading sub-string of `string` that does not contain characters in `cset`. So `value = atoi(inputArray[strcspn(inputArray, "0123456789")]);` will do the same thing, but calculating the array index of the first digit in the string.

(For completeness, note there is a companion function, `size_t strspn(const char *str, const char *cset);`, that returns the leading sub-string of 'string' consisting *only* of characters in `cset`).
> 1 votes

---
Tags: serial, xbee, string
---


# Question
Title: How much voltage/current do I need for multiple chips?
I have a Huzzah ESP826 Wifi breakout chip which requires 3.3V power voltage and peaks at 500mA of current, and an LED strip which requires 12V and 1A. How can I power both with one dc jack (I have a 12V 5A power supply) on one breadboard?

# Answer
> 2 votes
You need a voltage regulator for the esp. Preferably a dc-dc step down, which will neither waste power nor heat up. Other, passive solutions are possible but not desirable. The regulator can be found on ebay amazon etc.

EDIT:

One more thing about the LEDs: depending on the model you have, they might or might not work with 3.3V input (I'm assuming you want to drive the LEDs from the esp).

In case they take only 12V input, you will need some interface solution, like this one, for example.

---
Tags: voltage-level, current
---