Raspberry Pi + Arduino + SPI


This tutorial will show you how to communicate from your raspberry pi to your arduino using 3-wire SPI.


  • 1 Raspberry pi (running Raspbian)
  • 1 Arduino
  • 4 wires

Your raspberry pi should be running the newest version of Raspbian.  To ensure your system is up-to-date please download and run rpi-update.




Open your Arduino ide and flash the below code to your Arduino.

Arduino code

Raspberry Pi

With your updated rasbian system you should have the drivers that you need. Now it’s time to load them.

modprobe spi_bcm2708
modprobe spidev

Check to be sure the modules loaded:

Module Size Used by
spidev 5944 0
spi_bcm2708 5350 0
snd_bcm2835 21681 0
snd_pcm 81170 1 snd_bcm2835
snd_seq 59528 0
snd_timer 21602 2 snd_seq,snd_pcm
snd_seq_device 6924 1 snd_seq
snd 57427 5 snd_seq_device,snd_timer,snd_seq,snd_pcm,snd_bcm2835
snd_page_alloc 5343 1 snd_pcm
i2c_bcm2708 3822 0

Raspberry Pi Code

Save the below code as spidev_test.c on to your Raspberry Pi and compile it

gcc spidev_test.c -o spidev_test


Plug your Arduino to your desktop via the serial cable. Open the arduino Serial Monitor and set the bitrate to 115200. Now, on the Raspberry Pi, run the compiled code

sudo ./spidev_test

You should see HELLO WORLD print in the Arduino IDE Serial Monitor.


    • Make sure that your kernel has the required drivers (spi-bcm2708.ko and spidev.ko)

pi@raspberrypi ~/spi $ ls -al /lib/modules/`uname -r`/kernel/drivers/spi/
total 64
drwxrwxr-x 2 pi pi 4096 Aug 10 10:53 .
drwxrwxr-x 23 pi pi 4096 Aug 10 10:53 ..
-rw-rw-r– 1 pi pi 14428 Aug 10 10:53 spi-bcm2708.ko
-rw-rw-r– 1 pi pi 10852 Aug 10 10:53 spi-bitbang.ko
-rw-rw-r– 1 pi pi 15803 Aug 10 10:53 spidev.ko
-rw-rw-r– 1 pi pi 10693 Aug 10 10:53 spi-gpio.ko

Thanks to Nick Gammon for the SPI slave code.

Thanks to Anton Vorontsov for the kernel Documentation spidev_test.c example code.


Arduino Poor Man’s Oscilloscope


This tutorial will show you how to use your Arduino as an oscilloscope.  We end the tutorial with a verification portion that uses the Arduino to generate a square wave, requiring a single wire.


Lxardoscope is another Arduino + real-time graphing project that has the potential to turn an Arduino into an oscilloscope.  Unfortunately, I was unable to get any readings (the visual graph remained static).

Poor Man’s Oscilloscope

First, download processing.

gzip -d processing-1.5.1-linux.tgz
tar -xf processing-1.5.1-linux.tar

Desktop Application

Arduino uses a modified RXTXcomm.jar library.  This causes a problem when the processing project runs poor man’s oscilloscope and loads the RXTXcomm.jar library bundles with the processing project.  Instead, we wish for process to load the modified Arduino RXTXcomm.jar library.  To remedy this problem we simply replace processing RXTXcomm.jar with the Android specific RXTXcomm.jar.

rm processing-1.5.1/modes/java/libraries/serial/library/linux64/librxtxSerial.so
rm processing-1.5.1/modes/java/libraries/serial/library/RXTXcomm.jar
ln -s /usr/share/arduino/lib/RXTXcomm.jar processing-1.5.1/modes/java/libraries/serial/library/

Run processing

cd processing-1.5.1

Running the processing command should result in a GUI application launching that looks a lot like the Arduino idea.  Download and open the below code in processing and click play.

 * Oscilloscope
 * Gives a visual rendering of analog pin 0 in realtime.
 * This project is part of Accrochages
 * See http://accrochages.drone.ws
 * (c) 2008 Sofian Audry (info@sofianaudry.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
import processing.serial.*;

Serial port;  // Create object from Serial class
int val;      // Data received from the serial port
int[] values;
float zoom;

void setup() 
  size(1280, 480);
  // Open the port that the board is connected to and use the same speed (9600 bps)
  port = new Serial(this, Serial.list()[0], 9600);
  values = new int[width];
  zoom = 1.0f;

int getY(int val) {
  return (int)(height - val / 1023.0f * (height - 1));

int getValue() {
  int value = -1;
  while (port.available() >= 3) {
    if (port.read() == 0xff) {
      value = (port.read() << 8) | (port.read());
  return value;

void pushValue(int value) {
  for (int i=0; i<width-1; i++)
    values[i] = values[i+1];
  values[width-1] = value;

void drawLines() {
  int displayWidth = (int) (width / zoom);
  int k = values.length - displayWidth;
  int x0 = 0;
  int y0 = getY(values[k]);
  for (int i=1; i<displayWidth; i++) {
    int x1 = (int) (i * (width-1) / (displayWidth-1));
    int y1 = getY(values[k]);
    line(x0, y0, x1, y1);
    x0 = x1;
    y0 = y1;

void drawGrid() {
  stroke(255, 0, 0);
  line(0, height/2, width, height/2);

void keyReleased() {
  switch (key) {
    case '+':
      zoom *= 2.0f;
      if ( (int) (width / zoom) <= 1 )
        zoom /= 2.0f;
    case '-':
      zoom /= 2.0f;
      if (zoom < 1.0f)
        zoom *= 2.0f;

void draw()
  val = getValue();
  if (val != -1) {

Arduino Code

Arduinoscope has a simple arduino component to poll and forward analog 0 to the desktop via the serial connection.  Save the below code and flash it to your Arduino.

#define ANALOG_IN 0

void setup() {

void loop() {
  int val = analogRead(ANALOG_IN);                                              
  Serial.write( 0xff );                                                         
  Serial.write( (val >> 8) & 0xff );                                            
  Serial.write( val & 0xff );


Verifying the Oscilloscope

To test the oscilloscope we will generate data using the Arduino and feed it in to the analog A0 port to be viewed on our Desktop.  Flash the code below to your Arduino.

// The Arduino code.                                                            
#define ANALOG_IN 0                                                             
int outPin=13;                                                                  
int outPinState = LOW;                                                          
int count = 1;                                                                  
int every = 10000;                                                              
void setup() {                                                                  
void loop() {                                                                   
  int val = analogRead(ANALOG_IN);                                              
  Serial.write( 0xff );                                                         
  Serial.write( (val >> 8) & 0xff );                                            
  Serial.write( val & 0xff );                                                   
  /* Generate signal to test oscilloscope */                                    
  if ((count % every) == 0) {                                                   
    if (outPinState == LOW) {                                                   
      outPinState = HIGH;                                                       
    } else {                                                                    
      outPinState = LOW;                                                        
    digitalWrite(outPin, outPinState);                                          
    count = 0;                                                                  

Connect pin digital pin 13 on the Arduino to analog pin A0.  The above code will turn on and off the digital pin to produce a square wave.


  • You can alter the baud rate from 9600 to 115200 in the arduino code as well as the processing code.
  • Plus sign zooms in (shift and =) while – zooms out (just -, no shift)
  • PWM at a normal 50 HZ is easily observable
  • Raspberry Pi pin 18 can generate PWM and the arduino can be used to test it.
  • An idle capture looks like:

Arduino Physical CPU Gauges


Use Arduino and two hobby servos to control physical servo gauges for cpu activity, memory usage, bandwidth, and more. The script uses the python psutil and pyserial modules. The psutil module provides an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) providing service similar to command line tools such as ps, top, iostat, and netstat. The servo control portion of the project is based on Arduino-Python 4-Axis Servo Controlby Brian Wendt, and the Arduino sketch is essentially unmodified from the SerialServoControl Sketch on Sparkfun.


Connect the red, power lines of the servos to +5v, the black ground lines to GND, and the yellow signal lines to the desired output pins, 5 and 6 in the example (others can be used, but must be PWM capable

You can download my cheesy gauge overlay from here:


Print it out, cut out the gauges, and poke a hole in the lower center of the gauge.  Remove the servo horn, slide the shaft through the hole in the gauge printout, and reconnect the servo horn on top of it.



The first step is to install the python psutil and pyserial modules. The easiest way to install it is using the python pip package manager. If you don’t have it installed already, you can install it using apt-get:

sudo apt-get install python-pip

Then install the psutil and pyserial modules:

sudo pip install psutil pyserial

Next, flash the sketch to the Arduino board. You can download it or copy and paste into the Arduino IDE.


Then download or copy and paste the Python script:


That’s it! To run the script:

python  cpu_serial_servo.py


Note:If you receive this error:

raise SerialException(“could not open port %s: %s” % (self._port, msg)) serial.serialutil.SerialException: could not open port /dev/ttyUSB0: [Errno 13] Permission denied: ‘/dev/ttyUSB0′

The problem is the default permissions of the /dev/ttyUSB0 (or /dev/ttyACM0) device. This can be fixed by running the command:

sudo chmod 777 /dev/ttyUSB0


Arduino USB HID Keyboard


Turn your Arduino UNO into a USB HID keyboard, and make buttons that do whatever you want. Make it a useful tool, with new buttons for Cut/Copy/Paste or Volume+/Volume-/Mute, or annoy your friends and colleagues by setting the keyboard to perform random keypress after random delays!

The USB HID keyboard conforms to the standard USB specification, so is functional on all modern operating systems.  All this is made possible by the use of the Arduino Device Firmware Update (DFU) function.

Arduino Device Firmware Update (DFU)

The Atmega8U2 chip on the Arduino UNO can be programmed directly using the special USB protocol called Device Firmware Update (DFU). This is completely independant of the ‘normal’ method of flashing sketches to the board using the Arduino IDE.

This process is normally used to update the firmware to a more recent version, as explained in the offical Arduino guide, Updating the Atmega8U2 on an Uno or Mega2560 using DFU. Note: If your board is NOT an Arduino UNO SMD you’ll need to solder a 10k resistor (Brown-black-orange) at the back of your board as shown on the Arduino site.

However, in addition to the ability to flash standard USB Serial firmwares, we can also flash alternative firmwares as well. This allows the device to be recognized as many other device types, including keyboard, mouse, joystick, midi device, etc. This is made possible in part to the wonderful open source LUFA (Lightweight USB Framework for AVRs)  USB stack, and keyboard HID firmware from Darran.

In this demonstration, we will flash generic USB HID keyboard firmware. The USB HID protocol provides manufactures the generic specifications to interact with nearly every operating system in existence. For more info, check out the USB HID Spec sheet.

Before you start, install the required packages. On Ubuntu and Debain systems, in a terminal run:

sudo apt-get install dfu-programmer dfu-util

For Windows and Mac instructions to install the dfu-programmer tool, consult the official Arduino DFU documentation.

Then download these two firmware files:


The first step is to make sure you are able to flash the standard arduino firmware. This will confirm that the programmer and the environment are both functional. NOTE: There is no chance of ‘bricking’ the device using this method. The Arduino bootloader firmware can always be updated using the DFU protocol!

sudo dfu-programmer at90usb82 erase
sudo dfu-programmer at90usb82 flash --debug 1 Arduino-usbserial.hex
sudo dfu-programmer at90usb82 reset

Plug cycle the Arduino, then open the Arduino IDE and ensure that you can still upload a sketch. Assuming everything flashes normally, we can move forward with flashing the HID keyboard firmware.

sudo dfu-programmer at90usb82 erase
sudo dfu-programmer at90usb82 flash --debug 1 Arduino-keyboard-0.3.hex
sudo dfu-programmer at90usb82 reset

NOTE: The Arduino can only be flashed with skectches through the Adruino IDE if the Arduino-usbserial.hex bootloader is active. So, to develop a USB HID device, the process becomes:

Flash Arduino-usbserial.hex bootloader with dfu-programmer (erase/flash/reset)
Plug cycle the Arduino
Flash firmware sketch using Arduino IDE
Plug cycle the Arduino
Flash Arduino-keyboard-0.3.hex bootloader with dfu-programmer (erase/flash/reset)
Test and repeat

Now that you understand how the process works, you can try out some of these keyboard samples. The easiest example is the random keypress with random delays, since it doesn’t require any components connected to the Arduino.

Random Key/Random Delay

The following two examples both use three buttons connected to the Arduino. The code can easily be changed to make the buttons perform other actions, by consulting the mapping tables in the USB HID documentation.  Here is a diagram of the circuit, (created with Fritzing):





Arduino on Raspberry Pi


Connecting an Arduino to a Raspberry Pi is simple. In a terminal, install the Arduino IDE:

sudo apt-get install arduino

This will take a while to download and install all of the dependencies. Once completed, you can start the IDE from the terminal:


Or, from the LXDE menu, Electronics->Arduino IDE. Note: This is IDE version 0018, and does not seem to recognize boards newer then the Duemilanove. Update: The IDE version in the package manager has been updated to version 1.01 and should work with newer boards like the Uno and Leonardo now as well.

The 1 amp power supply I have connected to my Raspberry Pi was not sufficient to power both the Pi and the Arduino through the USB port, so I connected the Arduino through a powered external USB hub. This may not be necessary with a larger power supply connected to the Pi. Update: A larger power supply will not overcome this limitation; the micro USB port on the Raspberry Pi is fused with 1100mA. –Thanks cavebeat


Alternatively, the 5V GPIO R_Pi Pin can be used to power the Arduino. Just connect the 5V GPIO pin on the Raspberry Pi to the VIN pin on the Arduino, and respectively GND from one board to the other.


This eliminates the need for the externally powered USB hub, but can make development more of a chore due to the USB port restriction: the keyboard and Arduino will need to be swapped in and out to flash the Arduino.

Android + Arduino + USB Host + Temperature + Light


Sensing temperature and light with Android and Arduino.  This article will demonstrate a basic thermometer / ambient light level detection input accessory.

For additional background information on interfacing Android with the real world, check out my other introductory tutorials:

Simple Digital Input
Simple Digital Output
Simple Analog Input
Simple Analog Output



Parts needed:

  • Android Device (1.6+)
  • Photocell
  • 10K ohm resistor
  • TMP36 temperature sensor
  • Hook-up wire
  • Android ADK Board*
  • – OR –
  • Arduino compatible and USB Host shield

*Supported boards include:

Google ADK boardFreeduino ADK board Seeed Studio ADK board, and DIY Drones ADK board



Connect one of the photocell leads to 5v and the other to analog input pin A0. Also connect the same lead through a 10K resistor to ground.  In hardware, this concept is known as a voltage divider.  Then connect the ground and power leads of the TMP36 to, you guessed it, ground and 5V.  Finally, connect the signal lead of the TMP36 to analog input pin A1. Here is a diagram of the completed circuit (created with Fritzing):



Arduino Firmware

Next, upload the Arduino sketch to the microcontroller. The sketch uses the Microbridge implementation by Niels Brouwers. Microbridge uses Android Debug Bridge (ABD) forwarding over TCP, rather than the Google Android ADK. You can checkout the source for the Arduino sketch from Github, or just copy and paste the following into the Arduino IDE.

Android App

The next step is to install the Android Demo application onto the device. You can either download the pre-built .apk or checkout the source from Github:

git clone git://github.com/mitchtech/android_adb_temp_light.git

Finally upload the app to the device (or browse to this page on the device and download the apk above).  Connect the Android device to the USB Host board/shield, and start up the app.