# Question
Title: Wrong microcontroller found on Arduino Leonardo
When I try to upload a sketch on this brand new Arduino Leonardo, I get this error:

```
Arduino: 1.6.11 (Linux), Board: "Arduino Leonardo"

Sketch uses 4,134 bytes (14%) of program storage space. Maximum is 28,672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.

avrdude: Expected signature for ATmega32U4 is 1E 95 87
     Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

```

The output of "Get board info" is

```
BN: Arduino Leonardo
VID: 2A03
PID: 0036
SN: (null)

```

This is the actual board

And if I shine a very bright light on che microcontroller, take out my glasses and look veeeeeeery close at it, I can read MEGA32U4. So I think that this is an actual Arduino Leonardo.

I downloaded arduino.org IDE. After compiling ncurses5 (...) and making it starts, now i get this error

```
Arduino: 1.7.10 (Linux), Board: "Arduino Leonardo"

/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp -o /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/wiring.c -o /tmp/build6488251228617422525.tmp/wiring.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/wiring_digital.c -o /tmp/build6488251228617422525.tmp/wiring_digital.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/wiring_analog.c -o /tmp/build6488251228617422525.tmp/wiring_analog.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/wiring_shift.c -o /tmp/build6488251228617422525.tmp/wiring_shift.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/hooks.c -o /tmp/build6488251228617422525.tmp/hooks.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/WInterrupts.c -o /tmp/build6488251228617422525.tmp/WInterrupts.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/wiring_pulse.c -o /tmp/build6488251228617422525.tmp/wiring_pulse.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HardwareSerial1.cpp -o /tmp/build6488251228617422525.tmp/HardwareSerial1.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HardwareSerial0.cpp -o /tmp/build6488251228617422525.tmp/HardwareSerial0.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/USBCore.cpp -o /tmp/build6488251228617422525.tmp/USBCore.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HardwareSerial2.cpp -o /tmp/build6488251228617422525.tmp/HardwareSerial2.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/main.cpp -o /tmp/build6488251228617422525.tmp/main.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/abi.cpp -o /tmp/build6488251228617422525.tmp/abi.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp -o /tmp/build6488251228617422525.tmp/HardwareSerial.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HardwareSerial3.cpp -o /tmp/build6488251228617422525.tmp/HardwareSerial3.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/WString.cpp -o /tmp/build6488251228617422525.tmp/WString.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/Stream.cpp -o /tmp/build6488251228617422525.tmp/Stream.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/Print.cpp -o /tmp/build6488251228617422525.tmp/Print.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/CDC.cpp -o /tmp/build6488251228617422525.tmp/CDC.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/Tone.cpp -o /tmp/build6488251228617422525.tmp/Tone.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/HID.cpp -o /tmp/build6488251228617422525.tmp/HID.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/WMath.cpp -o /tmp/build6488251228617422525.tmp/WMath.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/IPAddress.cpp -o /tmp/build6488251228617422525.tmp/IPAddress.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2a03 -DUSB_PID=0x8036 -DUSB_MANUFACTURER="Unknown" -DUSB_PRODUCT="Arduino Leonardo" -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino -I/home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/variants/leonardo /home/phas/Downloads/arduino-1.7.10-linux64/hardware/arduino/avr/cores/arduino/new.cpp -o /tmp/build6488251228617422525.tmp/new.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/wiring.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/wiring_digital.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/wiring_analog.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/wiring_shift.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/hooks.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/WInterrupts.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/wiring_pulse.c.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HardwareSerial1.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HardwareSerial0.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/USBCore.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HardwareSerial2.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/main.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/abi.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HardwareSerial.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HardwareSerial3.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/WString.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/Stream.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/Print.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/CDC.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/Tone.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/HID.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/WMath.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/IPAddress.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-ar rcs /tmp/build6488251228617422525.tmp/core.a /tmp/build6488251228617422525.tmp/new.cpp.o
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-gcc -w -Os -Wl,--gc-sections -mmcu=atmega32u4 -o /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.elf /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.o /tmp/build6488251228617422525.tmp/core.a -L/tmp/build6488251228617422525.tmp -lm
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.elf /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.eep
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.elf /tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.hex

Sketch uses 4,252 bytes (14%) of program storage space. Maximum is 28,672 bytes.
Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, /dev/ttyS0, } / {/dev/ttyACM0, /dev/ttyS0, } => {}
PORTS {/dev/ttyACM0, /dev/ttyS0, } / {/dev/ttyACM0, /dev/ttyS0, } => {}
Uploading using selected port: /dev/ttyACM0
/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/bin/avrdude -C/home/phas/Downloads/arduino-1.7.10-linux64/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/build6488251228617422525.tmp/sketch_sep16a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Jan 15 2015 at 13:12:29
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

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

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         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  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 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 : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
Since no one has elaborated a better answer: if something like this happens, try to install arduino.org IDE on windows, connect the leonardo and flash a firmware. It should then start to work on any OS.
> 0 votes

---
Tags: arduino-leonardo
---


title: Working on a simple door lock

text:
# Question
Title: Working on a simple door lock
this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool! I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not feasible... To be clear, what I want to do is a simple door lock like this  (or even simpler) being moved from an Arduino program. How can I do that?

# Answer
You want a solenoid.

Looks like people sell ones which are specifically made for door locks.
> 1 votes

---
Tags: arduino-uno
---


title: Generating a short pulse after a delay

text:
# Question
Title: Generating a short pulse after a delay
I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.

Currently my code looks like this:

```
uint16_t pulse_delay = 12000; //half-microseconds
uint16_t pulse_length = 20;

void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void loop(){}
ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match

  OCR1A = pulse_delay + pulse_length;
}

```

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.

However, if I replace the last line (`OCR1A = pulse_delay + pulse_length;`) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.

```
  delayMicroseconds(pulse_length);
  TCCR1C = _BV(FOC1A); //manually trigger match event

```

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.

Why does the first version not work, and how can I make it work??

# Answer
Expanding on my comment, after checking experimentally that this was indeed the issue.

## Short answer

You should do

```
TIFR1 = _BV(OCF1A);  // clear interrutp flag

```

right before

```
TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

```

## Explanation

Whenever the timer reaches the value stored in one of its “compare match” registers, this triggers a “compare match” event, which has the effect of raising the corresponding interrupt flag (`OCF1A` in your case). If the associated interrupt is enabled, that fires an interrupt request, and the flag is automatically cleared when the CPU starts executing the interrupt vector.

However, if the interrupt is *not* enabled, the flag just stays set. If you later enable the interrupt when the flag is already set, the interrupt request is sent immediately. This is not what you want, you want the interrupt to fire only on the *next* match. For this to happen, you have to clear the interrupt flag prior to enabling the interrupt.

The interrupt flags have a very non-intuitive behavior: you *clear* the flag by writing a logic *one* to it. Thus the line:

```
TIFR1 = _BV(OCF1A);  // clear interrutp flag

```

For completeness, I would also clear `ICF1` before enabling `ICIE1`, although this seems to not be critical for the working of your program.

Also, as a side note, be aware that the timer can increment while the CPU is in the middle of executing `TCNT1 = TCNT1 - ICR1;`. If you want the cleanest possible timings, leave the timer free-running and just set `OCR1A` to the appropriate values: `ICR1+pulse_delay`, then `ICR1+(pulse_delay+pulse_length)`.
> 1 votes

---
Tags: timers
---


# Question
Title: A question on physical locations of the registers in ATmega328P
When I read about registers I always encounter the following illustration:

So there are 32 registers in the above diagram. They are processor registers.

But in the data-sheet of ATmega328P at page 428 there is a section called "Register Summary".

Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?

Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

# Answer
You are confusing CPU registers and SFRs, Special Function Registers.

CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.

CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.

As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.
> 2 votes

---
Tags: atmega328, avr
---


title: What controller should i use?

text:
# Question
Title: What controller should i use?
I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.

So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.

The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.

I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..

Peace out,

Lars

PS: other brands besides Arduino work for me to

# Answer
How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.

I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In

https://www.pjrc.com/store/teensylc.html

https://www.pjrc.com/teensy/index.html

The 3.1 and 3.6 are more powerful and more expensive at around $29

note: Read the index for which boards are 5v tolerant if that's what you need.
> 2 votes

---
Tags: bluetooth, shields, hardware
---


title: Do (cheap) SD modules support file I/O?

text:
# Question
Title: Do (cheap) SD modules support file I/O?
I noticed there are cheap SD modules and complete SD shields. I assume the last are used for a 'final' product and not for bread-boarding (?)

However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition to SPI interface)?

E.g. can I use the file I/O and the SD library with the This SD module?

# Answer
There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano. The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.

The ability to do file operations is separate to the protocol you use to talk to the module (SPI). Lots of device (not just SD cards) use SPI, but not all of them do file operations. An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.

What actions the SD module/shield is capable of is really up to the library/software. The module will have to comply to some set of standards and this will let the caller perform certain operations. Lets say one of the operations is to read one byte from an address. This operation would need to be used by the library to read a file, also it would need to use it to find where the file is. It would also need it when writing a file, because it would need to know what free space was left on the card. You are shielded from all this by the Library you probably have a read file, write file and delete file function. (This is an example of abstraction which you will see a lot in programming).

The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one. These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.

So to answer your question

1. If you use a module and shield that use the same IC (chip) to access the SD card and the same library then they will almost always behave the same.
2. If you use two different shield (different ICs) which need different libraries then they MIGHT have different functionality.
3. If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)

If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it. Otherwise, chances are you will be fine.

==== Edit ===

When you think of hardware/software abstraction think of it as a Television. You deal with the TV at the very highest level, you turn it on/off and change channels.

When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.

Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.

There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and.... Well it just gets silly, you just want to watch your soap.

So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call `WriteFile()`. Does it really matter how it does it? Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really? Does it matter that `WriteFile()` is actually storing it on the hard disk of a PC somewhere in the world?

Your call to `WriteFile()` is abstracted away from the underlying process hiding it, because it doesn't really matter. Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling `read()` and `write()` but it isn't.
> 2 votes

# Answer
Short answer. Yes, it will work.

I have used the same MicroSD Card Adapter module \[it is marked MOSO instead of MISO on one of the pins\] for a few projects. I found no problems or special considerations doing so \[except for getting the pin mapping correct\].

In contrast, I've used one shield that worked sporadically, because of intermittent header contact. It would work for a while, then stop until I "massaged" it properly. It was probably just a bad assembly, though.

Many people prefer working with shields, while I do not, and would rather build on PCB board once I have a working version of my project. It's cheaper as well.
> 2 votes

---
Tags: shields, sd-card
---


# Question
Title: Connecting two arduinos with wifi over the Internet
I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.

Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.

One board with only send data, and one will only receive.

Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.

thx in advance :)

# Answer
> 1 votes
The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.

If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

> So can I send and receive real time data over the internet, and receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?

Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).

tl;dr: The network will be a much greater limitation than the ESP devices.

Update:

> the problem i see is the delay with communication over the internet between the two uno if i use a server.can i communicate between the two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.

# Answer
> 0 votes
Have you considered using Particle Photons instead? They're $19, wifi enabled, Arduino compatible and they come with a very extensive cloud API functions that will allow you to pass information between them really easily: https://docs.particle.io/reference/firmware/photon/

---
Tags: wifi
---


title: Multiple push buttons

text:
# Question
Title: Multiple push buttons
I am behind a problem of controling multiple leds with multiple push buttons. Lets say that I have 5 push buttons and 3 leds. Led1 turns on if at least 1 out of the 5 push buttons is pressed. Led2 turns on if at lest 3 push buttons are pressed and Led3 turns on if at least 4 push buttons are pressed. How can this be solved ? With if else ?arrays? here is my code that i have

```
 const int led1 = 2;
 const int led2 = 3;
 const int led3 = 4;
 const int bp1 = 9;
 const int bp2 = 8;
 const int bp3 = 7;
 const int bp4 = 6;
 const int bp5 = 5;
 int state;

void setup()
 {
 Serial.begin(9600);
 pinMode(led1, OUTPUT);
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(bp1, INPUT);
 pinMode(bp2, INPUT);
 pinMode(bp3, INPUT);
 pinMode(bp4, INPUT);
 pinMode(bp5, INPUT);
}

void loop()
{
 state = digitalRead(bp1);
 state = digitalRead(bp2);
 state = digitalRead(bp3);
 state = digitalRead(bp4);
 state = digitalRead(bp5);
if (state = HIGH)
{ digitalWrite(led1, HIGH); }

if (state = 3 )
{ digitalWrite(led2, HIGH);
if (state >= 4);
{ digitalWrite(led3, HIGH); }
}
else { digitalWrite(led1, LOW); }
}

```

# Answer
Your code won't work as is. Each time you assign a value to `state` you're overwriting it in the next line. You could, for example have multiple int state variables such as `state1` for the first line in the loop then `state2` in the second etc. Then you need to compare values (don't use `=` on its own in a compare as it will assign the value being tested - use `==` instead). This way you gather all the button states first.

Or you could test the state of a button and if pressed add 1 to `state`:

```
if (digitalRead(bp1)) {
    state++};

```

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.

However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.

R3.
> 1 votes

# Answer
To get the functionality you want the code should be:

```
void loop()
{
 state = 0;
 if (digitalRead(bp1) == HIGH)
   state = state + 1;
 if (digitalRead(bp2) == HIGH)
   state = state + 1;
 if (digitalRead(bp3) == HIGH)
   state = state + 1;
 if (digitalRead(bp4) == HIGH)
   state = state + 1;
 if (digitalRead(bp5) == HIGH)
   state = state + 1;

 if (state >= 1)
   digitalWrite(led1, HIGH);
 else
   digitalWrite(led1, LOW);

 if (state >= 3 )
   digitalWrite(led2, HIGH);
 else
   digitalWrite(led2, LOW);

 if (state >= 4) // you had a ; here.
   digitalWrite(led3, HIGH);
 else
   digitalWrite(led3, LOW);
}

```

There are more shorthand ways to write this e.g.`if (digitalRead(bp4) == HIGH) state = state + 1;` could be replaced with `digitalRead(bp4)?state++;` but until you are familiar with programming it's often best to use the longer but clearer way of writing things.

If all you are doing is lighting LEDs then de-bouncing the buttons isn't necessary, any LED flicker caused by the contacts bouncing won't be visible to your eye.

If however at a later date you want to trigger other logic in your program to run once per button press then you will need to worry about that. All buttons and switches bounce a little when you close them, without something in the electronics or software to cope with that a single button press can look like a dozen very quick presses to your software.
> 1 votes

# Answer
I would do this:

```
 state = (state & ~STATE_MASK1) | ((digitalRead(bp1)==HIGH)?STATE_MASK1:0); //assuming buttons are active high
...

if (state & STATE_MASK1)
{ digitalWrite(led1, HIGH); }

```

it holds up to 8 button states for a uint8\_t type.

edit: here is a quick implementation.

```
//state = 0;                                            //reset the state

//read the buttons - all active high
state = (digitalRead(bp1)==HIGH)?STATE_BP1:0;
state|= (digitalRead(bp2)==HIGH)?STATE_BP2:0;
state|= (digitalRead(bp3)==HIGH)?STATE_BP3:0;
state|= (digitalRead(bp4)==HIGH)?STATE_BP4:0;
state|= (digitalRead(bp5)==HIGH)?STATE_BP5:0;

//process the buttons
digitalWrite(led1, (state & STATE_BP1)?HIGH:LOW);   //active high - led1 is high if bp1 is high
digitalWrite(led2, (state & (STATE_BP2 | STATE_BP4))?LOW:HIGH); //active low - led2 mimics bp2|bp4 => led2 high if both bp2+bp4 are low
digitalWrite(led3, ((state & STATE_BP3) && (~state & STATE_BP5))?HIGH:LOW); //active high -> led3 is high if bp3 is high and bp5 low

```

the code controls 3 leds:

1. led1: it mimics bp1;
2. led2: it goes high if both bp2/bp4 are high;
3. led3: it goes high if bp3 is high and bp5 is low.

I picked the output logic for no particular reason.

here is the output:

you can check the waveform against the logic, :)

again, this is just one particular implementation and you can write your own code / logic to produce your desired outcome. the principle is the same.
> 0 votes

# Answer
I solved my problem by myself with if..else structures. I am happy that I got this working and I learned something new. Thank you all for help and inputs.

```
int led1 = 2;
int led2 = 3;
int led3 = 4;
int bp1 = 9;
int bp2 = 8;
int bp3 = 7;
int bp4 = 6;
int bp5 = 5;

void setup()
 {
 Serial.begin(9600);
 pinMode(led1, OUTPUT);
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(bp1, INPUT);
 pinMode(bp2, INPUT);
 pinMode(bp3, INPUT);
 pinMode(bp4, INPUT);
 pinMode(bp5, INPUT);

}

void loop()

{

if (digitalRead(bp1)== HIGH or digitalRead(bp2)== HIGH or digitalRead(bp3)== HIGH or digitalRead(bp4)== HIGH or digitalRead(bp5)== HIGH )
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);
 }
else
{
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  digitalWrite(led3, HIGH);

 }

if (digitalRead(bp1)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH)
    {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led3, HIGH);
    }
else
  {
   digitalWrite(led1, HIGH);
   digitalWrite(led2, HIGH);
   digitalWrite(led3, HIGH);
   }

if (digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH)
   {digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, LOW);
}

else
 {  digitalWrite(led1, HIGH);
   digitalWrite(led2, HIGH);
   digitalWrite(led3, HIGH);
   }

}

```
> 0 votes

---
Tags: programming
---


title: Does SoftwareSerial use hardware timer?

text:
# Question
Title: Does SoftwareSerial use hardware timer?
I'm asking this because I'm using a timer to generate a 38KHZ signal to drive an IR diode, and I also need to use SoftwareSerial to talk to an HC-12 radio using serial communication.

The code I'm using was written by Nick Gammon and is here:

```
//Setup Conter/overflow to create 38KHZ drive for IR38KHZ
//38khz, no interrupts
#define IR_CLOCK_RATE 38000L
// toggle on compare, clk/1
TCCR2A = _BV(WGM21) | _BV(COM2A0);
TCCR2B = _BV(CS20);
// 38kHz carrier/timer
OCR2A = (F_CPU/(IR_CLOCK_RATE*2L)-1);
pinMode(IR38KHZ, OUTPUT);

```

I'm not quite up-to-date on the timer use on an Arduino (I'm using a Nano), plus I've no idea what the SoftwareSerial library uses.

# Answer
> 3 votes
No. It uses pin-change interrupts to trigger reception, and both reception and transmission use calibrated delay loops. However, interrupts are disabled during both transmission and reception so that the calibrated delay loops remain always the precise length - so if you do anything with any other interrupts they will not work at the same time as SoftwareSerial.

---
Tags: arduino-nano
---


title: Arduino and USB power, what to choose

text:
# Question
Title: Arduino and USB power, what to choose
I am a beginner at Arduino. I want to power the Arduino through the USB cable that is usually plugged in the USB of the laptop, but plugged in the wall instead of the laptop.

Here are my questions:

* Can I use a phone charger that has a USB (in which the end of the USB cable will go instead of the USB of the PC)?
* What should I look for written on the charger so it is best compatible?
* Is it ok to be done that way?
* Will it be the same as means of power like when it is plugged in the PC (for example when later on I connect LCD display, diodes, etc.)?

I did my research, but it got confusing, so I wanted to ask my own question. Thanks in advance.

# Answer
> 4 votes
Yes, you can power the Arduino using a USB phone charger.

The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.

A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).

In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from \<100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.

For the most part, a USB charger will be sufficient.

# Answer
> 2 votes
As you are still a beginner so I would not go into complex details. Your Arduino can run perfectly on a laptop powered USB but try to avoid connecting the power hungry electronics with your Arduino while powering it from the laptop USB port.

A Laptop USB port can give nearly 700mA that is enough for Arduino to run a couple of sensors easily.

Secondly, most wall chargers give 1A(1000mA) current that is better in my opinion. It can handle some power hungry electronics better then connecting your Arduino with the Laptop USB port.

I personally power my Arduino with either a Wall Charger or a power bank. Hope it helped solve your problem.

The more you dig into Arduino, the more fun it becomes. So have fun and be Creative.

---
Tags: power
---


# Question
Title: Is it possible to program an ESP8266 12F using an Arduino Nano?
I just got my ESP8266, but I am unable to program it. Since it can't be connected to via USB, I was wondering if I can program it using an Arduino or perhaps use it as a shield for an Arduino Nano. I haven't been able to find a good guide online. Any help is greatly appreciated.

# Answer
Yes, you can program it with Arduino but its a bit complex that way. You will need a separate Linear Regulator with Adjustable Output to get it hooked up with the Arduino. Its way better to have an FTDI adapter to program it.

But if you still want to know, there is a tutorial below,

Upload Bareminimum sketch so that no program is running on the Arduino.
> 1 votes

# Answer
> Is it possible to program an ESP8266 12F using an Arduino Nano?

Yes, but it is much easier to use a FTDI for USB-to-Serial adaptation. Two buttons are also needed to activate the ESP8266 programming mode.

Cheers!
> 0 votes

---
Tags: esp8266, arduino-nano
---


# Question
Title: Arduino Serial and myserial clarification. How to print out rx output?
I currently have a camera I am trying to run off an Arduino. I am new to Arduino and I have had trouble figuring out what serial and myserial really do. I also don't understand why, when I have something like `serial.write(0x56)` I will get the output in the serial monitor to be V in hex, but If I have the Arduino also connected to an oscilloscope, I won't be able to see the signal.

Yet if I have `myserial.write(0x56)`, I won't see anything in the serial monitor, but will see the bits on my oscilloscope.

Also, if I send a command to my camera, my camera should send back some hex values if the write command is sent. I understand I can send commands via `myserial.write(0x56)`, but how would I read the hex values the camera would send back?

# Answer
> 1 votes
It seems like you are using both the hardware UART pins and two other pins for SoftwareSerial i.e. UART emulated by the arduino.

When you write `Serial.read()` or `Serial.write()`, Arduino knows to use the UART hardware on the chip which is has RX/TX pins 0 and 1 for most Arduinos. So by using these functions you will be able to communicate with any device which is connected on these pins.

Generally, when you have the Arduino connected to your computer, these RX/TX pins internally go to a serial port on your computer via the USB, hence you can send/receive data to the computer and view it on the Serial Monitor. Great for debugging purposes!

Sometimes, like in your case for controlling the camera, you need to have another serial port for communication because UART is point to point i.e. only 2 devices can communicate via it. `SoftwareSerial` helps you do that by using two other pins on the Arduino into RX/TX pins. If you look at the top of your code file you will see a line like this

```
SoftwareSerial mySerial = SoftwareSerial(...);

```

Inside the brackets you will also see the two pin numbers which are being used as RX/TX. In the software serial example pins 10,11 are being used. So whatever is connected to these pins (i think your camera module is) will be able to send/receive data using `mySerial.write()` and `mySerial.read()`.

Hence, to be able to receive data from the camera you will use `mySerial.read()`.

---
Tags: serial
---


# Question
Title: sleep and wake up arduino mega according to ds3231 interrupt
how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.

here is my code

```
#include <DS3231.h>
#include <Wire.h>
#include <avr/sleep.h>

 int wakePin = 2;   // pin used for waking up
 int led = 13;

 DS3231 clock;
 RTCDAteTime dt;

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

 // initialize DS3231
 Serial.println("Initailize DS3231");
 delay(100);
  clock.begin();
  pinMode(wakePin,INPUT_PULLUP);
  pinMode(led,OUTPUT);

   //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
   //Under normal conditions, the settings should be reset after power and restart microcontroller
   clock.armAlarm(false);
   clock.clearAlarm();

   //Set Alarm1 - Every 20s in each minute
   // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
     clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
     attachInterrupt(0,wakeUpNow,LOW);

   //check alarm settings
    checkAlarms();
  }

   void checkAlarms()
  {
   RTCAlarmTimea1;
   RTCAlarmTimea2;

    if (clock.isArmed1())
   {
    a1 = clock.getAlarm1();

     Serial.print("Alarm1 is triggered:);
     switch(clock.getAlarmType1())
    {

       case DS3231_MATCH_S:
       Serial.print("When seconds match: ');
       Serial.println(clock.dateFormat("_ _:_:s",a1));
       delay(100);
        break;
        default:
         Serial.println("UNKNOWN RULE");
         break;
     }
    }
   }

       void wakeUpNow()
   {
       //execute code here after wake-up before returning to the loop() function
      //timers and code using timers(serial.print and more...)will not work here.
     //we don`t really need to execute any special functions here, since we
     //just want the thing to wake up
      Serial.print("Woke up");
     delay(100);
     }

      void sleepNow()
     {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
      sleep_enable();   //enables  the sleep bit in the mcucr register
      attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
      sleep_mode();
         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

         sleep_disable();  //first thing after waking from sleep: disable sleep
         detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
          time.
        }

         void loop()
        {
           dt=clock.getDateTime();

             Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
              delay(100);
           //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
              if(clock.isAlarm1())
           {
                 Serial.println("ALARM 1 TRIGGERED!");
                 digitalWrite(led,HIGH);
                   delay(1000);
                  digitalWrite(led,LOW);
                  Serial.println("Entering Sleep");
                    delay(100); //sleep fucntion called here
                     sleepNow();
               }
                delay(900);
               }

```

# Answer
> 0 votes
First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.

---
Tags: arduino-mega, sensors, pwm, timers, rtc
---


# Question
Title: Arduino Serial Port. COM1 does not exist
Hello everyone I'am new to this site so please bear with me.

I have an **`Arduino Uno`** that I'm using in my simple project using `VS 2008`. I got this error says `The Port COM1 does not exist`. The flow of my project is after inserting a `coin` into the `coin slot` the arduino will pass the data into my project and it will display into a Label or Textbox the value of the inserted coin.

# Answer
Probably it is on another COM port. When I checked my IDE (from Arduino) the Arduino was found at COM3.

You probably have to iterate through the (PC) COM ports to find out where the Arduino is connected to.
> 1 votes

# Answer
Never used Visual Basic but:

* There is no such thing as Serial1 on Arduino Uno. There is only Serial. (Serial1, 2, 3 are available on ArduinoMega) Reference: Arduino
* For COM port you should check your device manager. Often it appears at COM3 so probably you should check this issue.

Just for curiosity: Why VB? Is it only your choice or it use less ram or memory, works faster or anything?
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: What programmer do I select in Arduino IDE for the ATMEL-ICE ISP?
I have been using an AVRISPmkII for many years but recently gave mine away to another hobbiest. I wnated to buy a replacement and have had to buy an ATMEL-ICE ISP as the AVRISPmkII is now unavailable.

Occasionally, I like to program the Arduino Uno from the Arduino IDE using the ISP.

However when I go to select the programmer (from the tools menu), I don't see the ATMEL-ICE in the list.

How do I get Arduino IDE to recognize the ATMEL-ICE ISP?

Note: I am using Arduino IDE v1.6.8.

# Answer
> 3 votes
**As of V1.8.2, the ATMEL-ICE is now included as a programmer in the Arduino IDE.**

The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

---

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was released as a version on the 22nd of March 2017.

---
Tags: arduino-uno, arduino-ide, isp, programmer
---


# Question
Title: Initializing pointer to vector of objects inside another object
i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):

**INO file**

```
#include "LedDevice.h"

LedDevice device;

void setup() {
  device = LedDevice(10, 10, 10);
}

void loop() {
  Serial.println(F("Ticking"));
  device.Tick();
  delay(500);
}

```

**LedDevice**

```
#if !defined(_LEDDEVICE_H)
#define _LEDDEVICE_H

#include "Preset.h"
#include<Arduino.h>

class LedDevice {
public:
  Preset* Presets[];

  LedDevice(){}
  LedDevice(int numPixels, int numPresets, int numPatterns)
  {
    *Presets = (Preset*)malloc(sizeof(Preset) * numPresets);

    for (int p = 0; p < numPresets; p++)
    {
      Presets[p] = new Preset("test", numPixels, numPatterns);
    }
  }

  void Tick()
  {
    Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
    Presets[0]->Tick();
  }
};

#endif  //_LEDDEVICE_H

```

**Preset**

```
#if !defined(_PRESET_H)
#define _PRESET_H

#include "Pattern.h"

class Preset {
public:
  char *Name;
  int NumPatterns;
  Pattern* Patterns[];

  Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
  {
    Name = (char *)malloc(strlen(name) + 1);
    strcpy(Name, name);

    *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p] = new Pattern(numPixels);
    }
  }

  void Tick()
  {
    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p]->Tick();
    }
  }
};

#endif

```

**Pattern**

```
#if !defined(_PATTERN_H)
#define _PATTERN_H

class Pattern {
public:

  Pattern(int numPixels){}

  void Tick(){}
};

#endif

```

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.

Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.

Can you tell if anything is not being done correctly in the constructors?

# Answer
> 1 votes
Three things that need to be different:

```
Pattern* Patterns[];

```

should be

```
Pattern** Patterns;

```

It's a pointer to some pointers to patterns, not a pointer to an array (which is basically a pointer itself so same basic idea but an array implies a known size).

and

```
*Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

```

should be

```
Patterns = (Pattern*)malloc(sizeof(Pattern*) * NumPatterns);

```

\*Patterns is the thing pointed to by Patterns which at this point is undefined. You want to set Patterns to the allocated address. And we only need to allocate space for the pointers not the actual objects.

Your for loops then become

```
for (int p = 0; p < NumPatterns; p++)
{
  (Patterns+p) = new Pattern(numPixels);
}

```

You then have the same issues with Presets.

And finally

```
LedDevice device;
void setup() {
  device = LedDevice(10, 10, 10);
}

```

should be

```
LedDevice device(10, 10, 10);
void setup() {
}

```

# Answer
> 1 votes
This is wrong:

> ```
> Device device;
>
> void setup()
> {
>    device = Device();
> }
>
> ```

I don't know what your intentions are, but the first line instantiates `device`. You don't need to do anything in `setup` here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

---

> ```
> Preset* Presets[];
>
> ```

What's this? A pointer to an array of zero length?

---

> ```
>     *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);
>
> ```

Now you are allocating memory for a **pointer** to the array to be big enough to hold the **contents** of the array.

---

> ```
> for (int p = 0; p < NumPresets; p++)
> {
>     Presets[p] = new Preset("test", NumPixels, NumPatterns);
> }
>
> ```

Now you are allocating memory for the contents of the array again.

---

There is too much dereferencing going on here. Please post a Minimal, Complete, and Verifiable example. For example, make the classes in question do not much. Then make code we can actually work on.

---

> I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a `begin` function which you call in `setup`. This function can then do whatever is required at the proper time.

---
Tags: array, pointer
---


title: A confusion with setting timers

text:
# Question
Title: A confusion with setting timers
I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

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

int main (void)
{
    DDRB |= (1 << 0); // Set LED as output
    TCCR1B &= ~(1 << CS11); // Set up timer
    TCCR1B &= ~(1 << CS12); // Set up timer
    TCCR1B |= (1 << CS10); // Set up timer

    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}

```

I use the following formula:

> Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock Frequency) - 1

So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:

What am I doing wrong?

# Answer
If you want to output a signal at the same speed as the system clock, I would not recommend using a timer. You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top. You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.
> 4 votes

---
Tags: timers, avr
---


# Question
Title: The program keeps skipping over the running 1 and 2 states even though the prereqs are met
The serial prints are for troubleshooting. All outputs are LEDs for testing purposes. The running 1 and 2 states are sometimes skipped over, but not always. I think this is from the light sensor being bad and jumping up and down, but using a higher value does nothing. I also tested the light sensor in the example program and got 1s and 2s so that really shouldn't be the problem. When it does work and the second light sensor is covered (the one that measures sugar level) it continuously cycles through and never returns to ready state. If more detail is needed please let me know

```
//Digital Inputs
int measureSwitch = 13; //switch that sets 2 tsp and 1 tsp

//Digital Outputs
int motor = 12;
int buzzer = 11;
int readyLed = 10;
int running1Led = 9;
int running2Led = 8;
int doneLed = 7;
int sugarLevelLed = 6;

//Analog Inputs
int cupSensor = 20; //the light sensor should read 0 when the cup is resting on it
int lightSensor = 100; // the sugar should cover up thelight sensor so the light can pass thru, making it zero

//different run times

int running1Time = 100; //1 tsp tentative times
int running2Time = 250; //2 tsp tentative times
int buzzerTimer = 200; // how long the buzzer will go off for

void setup() {
  Serial.begin(9600);
  pinMode(measureSwitch, INPUT);
  pinMode(motor, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(readyLed, OUTPUT);
  pinMode(running1Led, OUTPUT);
  pinMode(running2Led, OUTPUT);
  pinMode(doneLed, OUTPUT);
  pinMode(sugarLevelLed, OUTPUT);
}

//Ready State

void readyState(){
  digitalWrite(readyLed, HIGH);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Running 1 State

void running1State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, HIGH);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Running 2 State
void running2State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, HIGH);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Done State
void doneState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, HIGH);
  digitalWrite(motor, LOW);
}

//Waiting State
void waitingState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Sugar Level State
void sugarLevelState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, HIGH);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

void loop() {
  while(analogRead(A0) > lightSensor){ //when there is no cup placed on the
sensor, be in ready state
    readyState();
    Serial.println("READY STATE");
  }

//when the cup is on the sensor and the switch is set to 1 tsp
    for(int time1 = 0; ((time1 < running1Time) &&
                        (analogRead(A0) < cupSensor) &&
                        (digitalRead(measureSwitch) == HIGH)) ; time1++){
    //run the running 1 state for 4 seconds
      running1State();
      delay(1);

      Serial.println("RUNNING STATE 1");
      Serial.println(time1);

  }

    //when the cup is on the sensor and the switch is set to 2 tsp

    for(int time2 = 0; ((time2 < running2Time) && (analogRead(A0) < cupSensor)

&& (digitalRead(measureSwitch) == LOW)); time2++){

//run the running 2 state for 8 seconds

      running2State();
      delay(1);
      Serial.println("RUNNING STATE 2");
      Serial.println(time2);
      Serial.println(analogRead(A0));

  }

  for(int buzzerTime = 0; buzzerTime < buzzerTimer; buzzerTime++){

    doneState();
    Serial.println("DONE STATE");
    Serial.println(buzzerTime);
    delay(1);
  }

  while(analogRead(A0) < cupSensor){
    waitingState();
    Serial.println("WAITING STATE");
  }

  while(analogRead(A1) > lightSensor){
    sugarLevelState();
    Serial.println("SUGAR LEVEL STATE");
  }
}

```

# Answer
Try pulling the output of the light sensor to ground via a 10k resistor, that should calm the values.

Note that you are going to need to completely change the value of the variable `lightSensor`. This is because it will now be outputting different values due to the extra resistor to ground.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: arduino-uno, sensors, c++
---


# Question
Title: Converting `millis()` to decimal seconds?
I would like to get my Arduino to print milliseconds as decimals of seconds. For example, instead of printing 10456, printing 10.456

I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal

The code I use is:

```
float ourtime = (millis() / 1000);
dataFile.print (ourtime);

```

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

# Answer
> 2 votes
Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.

Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:

```
Serial.println(millis() / 1000.0, 3);

```

The `3` as the second parameter tells `Serial.println()` how many decimal places to print. The `.0` at the end of `1000.0` forces the compiler to see `1000` as a float value (you can also use `1000f` if you prefer).

Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):

```
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now % 1000;

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

```

You could replace the `%` with a x1000 and a subtraction too if you like:

```
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now - (secs * 1000);

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

```

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:

```
char num[10];
snprintf(num, 10, "%lu", millis());
uint8_t nlen = strlen(num);

for (uint8_t i = 0; i < nlen - 3; i++) {
    Serial.write(num[i]);
}
Serial.write('.');
for (uint8_t i = nlen-3; i < nlen; i++) {
    Serial.write(num[i]);
}
Serial.println();

```

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.

# Answer
> 0 votes
Division is quite expensive.

Division can be done with subtraction, or shifting - right shift 10 (= /1024) and then compensate for that 24....

You may need too benchmark to see if on your chip this will yield any gaiin.

edit:

I did some quick benchmarking against the brutal force approach by Majenko (division followed by the mod operation), for full range 16-bit types, dividing by 1000, on a PIC16, XC8 free mode:

for 16-bit types 1. Majenko's approach (1000 divisor + mod): 45.9M ticks; 2. revised Majenko's approach (1000 divisor, no mod): 36.9M ticks; 3. My approach (1024 divisor, no mod): 20.8M ticks.

\[edit 2\]for 32-bit types 1. Majenko's approach (1000 divisor + mod): 101.6M ticks; 2. revised Majenko's approach (1000 divisor, no mod): 63.0M ticks; 3. My approach (1024 divisor, no mod): 19.3M ticks.

the same trend applies under the pro mode.

the same trend applies for AVR, with the speed gain being bigger.

edit 2: 32-bit benchmarking added.

I also revised my approach for 32-bit types to speed up the execution a little.

lessons learned:

1) mod ops shall be avoided as much as you can;

2) divisions shall be avoided as much as you can.

3) algorithm rules!

however, be cautious to extrapolate the data here. on a chip with hardware multiplier + divider (STM8, my favorite chip), this trend may not apply and you should benchmark on the target chip to be safe.

---
Tags: millis, mathematics
---


# Question
Title: Ethernet Shield - Multiple simultaneous connections cause TCP reset
I have a very inconvenient problem with a web server I'm writing for a Arduino Mega 2560 with a W5100 Ethernet Shield (with the "official" Ethernet lib). I wrote the server code and it works like a charm, BUT there is a condition, when the server won't accept all the TCP handshakes and resets the TCP connections: When I load a big webpage, the browser (Firefox and Chrome too) asks for the .htm first, then collects the links in the file and request them all simultaneously and that's when I got the problem:

The server gets multiple TCP connections but it only accepts the first, then dumps all the others (by TCP reset). After that the client sends them again and the problem starts again: the server accepts the first and drops the others. And so on, for example if the browser needs 3 files, it will take ~9 seconds, because of the retransmission delay. (3 + 6 seconds) Eventually the webpage will load, but a 10 second delay is not acceptable. Is there any way to cache the requests on the Ethernet Shield or to tell the browser to wait a bit between requests or any other way, to wait a bit for the Arduino to finish the previous request?

Snippet for the server, Wireshark and Chrome network data: https://gist.github.com/anonymous/181f359b70d69e4470931204c4ec175c

Thanks for the help!

G.

# Answer
*I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.*

---

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page Arduino Ethernet Shield 2 we learn:

> It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.

Please post a Minimal, Complete, and Verifiable example.

I did a post about a tiny web server for the Arduino which uses a state machine to handle incoming data without blocking.

---

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.

```
Connection: keep-alive

```

That might stop the client opening new connections in quick succession.
> 1 votes

---
Tags: ethernet
---


title: ESP8266 and Arduino integration

text:
# Question
Title: ESP8266 and Arduino integration
I am trying to upload a sketch and getting below error:

```
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed.

```

Connections:

```
TX - TX
CH_PD - 3.3 V
RX - RX
VCC - 3.3
GPIO GND
GND - GND

```

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

# Answer
> 1 votes
You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect

```
TX - RX
RX - TX

```

---
Tags: esp8266
---


title: Arduino 5v output dead?

text:
# Question
Title: Arduino 5v output dead?
i've got a bit of a problem with my Arduino UNO.

So coming back to my (pretty basic) build after a bathroom break, I go to un-assemble my circuit (on the breadboard) and grabbing the LED causes a static shock.

Since then I haven't been able to get any power to come out of the Arduino to the breadboard circuitry.

**I have tried:**

* Different Breadboards
* All new parts, LED's/cabling/buttons/resistors.
* Different power and ground cables (from Arduino to breadboard)
* Giving the Board more time to 'cool down' (I heard there was a temperature based reset device?)
* using the 3.5v output (I'm not sure if by doing this i should remove the resistor? i'm VERY new to electronics
* using the alternate ground input

Looking around here for 'shorts' or 'damaged Arduinos' returns mostly results about non communication to the board. the difference here is *I can absolutely still upload programs to my Arduino and then run them* (I've only tried the pre-existing blink, but i don't think there is any difference). And my computer's USB ports are also fine. So if there is a duplicate question i apologize, but i haven't been able to find anything related.

Any help would be much appreciated!

# Answer
> 1 votes
If you got zapped touching an LED and the circuit doesn't work any more, and since you're sure the Arduino uploads programs OK, then either the LED (or something else on your breadboard) or the pin driver within the Arduino is probably damaged.

* Try changing the LED.
* If that doesn't work, try changing the pin(s) the sketch uses to talk to your breadboard, rewire your breadboard to use those pins, and test again. If it works this time, the pin driver was probably damaged.
* If there are any other components (e.g., not wires or resistors) on the breadboard whose failure might cause the LED not to light, replace those and test again.
* If replacing the external components doesn't fix it, and if your Arduino's MCU is a 28-pin chip in a socket, a new one with the bootloader already loaded into it typically costs $5-$6 in the US.

Update:

> ...i have listed all these things as already tried.

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that *must* be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.

You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.

---
Tags: arduino-uno
---


title: From Wiring to pure C

text:
# Question
Title: From Wiring to pure C
I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.

It was really easy to use some basic libraries such as *avr/io*, or *util/delay* and write simple programs like "arduino hello world".

My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb\_mouse.h" (from pjrc.com) with pure C?

---

**EDIT 1**

Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):

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

int main(void) {
        (CLKPR = 0x80, CLKPR = 0x00);
        DDRD |= (1<<6);
        PORTD &= ~(1<<6);

        int sviti = 0;

        while (1) {
                if (sviti)
                        PORTD |= (1<<6);
                else
                        PORTD &= ~(1<<6);
                sviti ^= 1;
                _delay_ms(40000);
        }
}

```

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.

If you want a concrete example, I want to use this library with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

# Answer
Refer to the actual processors used on the platforms to find reference material for ordinary C or C++ programming. There are different processors used on various Arduino boards. Be aware that this approach normally requires programming hardware which range from a few dollars to hundreds of dollars. Also be aware that "bare metal programming" requires the programmer to setup the processor's resources of interest. This normally involves setting dozens (as in the Arduino Uno AVR processors) if not thousands (as in Arduino Zero's ARM processors) of registers which can deal with everything from the processor's clock to interrupt vectors.

USB programming is very complex. Consider the complete description of RS232 could be contained in a white paper. The equivalent for USB would be at least a book. To simplify your efforts, we can eliminate all USB Host features as a mouse is a peripheral or USB Device. Further, you will probably want to limit your USB Device to a USB HID or Human Interface Device. This allows most OSs to easily recognize and use the mouse as the HID definition is more complete / restrictive. Also note, embedded processors which happen to have a USB port usually only support USB Devices as USB Host requires additional features & resources. Now that the scope of USB support has been narrowed, you can start searching through the different processor's libraries for what you need to create a USB HID Mouse.
> 1 votes

# Answer
> And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -\> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.

nothing magic about going in "pure c".
> 1 votes

---
Tags: arduino-ide, c, avr, teensy
---


title: Right way to convert 120VAC to 5V?

text:
# Question
Title: Right way to convert 120VAC to 5V?
I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.

Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.

I found this (Enclosed AC DC Converter) and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?

Thanks for your help in advance.

# Answer
I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.

**Short Answer, No**

If you read the datasheet for the Particle Photon, it recommends no less than a 1A power supply. Unfortunately, the datasheet for the AC/DC Converter you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.

**How to Make This Work**

Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!

Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like this one may be right for you (not to plug for Adafruit, though they are a great learning resource).

Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.

**Bonus Points**

You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.

EDIT:

**Easiest Solution** Just install one of these at the receptacle you intend to use.
> 1 votes

---
Tags: power
---


title: Contoller for a stepper motor

text:
# Question
Title: Contoller for a stepper motor
I am currently implementing the following setup:

Arduino Mega 2650 -- DRV8834 -- Stepper motor

Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by AccelStepper, the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only discrete and not accurate enough for a nice speed control.

Therefore I want to do the following

Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor

whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.

How can I create a PWM from 100 to 3000Hz with an arduino?

---

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM

```
void loop(){
digitalWrite(pinSTEP, HIGH);
delayMicroseconds(T/2);
digitalWrite(pinSTEP, LOW);
delayMicroseconds(T/2);
}

```

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

---

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:

```
prescalar = 1 ---> PWM frequency is 31000 Hz
prescalar = 2 ---> PWM frequency is 4000 Hz
prescalar = 3 ---> PWM frequency is 490 Hz (default value)
prescalar = 4 ---> PWM frequency is 120 Hz
prescalar = 5 ---> PWM frequency is 30 Hz
prescalar = 6 ---> PWM frequency is <20 Hz

```

which is not sufficient for my application.

For more about this method:

---

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:

```
#include <TimerThree.h>
// TimerThree PWM Pins 2, 3, 5

#define pinPWM       2
#define pinM0        22
#define pinM1        24
#define pinSleepnot  28
#define pinDir       30

void setup(void){

  // Define output pins
  pinMode(pinM0, OUTPUT);
  digitalWrite(pinM0, HIGH);
  pinMode(pinM1, OUTPUT);
  digitalWrite(pinM1, LOW);
  pinMode(pinSleepnot, OUTPUT);
  digitalWrite(pinSleepnot, HIGH);
  pinMode(pinDir, OUTPUT);

  // Initialize serial communication
  Serial.begin(9600);

}

void loop(void){

  for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
    float T = 1 / frequency * 1000000;
    Serial.print("Frequency: ");
    Serial.println(frequency);
    Timer3.initialize(T);
    Timer3.pwm(pinPWM, 100);
    delay(5);
  }
}

```

# Answer
> How can I create a PWM from 100 to 3000Hz with an arduino?

Your question is really "How can I create a PWM from 100 to 3000Hz with an Atmega2560"?

The Atmega has various timers which can be configured in many ways. You can alter the prescaler (ratio of processor clocks to timer ticks) and the amount it counts up to. Certainly you can change the frequency and duty cycle.

I have a page about timers which may help you.

---

> I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM ... is not feasible

Yes, don't do "bit banging" when you have 5 hardware timers.

---

> One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM.

Adapt the prescaler **and** the timer configuration. Between them you have very fine control.
> 0 votes

# Answer
You might need to move away from the AccelStepper library, and 'roll your own', but as others have pointed out, the MCU certainly has the bandwidth to do this directly. I understand that PWM resolution may not give smooth ramping, but I would probably look into using a timer interrupt. The timer ISR would count steps and you would only need to adjust the timer compare register to change the step frequency.
> 1 votes

# Answer
> the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.

Much faster if you use direct pin ops.

So maybe the code you used isn't well written or your Arduino is doing lots of other things?

edit:

> I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.
> 0 votes

---
Tags: arduino-mega, pwm, frequency
---


title: Problem with shift register

text:
# Question
Title: Problem with shift register
I have a problem with the shift register 74HC595.

The sketch I use is able to enable a specific led (8 are connected).

When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).

However, for the led connected to pin 15 (other side of the ic, see layout) it behaves differently. When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.

This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?

The code to switch on a led:

```
void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

```

where leds are the indices of the leds (0..7).

# Answer
You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on. You have to build a table similar to the following:

```
byte led[8] = {
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000
};

```

and later . . .

```
shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

```

where leds is a number 0..7
> 1 votes

---
Tags: arduino-uno, shift-register
---


# Question
Title: Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino
The error message, generated from Sublime, in its entirety...

Compiling KCT\_Swimv4l...

Creating C:\Users\ken\Documents\Arduino\_Build\KCT\_Swimv4l\KCT\_Swimv4l.ino.cpp.o...

'"avr-g++"' is not recognized as an internal or external command, operable program or batch file.

\[Stino - Error 1\]

---

This is initial install of "Arduino-like IDE".

I used the following installation procedure:

* Install Sublime Text 3
* From Sublime, View --\> Show Console
* From a web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
* Copy the code there to the Sublime-Console and press enter.
* From Sublime, CTRL + Shift + P --\> Type "Install" and choose "Install package"
* Enter "Arduino" and choose "Arduino-like IDE"
* from Arduino --\> Preferences --\> Select Arduino Application Folder.

Same problem with any sketch.

System Configuration:

-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0

github info on Stino was not helpful. Has anyone encountered this problem and found a solution for it? If not, I can open an issue there.

---

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --\> Show Console From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version. Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --\> Type "Install" and choose "Install package" Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --\> Preferences --\> Select Arduino Application Folder

On Compile, error msg is now different:
Compiling KCT\_Swimv4l...
Creating C:\Users\kct\Documents\Arduino\_Build\KCT\_Swimv4l\KCT\_Swimv4l.ino.cpp.o...
cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
cc1plus.exe: error: unrecognized command line option "-flto"
\[Stino - Error 1\]

# Answer
Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.

**Update**

I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)
> 1 votes

---
Tags: arduino-ide
---