Let us RAP…

Raspberry pi controls Arduino using Python (RAP)

The Raspberry Pi is sometimes seen as competition to micro controllers like the Arduino. However the Raspberry Pi has a different sweet spot and can easily be combined with an Arduino to accomplish a wider range of tasks than otherwise possible. For example the missing Analog inputs.


Setting up your Arduino for Firmata

Firmata control of the Arduino requires loading an Arduino with the special Firmata sketch. You can download the Arduino software from the Arduino website. After opening the Arduino IDE, follow these steps to install Firmata on your Arduino:
1. Click File->Examples->Firmata->StandardFirmata
2. From the Tools->Board menu, select the type of Arduino you are using.
3. From the Tools->Serial Port menu, choose the USB port to which your Arduino is connected.
4. Click the upload button (it looks like a right arrow, just next to the checkmark) and wait for your sketch to upload. A message in the bottom black window will indicate success or failure
5. Once the Firmata sketch is loaded on your Arduino, you can test it out with the Firmata Test Program. (http://www.firmata.org/wiki/Main_Page)

Controlling your Arduino from Python

Next, your Raspberry Pi must be setup with the python firmata libraries. Run the following commands:

sudo apt-get install python-pip python-serial
sudo pip install pyfirmata

Use a USB cable to connect the Arduino with the Raspberry Pi (remember to use the big USB Standard A connector and not the smaller Micro B power connector). You can now find the USB name of the Arduino by running ‘ls -lrt /dev/tty*’. On my Raspberry Pi, it was listed as /dev/ttyUSB0. Remember this value for later.
Connecting to an Arduino
To control an Arduino from a Python script on your Raspberry Pi, you must first import the Arduino and util classes from the pyfirmata module. Then, create an object using the USB address you found in the previous step

>>> from pyfirmata import Arduino, util
>>> board = Arduino('/dev/ttyUSB0')

Controlling Arduino GPIO
The Arduino’s digital input and output ports can be controlled using the board.digital[] list. Calling write() can set the pin values high or low (1 and 0 respectively). The read() method returns the current value of the pin.

>>> board.digital[2].write(1)
>>> print board.digital[2].read()

If you’d like to use a pin repeatedly, its cumbersome to keep referring to it as board.digital[2]. Instead, you can get a reference to a pin with the board.get_pin() function. To this function, you pass a string of the format “[a|d]:[pin#]:[i:o:p:s]”. It is split by colons into three sections. The first section determines if the pin will be used in analog or digital mode. The second section is the number of the pin you would like to use. The third section selects the pin mode between input, output, pwm, and servo. The returned pin can be assigned to a variable and then later used to call read() and write() methods.

>>> pin2 = board.getpin('d:2:o')
>>> pin2.write(1)

Controlling Analog Pins
To read the value on an analog pin, you have to first turn on the analog value reporting on that pin. However, this continuously sends the analog value from the Arduino to the Raspberry Pi. If not continuously read, this will clog up the serial connection and prevent the rest of your script from running properly. To read the values, it is helpful to use an iterator thread.

>>> it = util.Iterator(board)
>>> it.start()
>>> board.analog[0].enable_reporting()
>>> board.analog[0].read()
>>> it.start()

To turn off the reporting of analog values, call disable_reporting() on the pin object

Sample code

Read LM35 temperature  from AI0 pin and store in CSV

# Python27
import csv
import pyfirmata
import time
from time import sleep

port = '/dev/cu.usbmodemfa1331' #'COM3' for Windows
board = pyfirmata.Arduino(port)
#pin =[0]
it = pyfirmata.util.Iterator(board)
a0 = board.get_pin('a:0:i')
with open('SensorDataStore.csv', 'w') as f:
    w = csv.writer(f)
    i = 0
    while i < 25:
        Temperature = a0.read()
        if (Temperature != None):
            Temperature = Temperature*100 # to read value in decimal
        i += 1
        row = [i, Temperature]
        print (Temperature)
    print ("Done. CSV file is ready!")


Raspberry pi for Windows users

Being a Windows user and fan of Raspberry pi and Linux, for me it was difficult to understand the guides from Linux experts.

After reading lot of blogs and tutorials, I have some tools and guides which is useful for Windows users to work on Raspberry pi.


I have downloaded from the raspberrypi website following linux image:

Link: https://www.raspberrypi.org/downloads/raspbian/

For new users I recommend to use Raspbian wheezy

Now being a windows user, I downloaded the application:


Link:  http://sourceforge.net/projects/win32diskimager/

This application is useful for putting the linux image into SD card. I have got a 4GB SD memory card. After running the Exe file, I have selected the linux image and then click on Write. It will take few minutes and after completion the SD card is ready to use with Raspberry Pi board.


I managed to get a 24” LCD screen with HDMI port, keyboard and a mouse. Also connected the Ethernet LAN cable from my company network.

After booting a PopUp screen came up and asked the configuration and booting option.

I have selected the SSH which I came to know that useful for remote connection and enable the Desktop GUI as boot option. After that It asked for a restart.

After restart the board was road with Desktop. I tried to open the browser to try the internet connection and it is working fine.

I have not done anything on the Ethernet configuartion yet. So I guess by default It takes the DHCP option for IP configuration.

Then next step is to use my windows laptop and run the Raspberry pi with remote connection.

I got a good site who helped me to the work pretty easily.

As a bit of background, I’m using the latest Debian image (19/04/2012) and I’m connecting from my Windows 7 laptop.  To connect I’ve installed UltraVNC on my laptop – you can download a free copy from here:
UltraVNC Downloads Page
Now, once  the VNC server is up and running on the Pi you can VNC from your laptop into your Pi without doing anything on the Pi first.  If you’ve just turned it on however, you’ll need to first start the VNC server on the Pi.  And if you’re using this as a truly headless box, that can be a little difficult.  To get around this I’ve used the PuTTY SSH client, which you can download here:
PuTTY Downloads Page
The last thing you need to know is the IP Address.  If you’ve configured your Pi with a static IP Address, that’s great.  If you have access to your router to look this up that’s fine too.  You might however be in a situation where you have no way to look up the IP Address (like me) – for this I needed a utility to scan the network for all machines.  For this I used:
Advanced IP Scanner
This will scan your network listing all devices it can find.  Simply look through the list of devices and find your Rashberry Pi. It’ll have a fairly obvious name, like “RaspberryPi”.
Alternatively, if you have access to your wireless router, you might be able to connect to this and see a list of all devices that have connected to it, including your Raspberry Pi.  As each wireless router differs, I’ll leave this up to you to figure out 🙂


This is useful software for sharing files between your windows laptop and Raspberry pi via ssh. I recommend to integrate putty to avoid multiple configuration.

Select the connection type as SSH enter the IP address and username with password

Now you can see in the left side my computer files and in right the raspberry pi contents. Use drag and drop for file transfer.



Now let us configure putty as shown in below image.


Simply type in Raspberry Pi IP Address in the Host Name field that you found earlier and click open.  Once Putty has connected to the SSH process running on the Pi, a terminal window will pop up and you’ll be prompted with a login.


I still have my UN & PW set to pi and raspberry, so just typed that in.  Once logged in I’m taken to the standard terminal prompt.  From here you can run pretty much any command you want on the Raspberry Pi.


Setting up VNC Server via SSH
Now that you’re connected, you need to start the VNC server.  If this is the first time you’re doing this, you’ll also need to install VNC first.  I’ve assumed you’ll have internet access as this will be required to install this.  To do this, run the following command:
sudo apt-get install tightvncserver
As mentioned above, the Putty SSH Client lets you run commands on your Pi directly, so by doing this you’re installing a VNC application on your Pi.
NOTE: during the install you’ll be prompted to install without verification – type y here.


Once installed, you’ll need to start the VNC server.  The command I’ve used here is vncserver :1 -geometry 1366×768 -depth 16 -pixelformat rgb565:


This will start the VNC server process on the Pi.  What this means is that it will start a virtual X session (a virtual instance of the Raspberry Pi GUI) on your Pi, in a very similar way to when you run startx when your Pi is connected to a display.  When you VNC into your Pi you will be connecting to this X session.
So – the important port of this command is :1.  This defines the port that the VNC process will be started on – you can make this whatever you want, but will need to remember it to ensure you connect to the right port.  You’ll see more details on this below.  As for the resolution (-geometry) this will be the resolution that the X session will run under – you can make this pretty much whatever you want
The first time you launch VNCServer you’ll be prompted for a password – you’ll need this to connect in using VNC.


You’ll also be asked for a view-only password (optional).  When providing the password via VNC the remote use will only have read-only access to the Raspberry Pi:


Connecting via UltraVNC
Once VNC server has been started the only thing left to do is connect.  Start up UltraVNC, type in the IP Address (or machine name) with a port of 1 and connect.
NOTE:  This port is the port you used when starting the VNC process above:


And that’s it – connected!



Start VNC automatically

So a couple of you have been asking about getting VNC to start automatically (me included).  So – I’m assuming that you have VNC up and running, working if you start it manually after each boot.  If not, take a look below.
Create startup file
The first thing you need to do is create the file that will actually start VNC on startup.  I’m doing this via Putty (instructions here), but you can just as easily use Terminal directly from the Pi.
Type the following:
sudo nano /etc/init.d/tightvncserver


NOTE: nano is a lightweight editor – the command above will create a new file called tightvncserver in the /etc/init.d directory and open it for editing, presenting the following screen (note the [ New File ] entry at the bottom, indicating a new file):


Once you have the file open, paste in the following:
# First configure the user you want to run this under – this will generally be pi, unless you’ve created your own users
export USER=’pi’
eval cd ~$USER

# Check the state of the command – this’ll either be start or stop

case “$1” in
    # if it’s start, then start vncserver using the details below
    su $USER -c ‘/usr/bin/vncserver :1 -geometry 1280×800 -depth 16 -pixelformat rgb565’
    echo “Starting vncserver for $USER “
    # if it’s stop, then just kill the process
    pkill Xtightvnc
    echo “vncserver stopped”
    echo “Usage: /etc/init.d/vncserver {start|stop}”
    exit 1
exit 0

NOTE: In the file I’ve specified my own resolution with the text -geometry 1280×800 – you can leave this out of you want
This will be what your screen now looks like.


To exit, press Ctrl+X.  You’ll be prompted to save – just type Y:


You’ll be prompted to confirm the filename – just press Enter:


Set file properties
Once that’s done make sure the file has the right propertied by typing the following:
sudo chmod 755 /etc/init.d/tightvncserver
NOTE: Important to do this step every time you modify this file.  I redid these steps to create the tutorial, skipped this step and couldn’t VNC in on the reboot!
Add File to startup sequence
And now just add your file to the list of startup actions by typing the following:
sudo update-rc.d tightvncserver defaults
And that should be it!  Just restart, and you should be able to VNC straight in!