# Question
Title: Error: Function not declared in the scope
I want to make a timer library. The cpp file I have written is:

```
#include "avr/interrupt.h"
#include "Arduino.h"

#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
    TIFR1 |= _BV(OCF1A);
    TCCR1B = 0X00;
    digitalWrite(13,!digitalRead(13));
}

void AllTimer::setTimer(void)
{
    TCNT1 = 0x0BDC;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
}

ISR (TIMER1_OVF_vect)
{
    dofun();
}

```

And the header file:

```
#ifndef AllTimer_h
#define AllTimer_h

class AllTimer{
public:
    AllTimer();
    void setTimer(void);

private:
    void dofun(void);
};

#endif

```

While compiling the file i am getting the following error:

```
sketch_jan05a.cpp: In function ‘void __vector_13()’:
sketch_jan05a.cpp:34:9: error: ‘dofun’ was not declared in this scope

```

# Answer
Answering here because I do not have enough rep to comment. At each iteration, the value in the timer counter must be reloaded. Either the ISR or dofun are responsible to reload TCNT1.
> 0 votes

# Answer
Because in the call:

```
 dofun();

```

you should put from which class you are calling that function. In your case:

```
AllTimer::dofun();

```

in that case your function must be declared as static method.

EDIT: Thanks to the comment:

I'm not pretty sure if your code reflects what you want to do. Because you can create your timer after defining the class:

```
Alltimer mytimer;

```

and call the method as a normal function (it must be declared as ***public***):

```
ISR (TIMER1_OVF_vect)
{
    mytimer.dofun();
}

```

But it is hard to say since I m not sure what you want to do.
> 4 votes

# Answer
`dofun()` is currently declared as a private member function, meaning you can't call it directly. It can only be called internally by an instance of the `AllTimer` class.

It looks like you probably want to declare it as a public static function instead. To do that, remove the `private` specifier from the class declaration, and put `static` before the function declaration. Your header should look something like this:

```
class AllTimer
{
public:
    AllTimer();
    void setTimer(void);
    static void dofun(void);
};

```

You will then need to change the ISR to include the class name in the call:

```
ISR (TIMER1_OVF_vect)
{
    AllTimer::dofun();
}

```
> 1 votes

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


# Question
Title: Arduino on ubuntu 14.4 gives "Broken pipe" and "Input/output error"
Im using arduino (R2) uno board and my pc is running 64bit ubuntu 14.4. I was previously using arduino on ubuntu 10.04 for a long time and got no error. I recently moved to 14.4 from 10.4.

I installed arduino using this command

```
$ sudo apt-get update && sudo apt-get install arduino arduino-core

```

later arduino appeared, but was not working. According to this link, i was able to launch the IDE on mouse click. I then tried to upload servo examples, i get following errors.

```
Binary sketch size: 1,056 bytes (of a 32,256 byte maximum)
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMGET"): Input/output error

```

I get the same error for even an Led blinking program too.

**Update 1:** (after Edgar's comment)

on terminal i get

```
~$ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4933543797518254688.tmp/Sweep.cpp -o /tmp/build4933543797518254688.tmp/Sweep.cpp.o
avr-g++: error: /tmp/build4933543797518254688.tmp/Sweep.cpp: No such file or directory
avr-g++: fatal error: no input files
compilation terminated.

```

But on the IDE, after enabling verbos i get

```
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4933543797518254688.tmp/Sweep.cpp -o /tmp/build4933543797518254688.tmp/Sweep.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo -I/usr/share/arduino/libraries/Servo/utility /usr/share/arduino/libraries/Servo/Servo.cpp -o /tmp/build4933543797518254688.tmp/Servo/Servo.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_analog.c -o /tmp/build4933543797518254688.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/avr-libc/malloc.c -o /tmp/build4933543797518254688.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/avr-libc/realloc.c -o /tmp/build4933543797518254688.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_digital.c -o /tmp/build4933543797518254688.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_pulse.c -o /tmp/build4933543797518254688.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c -o /tmp/build4933543797518254688.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_shift.c -o /tmp/build4933543797518254688.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WInterrupts.c -o /tmp/build4933543797518254688.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Stream.cpp -o /tmp/build4933543797518254688.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/HID.cpp -o /tmp/build4933543797518254688.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Print.cpp -o /tmp/build4933543797518254688.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WMath.cpp -o /tmp/build4933543797518254688.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/CDC.cpp -o /tmp/build4933543797518254688.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/new.cpp -o /tmp/build4933543797518254688.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp -o /tmp/build4933543797518254688.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In function ‘void store_char(unsigned char, ring_buffer*)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:100:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
   if (i != buffer->tail) {
                    ^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In function ‘void __vector_18()’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:129:21: warning: unused variable ‘c’ [-Wunused-variable]
       unsigned char c = UDR0;
                     ^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In member function ‘void HardwareSerial::begin(long unsigned int, byte)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:370:11: warning: unused variable ‘current_config’ [-Wunused-variable]
   uint8_t current_config;
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In member function ‘virtual size_t HardwareSerial::write(uint8_t)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:469:27: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
   while (i == _tx_buffer->tail)
                           ^
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/main.cpp -o /tmp/build4933543797518254688.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Tone.cpp -o /tmp/build4933543797518254688.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/IPAddress.cpp -o /tmp/build4933543797518254688.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/USBCore.cpp -o /tmp/build4933543797518254688.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WString.cpp -o /tmp/build4933543797518254688.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p -o /tmp/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.o /tmp/build4933543797518254688.tmp/Servo/Servo.cpp.o /tmp/build4933543797518254688.tmp/core.a -L/tmp/build4933543797518254688.tmp -lm
/usr/share/arduino/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/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.eep
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /tmp/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.hex
Binary sketch size: 2,554 bytes (of a 32,256 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build4933543797518254688.tmp/Sweep.cpp.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/username/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

avrdude done.  Thank you.

```

**Update 2:** (tried again, this time i get "broken pipe". Led 13 blinks like crazy and my servo sounds different, no movement but continues sound)

```
.
.
.
avrdude: avr_read(): skipping page 253: no interesting data
avrdude: avr_read(): skipping page 254: no interesting data
avrdude: avr_read(): skipping page 255: no interesting data
avrdude: verifying ...
avrdude: 2554 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4258280580047414287.tmp/Sweep.cpp -o /tmp/build4258280580047414287.tmp/Sweep.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/Servo/Servo.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_analog.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/malloc.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/realloc.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_digital.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_pulse.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/wiring.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_shift.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/WInterrupts.c.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/Stream.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/HID.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/Print.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/WMath.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/CDC.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/new.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/HardwareSerial.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/main.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/Tone.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/IPAddress.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/USBCore.cpp.o
  Using previously compiled: /tmp/build4258280580047414287.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p -o /tmp/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.o /tmp/build4258280580047414287.tmp/Servo/Servo.cpp.o /tmp/build4258280580047414287.tmp/core.a -L/tmp/build4258280580047414287.tmp -lm
/usr/share/arduino/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/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.eep
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /tmp/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.hex
Binary sketch size: 2,554 bytes (of a 32,256 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build4258280580047414287.tmp/Sweep.cpp.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/username/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMGET"): Input/output error

```

# Answer
Please use the last IDE version released here: arduino.cc/en/Main/Software The version 1.6.1 has many improvements about serial devices detection and sketches upload. It will solve your issues about older Arduino UNO version and Arduino Yun.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line?
I have a SwitchDoc Labs DS3231 Real Time Clock Module that I am using with an Arduino Mega. It's connected to 3.3V and the SDA(20)/SDL(21) pins. I'm also using SwitchDoc's RTC\_SDL\_DS3231\_ARDUINO library (see link to the example sketch below).

I can compile and run the example provided with the library just fine. However, I'm running into a very bizarre compilation problem when I remove the Clock set function calls in the setup.

Rather than take up the space and copy the code that works I'll just link to it on github: 100% working for me example.

The problem I am running into happens when I remove (or comment out) the section in the setup function that sets the time:

```
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Removed code
  // Start the serial interface
  Serial.begin(9600);
}

```

Then I get the following error when I try to compile/verify the sketch:

```
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/../
lib/gcc/avr/4.3.2/../../../../avr/lib/avr6/crtm2560.o: In function `__vector_default':
(.vectors+0x90): relocation truncated to fit: R_AVR_13_PCREL against symbol `__vector_36'
defined in .text.__vector_36 section in core.a(HardwareSerial.cpp.o)

```

If I add back just one single clock set call it will compile:

```
void setup() {
  // Start the I2C interface
  Wire.begin();
  Clock.setYear(15);  //Set the year (Last two digits of the year)
  // Start the serial interface
  Serial.begin(9600);
}

```

However, the truly strange thing is that if I simply add a Serial.println() line to the setup function, the sketch compiles too!

```
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  // Adding the following line allows the sketch to compile
  Serial.println("Why does this work now???");
}

```

Thanks for any help.

# Answer
> 4 votes
**Update**: This seems to be a linker bug. Quick fix: upgrade your Arduino installation. See the end of this answer for details. What follows is the first version of this answer, with a detailed explanation of the error message.

---

You have a problem linking the interrupt vector table with your program. I quite understand what the error message means, but I do not understand how in the world you can possibly have this error. This should not happen. I will try to explain the error anyway.

The Arduino Mega is based on an AVR chip. The AVR instruction set has “jump” and “call” instruction that come in two flavors:

* “absolute” jumps and calls (opcodes: `jmp` and `call`) can address the whole flash memory, which means you can branch from any part of the program to any other part, without restrictions.
* “relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: `rjmp` and `rcall`) have limited range: they can only bring you to nearby places, no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus better *if* the destination is close enough. On the smaller AVR chips (up to 8 K of flash), they can access the whole flash, then these chips lack the absolute flavors.

## How the vector table is normally linked

Every program you build for an AVR starts with an “interrupt vector table”. This is a series of jump instructions that are automatically executed whenever an interrupt triggers: if the *n*-th supported interrupt triggers, then the hardware automatically loads and executes the *n*-th jump instruction, which will jump the execution of the program to the corresponding ISR (*interrupt service routine*). The table is chip-specific: on the smaller AVRs (up to 8 K), it's a table of `rjmp`, whereas on the bigger ones it's a table of `jmp`. This table is part of the CRT (*C run time*) provided by the avr-libc library in a file named crtXXX.o, where XXX is a code identifying the chip. The Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.

I disassembled my own copy of crtm2560.o and found this vector table:

```
00000000 <__vectors>:
   0:   0c 94 00 00     jmp 0
   4:   0c 94 00 00     jmp 0
   8:   0c 94 00 00     jmp 0
   ...
  e0:   0c 94 00 00     jmp 0

```

You can see these are all `jmp` instructions (absolute flavor), as expected for any AVR with more than 8 K of flash. The address of the jump, however, is always 0, which is obviously wrong. This is because the proper addresses cannot be known until the program is fully built. When you build your program, the linker will put all the pieces together. It will then know where the ISRs are, and it will patch the vector table to make it correct. This kind of patching is known as “relocation”, and the linker performs this based on some “relocation records” included in the CRT. Here are the relevant records from my copy of crtm2560.o:

```
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_CALL        __init
00000004 R_AVR_CALL        __vector_1
00000008 R_AVR_CALL        __vector_2
...
00000090 R_AVR_CALL        __vector_36  [*]
...
000000e0 R_AVR_CALL        __vector_56

```

The record I marked with \[\*\] means: “at offset 0x90 into the vector table there is an absolute jump or call instruction, and the instruction should be modified to point to \__vector\_36”. This tells the linker how to fix the table when building the program.

If I instead disassemble a CRT for a smaller chip, I get a smaller table made of `rjmp` (instead of `jmp`) instructions, and the relocation records look like this:

```
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_13_PCREL    __init
00000002 R_AVR_13_PCREL    __vector_1
00000004 R_AVR_13_PCREL    __vector_2
...
00000032 R_AVR_13_PCREL    __vector_25

```

These records mean “at offset XXX into the vector table there is a PC-relative jump or call instruction, and the instruction should be modified to point to \__vector\_XXX”.

## Your error message

Your error message provides the following information:

* “crtm2560.o”: this is your CRT, where the vector table and the relocation records live.
* “.vectors+0x90”: this means the problem is at offset 0x90 into the vector table.
* “R\_AVR\_13\_PCREL against symbol \`\__vector\_36'”: this means there is a relocation record of type R\_AVR\_13\_PCREL (PC-relative jump or call) referencing \__vector\_36. **Here seems to be the problem**.
* “defined in \[...\] core.a(HardwareSerial.cpp.o)”: this \__vector\_36 is part of the serial port code from the Arduino core library.
* “relocation truncated to fit”: \__vector\_36 is too far to be reached by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type R\_AVR\_13\_PCREL, which is what you expect on smaller chips but not on your ATmega2560. You normally expect R\_AVR\_CALL.

Now, about the strange behavior: the exact point where the ISR lands when the program is built is difficult to predict. Add or remove a few lines in your code and the linker may bring the pieces together in a different order. Then, the infamous \__vector\_36 may end up being in range or out of range of a relative jump. Given the nature of the error, the behavior you find “strange” is actually quite normal.

## Further debugging

The root of the problem seems to be an incorrect relocation record in your CRT. You can try to disassemble the CRT to see what is wrong: search your computer for a file named crtm2560.o, probably in /Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6 or a similar place. The tool needed for disassembling is called “avr-objdump” and should be hidden somewhere in your Arduino installation folder. Once you find the files, start a terminal and type

```
/path/to/avr-objdump -d /path/to/crtm2560.o

```

with “/path/to” replaced by the actual paths. You should see something very much like the first listing of my answer, with lots of `jmp` instructions. If you have `rjmp` instructions instead, then something is already wrong at this level.

To see the relocation records, type:

```
/path/to/avr-objdump -r /path/to/crtm2560.o

```

The output should look like my second listing, with lots of `R_AVR_CALL` records. If you have `R_AVR_13_PCREL` instead, the records are wrong.

If this is the problem, then the obvious fix would be to replace the broken CRT with a sane one. You may try to reinstall the whole Arduino package. If you still have a corrupted CRT, you should report the error to the Arduino folks. Then you may try to fetch a fresh copy of the avr-libc and replace the relevant parts of your Arduino installation. Replacing just the CRT may or may not work: I don't know whether the last version of the CRT has incompatibilities with older versions of the rest of the libc.

## Update: this is a linker bug

I did some research, and I now believe you have hit a linker bug. There is a gcc option called `-mrelax` that allows some link-time optimizations. One if them is to have the linker replace some absolute jumps and calls by the smaller and faster relative ones. Obviously, this is only possible if the target address is within reach of the relative jumps or calls. There was a bug in old versions of the GNU linker (up to 2.22) where, under some obscure circumstances, it would erroneously believe the target was reachable, only to find out later that it was not. This bug mainly affected the interrupt vector table, producing the kind of error message you are seeing now.

Here is a partial timeline of this bug and its fix:

* November 2011: this is filed as bug 13410 on the bug tracker for the GNU binutils package.
* January 2012: Vidya Praveen, from Atmel, publishes a fix.
* February 2012: the fix is committed to the development version of binutils.
* October 2012: GNU binutils 2.23 is released, including the fix. The same month, the bug is reported again as issue 1071 on the Arduino issue tracker.
* June 2013: Paul Stoffregen links this new issue to the old bug.
* June 2014: Arduino gets an updated toolchain including binutils 2.23.2, which fixes the bug in the development version of Arduino.
* July 2014: Arduino 1.5.7 beta is released including the updated toolchain.
* September 2014: Arduino 1.0.6 is released *with the old toolchain*.

A workaround for the bug has been published by Mark Anderson on stackoverflow. The real fix, however, would be to upgrade to the latest Arduino package (1.6.1 as of this writing).

---
Tags: arduino-mega, i2c, compile
---


title: Why does timer ISR not execute?

text:
# Question
Title: Why does timer ISR not execute?
This is my code which I have written as a library

```
#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
     //TIFR1 |= _BV(OCF1A);

    TCCR1B = 0X00;
    //TIFR1 = 0X01;
    digitalWrite(13,!digitalRead(13));
    Serial.print("I printed");
    TCNT1 = 0X0000;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    //sei();
}

 void AllTimer::setTimer(void)
 {
    TCNT1 = 0x0000;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
 }

ISR (TIMER1_OVF_vect)
{
     AllTimer::dofun();
}

```

Code in Arduino IDE:

```
 #include <AllTimer.h>

 AllTimer mytimer;

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

 void loop()
 {
     mytimer.setTimer();
    //delay(200);
  }

```

But I am not getting anything on the serial monitor. What is the error I have made?

# Answer
> 6 votes
The Arduino `main()` calls `loop()` continuously, in a tight loop. Thus your `AllTimer::setTimer()` is called continuously, and each time it resets the counter (`TCNT1 = 0x0000;`). Thus the counter can never overflow.

---
Tags: timers, isr
---


# Question
Title: NodeJS (Galileo-IO) + Arduino sensor library
I've done some basic apps with NodeJS firmata where I can connect to my Arduino Uno and do the basics like reading a pin or doing a servo write. I'd like to go further and play with some different sensors from vendors like Adafruit.

Many such sensors appear to come with their own Arduino libraries. Using NodeJS firmata to communicate with my Uno, could I somehow use the sensor libraries? Maybe by including their header files in the Standard Firmata sketch before uploading or...? But then I don't know how I'd get at their methods from my NodeJS app.

Even better, I'd love a little direction on how to go about using an Arduino sensor library in a sketch, and use Galileo-IO to interact with the sensor that way, if possible.

# Answer
Including the header files for the libraries in the standard Firmata sketch is only the first step. You will have to also modify the sketch in order to actually *use* the libraries. You will have to figure out a way of interacting with the libraries through the Firmata protocol and implement this in your modified version of the sketch. You will then have to modify the JavaScript side to enable these new interactions. That's where you will write the missing methods
> 1 votes

---
Tags: sensors, library, arduino-galileo, node.js, johnny-five
---


# Question
Title: Pattern library for addressable LED strips
Is there any central place that we can get drawing pattern functions for the addressable LED strips like the once based on the WS2812B component? These are sold on the Adafruit site under the NeoPixel name. For example I know of a few pattern examples like the Larson Scanner (Cylon), a candle light flicker or a rainbow pattern. However I could not find a single pattern repository.

I am working on a project for kids learning to program the Arduino and it would be nice to have all the patterns in a single place and to be able to switch between the program examples with a mode switch.

If people send me links I am happy to post a blog of them.

# Answer
I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154

He uses the Fast\_SPI (now FastLED) library, which is truly exceptional!

https://plus.google.com/u/0/communities/109127054924227823508
> 7 votes

# Answer
Thake a look at this library.

In this video you can see some of the many animations available.
> 6 votes

---
Tags: led
---


title: Arduino/C++ byte manipulation

text:
# Question
Title: Arduino/C++ byte manipulation
Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.

Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.

eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.

01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1

What would be the most efficient way to accomplish this?

# Answer
> 2 votes
Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:

```
int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 0x08) retval |= 0x800;
   return retval;
}

```

On most microprocessors, this will compile into just a few instructions per statement.

This is also arguably more maintainable than a complex series of shift and mask operations.

# Answer
> 0 votes
Assuming the incoming bytes are guaranteed to come in even numbers, and your output is in little-endian order, you could do something like this:

```
void process_and_send_bytes(uint8_t data_in)
{
    uint16_t some_12_bit_function(uint8_t);  // processing function
    void send_byte(uint8_t);                 // sending function
    static uint8_t data_on_old = 0;
    static bool has_data_on_old = false;
    uint16_t processed_data = some_12_bit_function(data_in);
    if (has_data_on_old) {
        send_byte(processed_data << 4 | data_on_old);  // two pieces
        send_byte(processed_data >> 4);      // high 8 bits
        has_data_on_old = false;
    }
    else {
        send_byte(processed_data);           // send low 8 bits
        data_on_old = processed_data >> 8;   // save higher 4 bits
        has_data_on_old = true;
    }
}

```

Basically, when you get the first byte, this function outputs one byte and keeps 4 bits on hold. When you get the next byte, this outputs the 4 bits that where on hold, together with the new 12 bits, as two 8-bit packets.

# Answer
> 0 votes
I haven't tested this in any way whatsoever, but you could use a 32-bit integer as a buffer to store the bytes as you process them. Then, any multiples of 8 bytes that end up in the buffer can be passed on to wherever they are needed.

The first byte that comes in you process and push all 12 bits into the 32-bit integer - increment a counter by 12. You now have 12 bits in the buffer variable.

Then while the number of bits in the buffer is at least 8 bits you grab the upper-most 8 bits and pass them on to wherever they are going. Decrement the counter by 8 for each iteration. You have now sent 1 byte and you have 4 bits left in the buffer.

The next byte that comes in you push the new 12 bits into the buffer. The counter, increased by 12, is now 16.

16 is greater than or equal to 8, so send out the upper 8 bits of the 16 and decrement the counter by 8.

8 is greater than or equal to 8, so send out the upper 8 bits of the 8 and decrement the counter by 8.

Counter is now 0, so nothing else to send. Back to the beginning again.

Something like:

```
void processByte(uint8_t in) {
    static uint32_t buffer = 0;
    static uint8_t validBits = 0;
    buffer <<= 12; // Make room for 12 new bits.
    buffer |= (first processed bit << 11);
    buffer |= (second processed bit << 10);
    buffer |= ((in & 0x80) << 2);
    buffer |= (third processed bit << 7);
    buffer |= ((in & 0x70) << 1);
    buffer |= (fourth processed bit << 4);
    buffer |= (in & 0x0F);
    validBits += 12;

    while (validBits >= 8)
        validBits -= 8;
        executeByte((buffer >> validBits) & 0xFF);
    }
}

```

---
Tags: communication, c++
---


# Question
Title: Arduino on attiny85 driving 4-digit 7-segment using two 74HC595N shift register not alternating fast enough
I am using a port of the Arduino libraries on an AtTiny85 (1MHz) to drive a 4-digit 7-segment LED (common cathode, 12-pin). I'm just counting from 0 to 9 and alternating between the first two digits (pin 12 and 9) as a test. I am driving from two 74HC595N shift registers in series, the first of which will trigger S9018 NPN BJT transistors to turn on/off the digit I want and the other to light the segments.

The code seems to work fine, functionally, to alternate the two digits, but they don't alternate fast enough to make the LED show two solid digits, instead you can clearly see them flashing/alternating. Not sure what the bottleneck is but here's the code (please ignore my wiring for the 7 segments)

```
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const long output_interval = 10000; // Time to change each output
const int T_digit = 2; //period on one digit (4 digit 7-segment only)
const int duty_digit = 1; // duty cyle of a digit shown

// States
unsigned long outputT_last = 0; // Holds the last time output change was checked
unsigned long outputT_now = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  checkOutput();
}

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = (int)(outputT_now - outputT_last);
    digits = 0;
    if(digitON%T_digit < duty_digit){
      //bitwrite led 0
      bitWrite(digits, 0, 1);
    }
    else{
      //bitwrite led 1
      bitWrite(digits, 1, 1);
    }
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

void clearMemory(){
  leds = 0;
  updateShiftRegister();
}

void checkOutput(){
  outputT_now = millis();
  float timeleft = (int)((outputT_now - outputT_last)/1000);
  if (outputT_now - outputT_last >= output_interval){
    outputT_last = outputT_now; // output_interval set to 10000, because LED counts 0 to 9, and then needs to reset
  }
    // clearMemory(); // Uncomment this if you want 1 LED lit at time, all others turned off
    leds = sevenSegment1D(timeleft);
    updateShiftRegister();
    // output_count++;
  // }
  // Check if we reach the end, then do 1 more iteration for 0x0 (all turned off)
  // if(output_count > 8){
    // output_count=0;
    // clearMemory();
  // }
}

byte sevenSegment1D(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}

```

I tried to mod a float but it seems to require an int, so that's why I stopped at 2%1. I also converted the code from a single-digit 7-segment LED so please ignore anything that doesn't make sense in lighting up the segments.

I am not sure if the bottleneck is my code, the 1MHz AtTiny85, or the shift register.

EDIT: switched over to `micros()` instead of using `millis()` for more resolution. Still not solid.

# Answer
> 0 votes
The original idea was to divide up a specific period into segments where each digit on the 4-digit 7-segment would light up. I would use a mod(%) and divide it up to make the function call more generic for future extensibility (and also make it more asynchronous). What I learned is that it would probably take more work doing the calculations then just calling a function to reset and light up the next digit one after another. Here's the updated code:

```
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const int countdown = 60; // amount of time to countdown from in seconds
const long reset_interval = countdown*1000000; // interval before reset in microseconds, i.e. if countdown is set to 60s, every 60 seconds will reset display to countdown start

// States
unsigned long last_display_update_time = 0; // Holds the last time output change was checked
unsigned long curr_time = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  updateResetTimer(); // checks what the countdown is at
  int timeleft = countdown - (curr_time - last_display_update_time)/1000000;
  leds = getSevenSegmentFormation(timeleft/10);
  updateShiftRegister(0);
  leds = getSevenSegmentFormation(timeleft%10);
  updateShiftRegister(1);
}

void updateShiftRegister(int digit)
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = micros();
    digits = 0;
    bitWrite(digits, digit, 1);
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

//Turns off all 7 segments of a digit, will need to specify digits 0 to n
void clearMemory(int i){
  leds = 0;
  updateShiftRegister(i);
}

//Updating timer for resetting countdown
//Will take absolute current time and compare it to the last time checked, if it is greater than countdown value, we reset
void updateResetTimer(){
  curr_time = micros();
  if (curr_time - last_display_update_time >= reset_interval){
    last_display_update_time = curr_time; // reset_interval set to 10000000, because LED counts 0 to 9, and then needs to reset // actually set to 60*1000000 to countdown 1 minute
  }
}

byte getSevenSegmentFormation(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}

```

---
Tags: led, attiny, shift-register
---


# Question
Title: Learning to use ATmel Studio - using BOSSA downloader
The basic question - is BOSSA the right SOFTWARE "tool" to use in ATmel Studio to **connect / download to Arduino DUE AND NOT using VisualMicro**?

I cannot get BOSSA to AUtoScan for COM port. Getting error "Could not find a device" When I select my COM port ( COM4 ) which works in Arduino IDE I get "Could not connect to device on COM4"

This tells me that ATmel Studio does not recognize my Due at all.

Could someone please advise me what did I missed in configuring the Studio?

I can use Studio to run Arduino IDE (VisualMicro ) but I need to get away from Arduino IDE environment. Thanks for your time.

# Answer
The Arduino Due needs a patched version of Bossa, not the 1.2.1 version available on SourceForge. Supposedly the patched version is available on GitHub, or you can copy the version in the Arduino IDE.

Also, the Due USB port must be put into bootloader mode. Open then close the serial port at 1200 baud, and it will re-instantiate as a Bossa programming port.

To return to serial port mode, the only way I have found is to power cycle the Due.
> 1 votes

---
Tags: atmel-studio
---


# Question
Title: UNO analog input voltage reading not accurate
My loop code is this:

```
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(float(sensorValue*5000.0/1023));
delay(1);        // delay in between reads for stability

```

When I read 5V it gives 5000 mV. When I read 3.3V pin it gives 3211 mV. When I read 1442 mV battery it gives 1392. What do you think about this situation?

NOTE: There is no any additive circuit. Just wires.

# Answer
> 5 votes
Your question contains a number of errors and misconceptions.

Firstly the maximum output of a successive approximation ADC (here 0x3ff) corresponds to Vref - 1 LSB The voltage will thus be `sensorValue*5000.0/1024`. Note this error is less than the error of ±2LSB.

Measuring your 5V is futile, as this is the default analog reference, so the result must be 0x3ff.

Measuring the 3.3V pin will give a relative value to the 5V reference. Both are produced from commercial grade regulators with a accuracy of ±5%.

You are also confusing the precision of the reading (10 bit) with accuracy which is a best ±5% ±2LSB.

If you really want to measure voltage you should use the internal 1.1V bandgap reference. You would of course need to reduce the 5V and 3.3V to less than 1.1V. This introduces another potential error (even if you use 1% resistors), but would give more accurate results which are directly comparable.

# Answer
> 3 votes
Both your measurement (e.g. using a voltmeter) and the ADC of the Arduino have a limited accuracy (cf. table 28.7 in the datasheet of the ATmega328). Therefore you should never expect them to agree to all given digits.

Concerning the points raised in your comment:

> All comments are true but it gives 5V correctly, why?

`analogRead` returns a value between 0 and 1023. For all voltages above an (unknown) threshold close to 5 V, it will saturate and always return 1023, no matter what the actual input voltage is. This value is then converted to 5.000 V in your code. What you are probably seeing is just the maximum value your code can return, not an accurate measurement of a 5 V input voltage.

> And my voltmeter is not corrupted.

It doesn't have to be corrupted. It will still be off. Have a look at the manual to find the nominal accuracy. (Also note that accuracy and precision are two different things and different from the number of digits of the display, assuming your voltmeter is digital.)

---
Tags: arduino-uno, analogread
---


# Question
Title: Question about infrared receiver with metal shell to detect heart pulse rate?
I'm newbie to the world of arduino and environmental sensing. I have been searching for a while about how can I measure the heart pulse rate, I came through the following tutorial:

Click Here

I have the following Arduino IR Receiver with metal shell module that I want to use as the previous tutorial suggesting, but, the IR receiver used in the tutorial has no metal shell, so, my question is if they are both functioning the same way?
Can I position my IR Receiver exactly as the one in the tutorial or do I need some workaround to reach my goal based on the fact that it has a metal shell?
Thanks in advance.

# Answer
"Proper" oxygen meters use a bimodal LED - red + IR - so there will be limitations to this. They also have a piece of copper foil wrapped around the sensor & heavily earthed, so your shielded sensor has, already, an advantage!

You should be able to use your receiver exactly the same way. If you can ground the shield, do so.
> 1 votes

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


title: Port manipulation using C code

text:
# Question
Title: Port manipulation using C code
I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte `PINB & (1 << PB5)` equals 32, or `0b00100000`.

However, if I try to use

```
if( PINB &(1<<PB5) == 32){

```

or

```
if( PINB &(1<<PB5) == 0b00100000){

```

the LED doesn't respond.

Here's the full code:

```
void setup() {
  DDRB |= 0b00011111;
  Serial.begin(9600);
  }

void loop() {
  Serial.print("PINB &(1<<PB5)");
  Serial.println(PINB &(1<<PB5));

  if( PINB &(1<<PB5) ){
    PORTB |= (1<<PB0);
    }
  else{
    PORTB &= ~(1<<PB0);
    }
  }

```

What am I missing?

# Answer
`==` has higher precedence than `&`, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a *specific* value, just if the appropriate bit is set.
> 5 votes

---
Tags: programming, c
---


title: Connect 5V DC Fan to Ardumoto

text:
# Question
Title: Connect 5V DC Fan to Ardumoto
I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, https://www.sparkfun.com/products/9649) to Ardumoto (https://www.sparkfun.com/products/9815).

Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?

Thanks.

# Answer
If you look at the schematic on the product page it shows that the `Vin` from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.

With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that **it cannot be made to reverse**, therefore you should always give the direction pin a high signal. The Sparkfun hookup guide has a example code which shows how to control the motor shield, and some explination.
> 1 votes

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


# Question
Title: Seeedstudio Wifi shield v1.1 Not working with Arduino Mega 2560
I have been trying use the Seeedstudio wifi shield v1.1 with Arduino Mega 2560 as part of my project but I could not make the WiFly library provided on the wiki work with the Mega. I tried to run the example sketch wifly\_test but it did not work I tried some troubleshooting and found that the write commands to the shield were not successful. After a few hours of searching on the internet, I found out the problem and was able to solve it. I am posting my solution below. Anyone is welcome to add to my solution.

# Answer
The WiFly library provided at the Seeedstudio wiki uses the software serial to communicate with the WiFi shield. All the example files provided by the WiFly library use pins 2 and 3 as the Rx and Tx of the software serial. Moreover, the Wifi shield only allows pins 0-7 to be chosen as Rx and Tx by using different jumper combinations. The SoftwareSerial library, on the other hand, has the following limitation for the Arduino Mega

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

Thus, as a workaround, I jumped pin 2 of the shiled with pin 10 (Rx of Software Serial) and pin 3 with pin 11 (Tx of Software Serial) using connecting wires and used the jumper setting given on the wiki. Finally I made the following changes in the example code

```
// Pins' connection
// Arduino       WiFly
//  10    <---->    TX (via connecting pin 2 to 10 on wifi shield)
//  11    <---->    RX (via connecting pin 3 to 11 on wifi shield)

```

```
SoftwareSerial uart(10, 11); //change software serial pins for Mega

```

This allowed the Mega to communicate with the Wifi shield successfully using the WiFly library.
> 1 votes

---
Tags: wifi
---


# Question
Title: avrdude: stk500v2_ReceiveMessage(): timeout with ADDAC VCC
I am getting the above error message uploading the ADDAC VCC, and the only thing that's changed I think is the patch is bigger.

Is there a fix for this or will I have to send it back? Hope my formatting is OK

```
Binary sketch size: 12,330 bytes (of a 258,048 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cwiring -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/build953252908946386724.tmp/comps.cpp.hex:i
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 17:07:18
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/luke/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: wiring_open(): releasing DTR/RTS
avrdude: wiring_open(): asserting DTR/RTS
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

```

# Answer
> 3 votes
Your log is showing that communication is failing right away (avrdude never gets a proper response). This can mean that

1. the VCC is not resetting
2. there is no bootloader installed
3. there is some other defect

You can test case is by manually hitting the reset switch around the time that avrdude starts. If the necessary pins are available, you can exclude case 2 by installing a new boot loader with a programmer, which also tests scenario 3 a bit.

---
Tags: bootloader, avrdude
---


title: OSC parsing code. Can it be optimised?

text:
# Question
Title: OSC parsing code. Can it be optimised?
I'm using this OSC library and TouchOSC to controls some motors. Right now I'm receiving those two kind of messages:

```
/u/1       // move motor 1 of default steps
/u/2       // move motor 2 of default steps

/u/1/5     // move motor 1 of 5 steps
/u/3/25    // move motor 1 of 25 steps

```

and so on.

Right now I have this piece of code:

```
void loop() {
  OSCMsgReceive();
}

void OSCMsgReceive() {

  OSCMessage msgIN;
  int size;
  if ((size = Udp.parsePacket()) > 0) {
    //Serial.println("incoming message.. ");
    while (size--) {
      byte n = Udp.read();
      msgIN.fill(n);
      Serial.print((char)n);
    }
    Serial.println();
    if (!msgIN.hasError()) {
      msgIN.route("/u", up);
    }
  }
}

void upValueExtraction(char *ca, int &num_motor, int &num_step) {
    String s = String(ca);
    String num_motor_s = "";
    String num_step_s = "-1";
    int n = 0;
    for(int i=0; i<s.length(); i++) {
      char c = s[i];
      if(c=='\\') {
        n++;
      }
      if(n==0) num_motor_s += c;
      if(n==1) num_step_s += c;
    }
    Serial.print("num motor: "); Serial.println(num_motor_s.toInt());
    Serial.print("num step: "); Serial.println(num_step_s.toInt());

    num_motor = num_motor_s.toInt();
    num_step = num_step_s.toInt();
}

void up(OSCMessage &msg, int addrOffset) {
  static boolean flag = false;
  if (!flag) {
    Serial.print("route: up "); Serial.println(addrOffset);

    char ca[200];
    msg.getAddress(ca, addrOffset+1);

    int num_motor, num_step;
    upValueExtraction(ca, num_motor, num_step);

    if(num_step==-1) {
      num_step = defaul_steps;
    }

    Serial.print("Have to move motor n ");
    Serial.print(num_motor);
    Serial.print(" of step ");
    Serial.println(num_step);
  }
  flag = !flag;
}

```

Even if it is working and even if I'm using an Arduino DUE (much more memory then the UNO) I think it can be optimised.

Does it contains some leeks? How can I better use the OSC matching part of the library? Any kind of "embedded c++" guidelines? Can I do everything inline without a `ca` char array and `s` String variables? Is better to use Arduino Lib `String` class or plain old C str\* functions? Any kind of comment?

Thanks in advance.

# Answer
> 1 votes
OSC is such a simple format that I ended up ditching libraries entirely, and just parsing the UDP packets directly with a state machine. Just learn the wire format of the bytes and parse the state machine explicitly.

It's just a trivial function calling format. The message starts with a 32-bit padded zero terminated string (important!) for the method name. I am not sure if the type tag is mandatory but it was always being sent (ie: ",iff"), then the binary values corresponding to what type tag says - like bigendian int32,float32,float32.

This was related to OSC generated by ChucK, SuperCollider, and CSound.

Real optimizations would come just from the design of the protocol itself. You will need to assume that any UDP packet can be dropped.

You are sending motor changes as diffs from current position, so you need to handle packet drops somehow. (ie: Do you have a TCP-like mechanism? Do you change the design to send absolute motor positions so that position reports are idempotent and subject to re-broadcast? Do you ack message receipt individually, or do you periodically poll the device for its current state?)

---
Tags: c++, arduino-due, c, string
---


# Question
Title: Integrating Shift Registers into 7 Segment LED Circuit
I'm trying to implement a shift register(s) into my circuitry and program to control two seven segment LEDs that would count up from 00 - 99. So far I have a fairly straightforward code (at least, I think. It's my first time experimenting with creating my own void functions) that controls the 7 segs in this manner, but I end up using every single digital pin on my Uno. Here it is:

```
const int led1a = 13;
const int led1b = 12;
const int led1c = 11;
const int led1d = 10;
const int led1e = 9;
const int led1f = 8;
const int led1g = 7;
const int led2a = 6;
const int led2b = 5;
const int led2c = 4;
const int led2d = 3;
const int led2e = 2;
const int led2f = 1;
const int led2g = 0;

void setup() {
    pinMode(led1a, OUTPUT);
    pinMode(led1b, OUTPUT);
    pinMode(led1c, OUTPUT);
    pinMode(led1d, OUTPUT);
    pinMode(led1e, OUTPUT);
    pinMode(led1f, OUTPUT);
    pinMode(led1g, OUTPUT);
    pinMode(led2a, OUTPUT);
    pinMode(led2b, OUTPUT);
    pinMode(led2c, OUTPUT);
    pinMode(led2d, OUTPUT);
    pinMode(led2e, OUTPUT);
    pinMode(led2f, OUTPUT);
    pinMode(led2g, OUTPUT);
}

void loop () {
    led1_0();
    led2_run();
    led1_1();
    led2_run();
    led1_2();
    led2_run();
    led1_3();
    led2_run();
    led1_4();
    led2_run();
    led1_5();
    led2_run();
    led1_6();
    led2_run();
    led1_7();
    led2_run();
    led1_8();
    led2_run();
    led1_9();
    led2_run();
}

void led1_0() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, LOW);
}
void led1_1() {
    digitalWrite(led1a, LOW);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, LOW);
    digitalWrite(led1e, LOW);
    digitalWrite(led1f, LOW);
    digitalWrite(led1g, LOW);
}
void led1_2() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1c, LOW);
    digitalWrite(led1g, LOW);
}
void led1_3() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, LOW);
    digitalWrite(led1g, LOW);
}
void led1_4() {
    digitalWrite(led1a, LOW);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1e, LOW);
    digitalWrite(led1d, LOW);
}
void led1_5() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1b, LOW);
    digitalWrite(led1e, LOW);
}
void led1_6() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1b, LOW);
}
void led1_7() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, LOW);
    digitalWrite(led1e, LOW);
    digitalWrite(led1f, LOW);
    digitalWrite(led1g, LOW);
}
void led1_8() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1e, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1g, HIGH);
}
void led1_9() {
    digitalWrite(led1a, HIGH);
    digitalWrite(led1b, HIGH);
    digitalWrite(led1c, HIGH);
    digitalWrite(led1d, HIGH);
    digitalWrite(led1g, HIGH);
    digitalWrite(led1f, HIGH);
    digitalWrite(led1e, LOW);
}
void led2_0() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, LOW);
}
void led2_1() {
    digitalWrite(led2a, LOW);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, LOW);
    digitalWrite(led2e, LOW);
    digitalWrite(led2f, LOW);
    digitalWrite(led2g, LOW);
}
void led2_2() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2c, LOW);
    digitalWrite(led2g, LOW);
}
void led2_3() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, LOW);
    digitalWrite(led2g, LOW);
}
void led2_4() {
    digitalWrite(led2a, LOW);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2e, LOW);
    digitalWrite(led2d, LOW);
}
void led2_5() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2b, LOW);
    digitalWrite(led2e, LOW);
}
void led2_6() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2b, LOW);
}
void led2_7() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, LOW);
    digitalWrite(led2e, LOW);
    digitalWrite(led2f, LOW);
    digitalWrite(led2g, LOW);
}
void led2_8() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2e, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2g, HIGH);
}
void led2_9() {
    digitalWrite(led2a, HIGH);
    digitalWrite(led2b, HIGH);
    digitalWrite(led2c, HIGH);
    digitalWrite(led2d, HIGH);
    digitalWrite(led2g, HIGH);
    digitalWrite(led2f, HIGH);
    digitalWrite(led2e, LOW);
}
void led2_run() {
    led2_0();
    delay(1000);
    led2_1();
    delay(1000);
    led2_2();
    delay(1000);
    led2_3();
    delay(1000);
    led2_4();
    delay(1000);
    led2_5();
    delay(1000);
    led2_6();
    delay(1000);
    led2_7();
    delay(1000);
    led2_8();
    delay(1000);
    led2_9();
    delay(1000);
}

```

So how would I reduce the amount of pins used while still keeping functionality? I have two 74HC595N shift registers at my disposal.

Thanks!

# Answer
I have done exactly this, to great effect.

```
int clockPin = 4;
int dataPin  = 2;
int oePin    = 3;

// Here are the digits from 0 to 9, as bitmaps.
// You will need to work out which segments are which,
// according to your wiring, and make your own.
unsigned char digitmaps[]={0x7b,0x11,0xe3,0xb3,0x99,0xba,0xfa,0x13,0xfb,0xbb};

void setup() {
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);
  pinMode(oePin,OUTPUT);
}

void sendnumber(unsigned int number, int oePin,int dataPin,int clockPin) {
   digitalWrite(oePin,LOW);
   shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[(number/10)%10]);
   shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[number%10]);
   digitalWrite(oePin,HIGH);
 }

void loop() {
  for (int i=0; i<100; i++) {
    sendnumber(i,oePin,dataPin,clockPin);
    delay(1000);
  }
 }

```

The crux of the matter is shiftOut, which shifts 8 bits out the dataPin, toggling the clockPin as it goes, high bit first (MSBFIRST), looking up the pattern in the table. dataPin goes to serial in on the FIRST shift register, clockpin to BOTH clocks, oePin to BOTH OE and another one, I think store register? Q7' or QH' (depending on your docs - it's the overflow pin) of the first goes to the serial in of the second, and +5v & GND, as per normal, and the 8 parallel out Q0-Q7 go to the pins on the 7-segment.

If there's anything unclear, or anything I've missed, let me know. My example shows 2 digits, but any number will work, up to the available power.

Things might be clearer if I convert the digitmaps to binary. The below compiles to the same thing as the one above.

```
unsigned char digitmaps[]={
   B01111011, // 0
   B00010001, // 1
   B11100011, // 2
   B10110011, // 3
   B10011001, // 4
   B10111010, // 5
   B11111010, // 6
   B00010011, // 7
   B11111011, // 8
   B10111011}; // 9

```

This is because, in my wiring, from left to right the bits represent in the 8 on my display: center,bottom left,bottom,right bottom,top left,decimal point/not used,top,right top. You can see that the digit "1" has 2 1's in it: the 4th (right bottom) and the last (right top). An 8 has all of the bits set to 1, except position 6 - because that's the decimal point. Send individual bits (e.g. B00010000) to see which segments shows up, make a map, and then combine them.
> 4 votes

---
Tags: led, sketch, shift-register
---


# Question
Title: GSM Modem with MAX232 to Arduino Serial?
I have GSM modem that has MAX232 interface for RX/TX/GND on three pins. Is it possible to interface Arduino in some way?

Tnx for help.

# Answer
Yes, with another MAX232, or bypass the MAX232 somehow.
> 1 votes

---
Tags: gsm, max232
---


# Question
Title: AVCC and AREF when using a reference voltage lower than 5V?
I'm designing a circuit that will use a 2.5v reference for the AREF. Should AVCC be powered from 5V or 2.5V?

# Answer
> 3 votes
> AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6...4 use digital supply voltage, VCC.

So it should be connected to 5V.

---
Tags: analogread, system-design
---


# Question
Title: Cheap weatherproof ultrasonic range sensor?
What's an inexpensive ultrasonic range sensor that's reasonable waterproof or weatherproof that also interfaces easily with an Arduino?

I've used these kinds of ultrasonic range sensors, which are cheap and trivial to wire to an Arduino, but they're not very robust and are easily damaged since you can't cover them without that covering obstructing the soundwave.

Maxbotix sells a "Weather-Resistant" ultrasonic range sensor, but it's around $100, which is a little out of my price range.

I've researched those "parking sensors" used on cars, but I haven't seen anyone successfully interface them with an Arduino. It's also hard to tell how they're controlled. Some sites sell batches of the sensor for $3/each, but I don't think this includes the control electronics. Ebay listings that include what appears to be a bulky controller board seem to go for around $50-$100, which makes them a little pricey.

# Answer
Those modules are just the ultrasonic transducers. You can see the two pin connector. You can probably get those cheap boards, de-solder the two transducers, and connect the wires from two of the water-proof ones.
> 1 votes

---
Tags: sensors
---


title: Using A 4 Ohm Speaker With Arduino

text:
# Question
Title: Using A 4 Ohm Speaker With Arduino
I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?

# Answer
5v, 4ohm, \>1amp from a pin rated for 0.04amps; this isn't safe!
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; here is a slightly more complex layout, there are many examples on the web.
> 0 votes

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


# Question
Title: Integrating an analog signal using Arduino Uno SMD
I need to integrate an analog signal using my Arduino Uno. I am sampling the input signal at 1 KHz using a delay command in my `void loop()` and adding up the values at the analog read at that specific time. Then I multiply my added output with 0.001 s to get my integration.

Since, I am new to Arduino Uno, I want some review on the code to check whether I am correct or not. Kindly help, I'll be indebted.

```
const int a=13; //my output pin
const int c=A0; //my input pin
int d=0; //my summation variable
int e=0; //my integration variable(integration as a summation)
void setup()
{
  pinMode(a, OUTPUT);
}
void loop()
{
  int b=analogRead(c);
  d=d+b; //my summation
  e=d*10^-3; //my integration as a summation, by sampling my signal at 1ms
  analogWrite(a,e); //writing my integration into my output pin

  //print the results to the serial monitor
  Serial.print("input=");
  Serial.print(b);
  Serial.print("\t output=");
  Serial.println(e);

  delay(1); //wait for 1ms as I want it sampled at that rate
}

```

# Answer
There are a couple of issues with your code.

First of all, `10^-3` is not a valid constant in C/C++ code. The correct syntax would be `1e-3`, which means 1 × 10-3. But you have the further problem that you're working with integer variables, and 0.001 rounded to the nearest integer is just zero. You'll probably want to use `float` variables for this math.

Also, the values you get from `AnalogRead()` are all non-negative integers, so your summation will quickly overflow unless you subtract a constant from each reading in order to get both positive and negative values.

The second issue is about the `delay()` function, and trying to use it to determine the sample rate of your system. The `delay()` function is not all that precise. It really is just guaranteed to produce a delay of *at least* the number of milliseconds specified, but it can be more — sometimes much more.

Furthermore, the other operations in your loop take much longer than 1 ms anyway. For example, you're printing on the order of 25 to 30 characters to a serial port on every iteration, which is an overall rate of 25,000 to 30,000 characters per second. Unless you're running your serial port at an insane baud rate (430.8 kbaud or more), it simply won't be able to keep up, and it will end up increasing the period of your loop to whatever time it needs.

All of this means that the sample period of your loop is NOT 1 ms as you want, and in fact, it can vary quite a lot based on other things that are going on in the system, such as interrupts. For doing this kind of DSP, you will want to learn how to use a timer interrupt to control the sampling of the analog input, and you'll need to trim the amount of data transmitted for each sample to an amount your serial link can handle.
> 3 votes

# Answer
I'm not entirely clear on what you're trying to achieve mathematically. However, I can see a number of issues in your code which I'll try to address briefly.

**Arithmetic**
I suspect this line isn't doing what you intended:

```
e=d*10^-3

```

The `^` operator in C/C++ is actually a bitwise XOR (exclusive-or). There is no arithmetic raise-to-the-power operator.

There is a function called `pow()` for calculating exponents. However, there's no point using it for a fixed value. It would be better to explicitly write the number, i.e. 0.001.

**Precision**
The power issue notwithstanding, it's important to note that you're working with integers here, and the result of `analogRead()` is only in the range 0 to 1023. Dividing that by 1000 and storing the result as an integer will destroy your data -- most readings will effectively be 0. (That's not to mention the fact that an `int` has a limited range and will overflow quite quickly if you don't reset it.)

The simple solution would be to store the data using the `float` data type (floating point). You would need to declare variables `b`, `d` and `e` as `float` instead of `int`. That should let you divide down by 1000 without losing significant precision.

**Output range**
The `analogWrite()` function has a very specific output range. It will only accept values 0 to 255 (inclusive). I'm not entirely sure what you're hoping to do with it, but I suspect you'll need some way to map your integration calculation onto that output range, or possibly reset your summation periodically.

If you don't do that, you'll probably find that `e` ends up over 255 very quickly (within a couple of seconds). The result is that you won't see any change on the output PWM.
> 0 votes

# Answer
Here is an edited version of your code:

```
/*
 * Integrate a signal read on analog input 0.
 * Print the result every 2 seconds on the serial port.
 */

const int input_pin = A0;
unsigned long last_time_sampled = 0;
unsigned long last_time_printed = 0;

// The integral is in units of DN*us, 1 DN being the ADC step.
float integral = 0;

// Convert from DN*us to V*s, assuming a 5 V reference.
const float conversion = 5.0 / 1024 * 1e-6;

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

void loop()
{
    int sample = analogRead(input_pin);
    unsigned long now = micros();

    // Approximate the signal as a constant equal to the current sample
    // from the time of the previous sample until now.
    integral += sample * (now - last_time_sampled);
    last_time_sampled = now;

    // Print the results every 2 seconds.
    if (now - last_time_printed >= 2000000) {
        Serial.print("input = ");
        Serial.print(sample);
        Serial.print(", output = ");
        Serial.println(integral * conversion);
        last_time_printed = now;
    }

    // Limit the sampling rate to no more than 1000/s.
    delay(1);
}

```

The main changes I did are:

1. I renamed the variables to give them more meaningful names. This single change makes the code a lot more readable.
2. I removed those comments made redundant by the better variable names.
3. I removed `analogWrite()`, since I couldn't make any sense out of it.
4. I compute the time between samples as time differences. Unless you take your samples on some kind of timer interrupt, the delay between samples will never be 1 ms.
5. I stored the integral as a float to avoid overflows.
6. I removed the summation variable, as it was redundant with the integration variable. Instead, there is a conversion factor for converting the integral from its “natural” unit (DN⋅µs) into a more human-friendly unit (V⋅s).
7. I print the results only every 2 seconds, as nobody will read something printed every millisecond.
8. I added some comments, most importantly for making explicit the approximation used in computing the integral.

There is still one caveat with this code: once the integral is roughly 107 times larger than the samples, which should happen after only a few hours, the integral is not incremented any more, due to loss of precision.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Different dht21 readings on different arduinos
First of all, let me begin by saying that I'm still pretty much a rookie.

I have a project with a dht21, an LDR and an ultrasonic distance sensor. I have 3 different arduino uno boards, namely:

* A (supposedly) original arduino uno r3.
* A chinese nhduino, arduino uno r3 clone.
* And this one, sitting on top of this.

I've been playing around with the three boards for the last couple of months, testing a variety of sensors and having the same results with the three boards, as expected. But then, with the aforementioned setup, I'm getting very different readings on the DHT21 sensor. If I use the "regular" (first two) arduinos plugged in my laptop, the readings are consistent. But if I use the banana pi(duino), I get the temperature reading correct, but getting weird humidity readings... pretty most of the time a 5% humidity value.

Everything tested on the same room, same sensors and same protoboard. No external power supply.

I'm totally clueless here, any ideas of what could be the problem?

Thanks.

# Answer
Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.
> 0 votes

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


title: Razor 9DOF SMD Capacitor replacing

text:
# Question
Title: Razor 9DOF SMD Capacitor replacing
I just bought This IMU a while ago, and when I reached the point where I wanna connect it, I noticed that one of the capacitors have been removed by accedint, and since it took too long to check the product, I won't get to replace it or get any refund, so my question, how can I replace that SMD capacitor? P.S. I have some Ultrasonic sensors might have the same SMD capacitors that I can take off and replace with if anyone can help.

# Answer
You are looking for C22, 0.1uF capacitor, connected to smooth the 3.3v from the regulator. If you are not using the battery connector, you can probably just leave it out.

You could just get a capacitor with leads and connect it somewhere between 3.3v and ground. You can use the ISP header (2x3 holes on the right) for this. I think it's the top-right and bottom-right pin.
> 0 votes

# Answer
You are on a tough road. I hope someone can give you specifics. Normally you would able to identify the capacitor from its parts designation, but that board does not have any. So you will have to match the schematic (assuming spark fun provides one) to the board layout to figure out what it is. The cost of the part is probably over a penny, maybe even 2 cents. In other words, not an issue.

It will require hot air to desolder one from another board and to solder this one on. Someone might be able to do it with a fine tip solder pencil, but not likely.

Bottom line; find someone who has experience repairing boards, or order another one. Amazon has breakout boards for the 6050 for $6. But I see this one has Serial, and a magnetometer, so it is not quite the same. But depending on what you plan to do with it, it could work.
> 0 votes

# Answer
Try using two soldering pencils, one in each hand. makes it easy to remove the capacitor from the donor board.
> 0 votes

---
Tags: sensors, electronics
---


# Question
Title: Serial communication and Arduino program in C
When I flash this simple code (using Arduino-Makefile):

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

void init_io(void) {

    // open serial port
    Serial.begin(9600);
    while (!Serial);
    Serial.println("Comm-link online");

}//END: init_io

int main(void) {

    init_io();

    while (1) {

        // send data only when you receive data:
        if (Serial.available() > 0) {

            // read the incoming byte:
            int incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);

        } else {

            //  Serial.println("No serial ");

        }

    }//END: loop

    return 0;
}//END: main

```

I only see first two chars printed in the serial output:

> ~$\> Co

The input also does not work as intended - tested on two independent microcontrolers, Mega and Uno. I'm not sure what's the cause of this behaviour. Here's the Makefile:

```
BOARD_TAG    = uno # megaADK uno
MONITOR_PORT  = /dev/ttyACM0
ARDUINO_LIBS =

include $(ARDMK_DIR)/Arduino.mk

```

It's definitely not a hardware problem, I've used serial i/o before in other projects.

# Answer
> 2 votes
When using the Arduino core library, you normally do not write a `main()` function. Instead, you write `setup()` and `loop()` and rely on libcore's provided `main()` for calling them.

If you nevertheless want to provide your own `main()`, then you should call `init();` (with no arguments) before you try to use the library. Adding this single call makes your program work on my Uno.

However, since it does not seem to be officially documented, this trick may not be safe against upgrades in the core library. Writing `setup()` and `loop()` should be more future-proof.

---
Tags: serial, c++
---


# Question
Title: How big of a difference is there between an Arduino Uno and the rest?
Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it built for the Teensy 2.0. On the page for the Teensy 2.0 there is a link for an Arduino Library for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be

```
#if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
 #define __AVR_AT90USBX2__
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
 #define __AVR_AT90USBX6__
#else
 #error "Unsupported device"
#endif

```

Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys.

What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.

# Answer
> 1 votes
The code won't work as a traditional project when uploaded on an Uno, because the Uno does not talk directly to the Host, it only speaks UART.

But good news is that the Uno uses another atmega chip, an Atmega8u2 on the older models or Atmega16u2 on the others. That IC handles directly the USB connection with the host on behalf of the Atmega328. And that code below is actually (close enough) support for that IC:

```
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__

```

That means you should be able to upload the code (or a similar one) on that 'frontend' IC, so it acts as a HID device, and connects to the main 328 for any I/O you might need.

To do the upload on that other chip, you can use an ISP programmer on the 6pins header close to USB, or you can use the DFU programmation mode over USB.

I'm sorry for not giving external references or code, but I'm answering from my phone!

Edit: after a short browse over the code, it's definitely *possible* to implement that using an uno, but you'll need to split the code between the two chips: the USB interface to behave like ah HID device and the main I/O chip to talk midi, and implement comms between both.

Edit #2:

Here's a few resources that might help to work out USB and Midi using Arduino, but it looks like none is a cooked in USB on atmegaXu2 to Midi on atmega328:

And if you're not at ease with AVR development, it's gonna be **HARD**. You'd better get a teensy2 or a leonardo where that code should compile and work with little effort.

HTH

# Answer
> 1 votes
That program will make the arduino board act like a keyboard to the PC it's plugged in. This can't be done on the Uno, since it doesn't have USB support.

# Answer
> 0 votes
Generally, the differences between the different chips are mostly: amount of memory (sram, eeprom), number of pins (analog, digital, pwm), numbering of pins, and hardware support for protocols (serial, SPI, 2 wire etc)

In this case, you would have to go through the code wherever you find `#IFDEF __AVR_AT90USBX2__` or `#IFNDEF __AVR_AT90USBX2__` and the others - you would need to work out what it is doing differently for each, and work out how you would do the same thing on the Arduino Uno (which runs on an Atmega328).

---
Tags: arduino-uno, programming, arduino-leonardo, arduino-micro, teensy
---


title: Is PulseIn fast enough for Quadcopter?

text:
# Question
Title: Is PulseIn fast enough for Quadcopter?
I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn

# Answer
You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.

pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so.

What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.

In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).

You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.

---

FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library here that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.
> 1 votes

---
Tags: arduino-mega, interrupt, pulsein
---