Pi and Arduino

You’ve probably seen Dr. Monk’s blog on using Pi and Arduino, but what if you don’t have the Arduino software installed on a nearby computer?  (Or, like me, you are just perverse and want to make something work only using the RasPi.)

I had a quick look at getting the Arduino IDE running on the Pi, but that’s likely to be effort because the Arduino page specifically states you must use Sun’s version of Java or it won’t compile.  That’s an issue because Sun (now Oracle) haven’t made a version of Java for the Pi (so far).

So, time to learn how to program an Arduino without using the IDE.  These instructions basically worked first time for me, except I had an issue with actually programming the Arduino which turned out to be because the USB hub I was using to provide power was only giving around 4.5v to the Pi – which is out of spec.  (Aside: That may well be what caused the problem with the Sandisk Cruzer USB flash drive – I can’t tell if it works now because the drive has gone permanently write protected, which is a bit annoying)

Note these instructions are for the Arduino Uno.

In summary you need to install the AVR toolchain:

sudo apt-get install gcc-avr avr-libc avrdude

Create your program for the Arduino, say as blink.c (source heavily based on the above link):

#include <avr/io.h>
#include <util/delay.h>
#define BLINK_DELAY_MS 500
int main (void)
{
  /* set pin 5 of PORTB for output*/
  DDRB |= _BV(DDB5);
  while(1) {
    /* set pin 5 high to turn led on */
    PORTB |= _BV(PORTB5);
    _delay_ms(BLINK_DELAY_MS);
    /* set pin 5 low to turn led off */
    PORTB &= ~_BV(PORTB5);
    _delay_ms(BLINK_DELAY_MS);
  }
  return 0;
}

Now I created a short shell script “program.sh” to compile and program the board, it takes the C file to compile as an argument, e.g. ./program.sh blink.c

#!/bin/bash
if [ -z $1 ]; then
 echo "Usage $0 <source.c>"
 exit
fi
FILE=$(echo $1 | sed 's/\..*//')
rm $FILE.o $FILE.elf $FILE.hex
avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o $FILE.o $1
avr-gcc -mmcu=atmega328p $FILE.o -o $FILE.elf
avr-objcopy -O ihex -R .eeprom $FILE.elf $FILE.hex
avrdude -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:$FILE.hex

Run that over your C file and you should see output as your Arduino is programmed, and then the LED on the Arduino starts to flash.

Source in easy to pull form is over on github.

Comments are closed.