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.

arduino

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)
it.start()
a0 = board.get_pin('a:0:i')
#a0.enable_reporting()
with open('SensorDataStore.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(["Number","Temperature"])
    i = 0
    while i < 25:
        Temperature = a0.read()
        if (Temperature != None):
            Temperature = Temperature*100 # to read value in decimal
        sleep(1)
        i += 1
        row = [i, Temperature]
        w.writerow(row)
        print (Temperature)
    print ("Done. CSV file is ready!")
board.exit()

 

Remote Debug on Raspberry Pi by PyCharm

pycharm

Recently I’ve been getting into embedded Linux, particularly the Raspberry Pi and have consequently been learning Python. I really don’t like programming directly on these small devices since the environment is typically spare and slow.

What I really needed was something that I could work on in my main dev environment but deploy and execute on the RPi. It also needed to be able to run as root because all RPi GPIO requires root privileges.

Most importantly, PyCharm has a remote debugging feature which coupled with automatic deployment makes everything super easy.

Setting Up Remote Debugging

Below is how I set up my environment. Much of this is found in the PyCharm help documentation. You can find how to set up remote debugging particularly the section on setting up a remote interpreter via SSH.

Automatic Deployment

First we need to setup automatic deployment of our files to the RPi. This part isn’t strictly required but if you don’t do it you’ll have to manage uploading your changes.

  1. Important: The login you use here is the credentials that the remote process will be run as. You can use the “pi” user, as we have another way of gaining root privileges to access GPIO detailed below.

Run Configuration

Still with me? Now that we’ve got deployment set up and an interpreter that will use our remote virtual environment, the final step is to create a run configuration to actually run a script.

  1. Create a simple python script and call it hello_world.py. Give it the following contents.
    • import RPi.GPIO
    • print “hello world!”
  2. Click in the upper right of the main window and choose “Edit Configurations…”.
    rd3-01 Run Configuration
  3. Click the plus button and choose Python.
    rd3-02 Add Python Interpreter
  4. Give the new configuration the name “hello_world (remote)”. For the script, choose the script we just created. For Python interpreter, choose the remote interpreter we created in the last section.
    rd3-03 Run Configuration
  5. Now add a path mapping to map from your local project path to the remote path. This lets the interpreter find the source file for what’s executing remotely.
    rd3-04 Edit Path Mappings
    rd3-05 Run Configuration With Paths
  6. Save the new configuration and click the run button. You should see PyCharm connect and the hello world print on the debug console.
    rd3-06 Run Success

Running as Root

Rather than enabling logging in as root over SSH, there’s another approach that will work without opening that security hole. Using permissions, we can cause our python interpreter to simply run as root.

  1. Reconnect using PuTTY and navigate to the project root folder.
    cd /home/pi/remote_debug/remote_debug_ex
  2. Change ownership of the python interpreter to root and cause it to be executed as its owner whenever it’s run.
    • sudo chown -v root:root venv/bin/python
    • sudo chmod -v u+s venv/bin/python

This will cause pip to act a bit funny when you want to install anything later on so just reverse the above changes from step 2 as needed. Just use the same commands but with pi instead of root and with u-s.

I have a couple of scripts that I keep in the project root for just this purpose. You can use below:

python_as_pi.sh 

#!/usr/bin/env bash

DIR=$(dirname $(readlink -f "${BASH_SOURCE}"))

if [ ! -f $DIR/venv/bin/python ]; then
  echo "This script should be located in the project root directory"
  echo "and the virtual environment should be created."
else

    # Change python back to run as pi
    sudo chown -v pi:pi "$DIR/venv/bin/python"
    sudo chmod -v u-s "$DIR/venv/bin/python"

fi

python_as_root.sh

#!/usr/bin/env bash

DIR=$(dirname $(readlink -f "${BASH_SOURCE}"))

if [ ! -f $DIR/venv/bin/python ]; then
  echo "This script should be located in the project root directory"
  echo "and the virtual environment should be created."
else

    # Change python to run as root
    sudo chown -v root:root "$DIR/venv/bin/python"
    sudo chmod -v u+s "$DIR/venv/bin/python"

fi

Conclusion

Now you have a way to remote debug your RPi with the interpreter running as root, allowing access to the Pi’s GPIO. You can do this with multiple projects and even have multiple projects or instances of projects open and debugging remotely.

PyCharm is a great IDE and I encourage you to look into using it to improve your development environment. For example, check out Zeal and the Dash plugin that will cause PyCharm to perform a documentation lookup when you press Ctrl+Shift+D. There are also plugins to provide support for Markdown and bash scripts.

GPIO control using Python

GPIO

The RPi.GPIO Python library allows you to easily configure and read-write the input/output pins on the Pi’s GPIO header within a Python script. Thankfully this library is now including in the standard Raspbian image available from the Foundations Download Page.

If you are using a fresh image you don’t need to install it but I’ve kept the instructions here in case you ever want to try a manually installation.

Method 1 – Install from repository

If the package exists in the Raspbian repository is can be installed using apt-get. First you need to update the available package versions :

sudo apt-get update

Then attempt to install the RPi.GPIO package :

sudo apt-get install rpi.gpio

If it isn’t already installed it will be installed. If it is already installed it will be upgraded if a newer version is available.

Method 2 – Manual Installation

The package is available from http://pypi.python.org/pypi/RPi.GPIO and the current version is 0.5.11 (February 2015). If this version is updated you will need to make appropriate changes to the version number in the commands below.

Step 1 – Download the library

wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz

Step 2 – Extract the archive to a new folder

tar -xvf RPi.GPIO-0.5.11.tar.gz

Step 3 – Browse to the new directory

cd RPi.GPIO-0.5.11

Step 4 – Install the library

sudo python setup.py install

Step 5 – Remove the directory and archive file

cd ~
sudo rm -rf RPi.GPIO-0.*

This will now mean you can use the library within Python.

Example Usage

import RPi.GPIO as GPIO
 
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
 
# set up the GPIO channels - one input and one output
GPIO.setup(11, GPIO.IN)
GPIO.setup(12, GPIO.OUT)
 
# input from pin 11
input_value = GPIO.input(11)
 
# output to pin 12
GPIO.output(12, GPIO.HIGH)
 
# the same script as above but using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
GPIO.setup(18, GPIO.OUT)
input_value = GPIO.input(17)
GPIO.output(18, GPIO.HIGH)

Example to run script on key press

import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
#This will import the necessary libraries in the GPIO namespace and set the pin numbering to correspond to your breakout board.
#Now we need to set the pin as input, pin 18 is used in this example.
GPIO.setup(18,GPIO.IN)
#Reading the pin is now as easy as:
input = GPIO.input(18)
#If we want to print Button Pressed each time a button is pressed
while True:
 if (GPIO.input(18)):
 print("Button Pressed")
 time.sleep(1)
 os.system('startx')
 #os.system('reboot')
 #os.system('/etc/network/if-up.d/sayIP')
 else:
 print("Button Not pressed")
 time.sleep(1)
 # use 0.1 for 1 ms delay