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.

Ethernet JTAG Adapter with Raspberry Pi

jtagpi

 I recently wanted an ethernet JTAG adapter for a project I was working on. Unfortunately ethernet JTAG adapters can cost upwards of $300, and even then they can be specific to particular chipset and toolchains.

However, were already using OpenOCD with ST-LINK/V2 programmers to communicate with out hardware, and it turns out that it’s very easy to set up OpenOCD on the Raspberry Pi. You can then plug the programmer into the Pi, connect a debugger (gdb in our case) to the OpenOCD instance, and debug your firmware remotely!

The Raspberry Pi is also a very convenient platform for adding additional interfaces to your hardware. For our project, we have FTDI serial cables and some ADC’s connected to ours as well. This lets us flash and debug our hardware, communicate with it over serial (forwarded over a socket), and continuously monitor power consumption of key components on our board. And we can do it from anywhere with an internet connection. It’s basically magic.

1. Acquire a Pi

First you’ll need a Rapsberry Pi and an SD card with the Raspbian installed on it. You can get a Raspberry Model B Starter Kit from Newark. This comes with a power adapter and an SD card with Noobs (which can automatically install Raspbian for you) pre-installed and is probably the easiest way to get started.

2. Install a Recent Version of OpenOCD

There is a version of OpenOCD already in the package database for Raspbian, but it’s version 0.6.1, which was too old for our platform. Fortunately it’s quite easy to install the latest OpenOCD from scratch. There are pretty good instructions on how to do this at SourceForge. But specifically for the Pi you can just do the following:

From your Pi:

sudo apt-get update
sudo apt-get install libtool libusb-dev libusb-1.0 autoconf automake texinfo

And then:

git clone git://git.code.sf.net/p/openocd/code openocd-code
cd openocd-code/
./bootstrap
./configure

This should spit out a bunch of stuff and then if everything worked you should see this at the end:

OpenOCD configuration summary
--------------------------------------------------
MPSSE mode of FTDI based devices        yes (auto)
ST-Link JTAG Programmer                 yes (auto)
TI ICDI JTAG Programmer                 yes (auto)
Keil ULINK JTAG Programmer              yes (auto)
Altera USB-Blaster II Compatible        yes (auto)
Segger J-Link JTAG Programmer           yes (auto)
OSBDM (JTAG only) Programmer            yes (auto)
eStick/opendous JTAG Programmer         yes (auto)
Andes JTAG Programmer                   yes (auto)
Versaloon-Link JTAG Programmer          yes (auto)
USBProg JTAG Programmer                 yes (auto)
Raisonance RLink JTAG Programmer        yes (auto)
Olimex ARM-JTAG-EW Programmer           yes (auto)
CMSIS-DAP Compliant Debugger            no

Make sure support for the programmer you are using is enabled, and then type make. Once that finishes, type sudo make install.

Now OpenOCD should be installed and ready to go!

3. Run OpenOCD

Now you can run OpenOCD. For example, if you were using an F4 discovery board, you could so something like this:

sudo openocd -f board/stm32f4discovery.cfg

If it worked, you should see something like:

Info : stm32f4x.cpu: hardware has 6 breakpoints, 4 watchpoints

Which means your programmer is ready to go!

You can then use telnet ip_of_pi 4444 to connect to your OpenOCD session and run OpenOCD commands. You can also connect to it with gdb. The most convenient way is to create a .gdbinit file with something like:

target remote my_pi_ipaddress:3333
file my_firmware.elf
monitor reset halt
load
And then you can type gdb (or in my case arm-none-eabi-gdb), and my_firmware.elf is flashed onto the hardware and is ready for debugging!

Reference: 
https://spin.atomicobject.com/2014/04/01/ethernet-adapter-jtag/

Open OCD bin compiled:

http://www.embeddedhelper.de/blog/raspberry-pi-openocd-binary/

A few minor corrections:

1. Using “extended-remote” over “remote” is recommended as it enables “run” and “start” GDB commands;
2. There’s no need to do “reset halt” before “load” with any >= 0.8.0 OpenOCD version;
3. To avoid typing “file” you can start gdb passing the filename as the first argument.

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

 

Cherokee Web server on Raspberry Pi

022716_0841_CherokeeWeb1.png

Why to go for another web server, if there are lot of web servers we discussed and available in market. The simple answer to that question is, embedded light weight web server with IoT support.

In this topic, I am not going to say a again from scratch on how to use raspberry pi. If you are at really having a fresh Raspberry pi board and want to do this exercise.Please read my blog on “getting started with raspberry pi for Windows users”

Installation Guide

First of all if you are interested in installation of Cherokee web server, go the reference at the end of this document. Do remember to read the dependencies for installation of Cherokee. After installation of Cherokee the most important work is to provide the virtual path of file system.

How it works:

Basically after successful installation of server need to do a command

sudo Cherokee –admin –b

Keep the user name and password to enter on webpage.

During configuration Cherokee cannot able to write into default path. So reason is simple as pi user do not have the credential to access. So to avoid that type of issues two ways can be adapted, 1st option is preferable.

Option:1

Make all default paths with in Pi user, I have used the following path

/home/pi/New1

Option:2

Provide credential to Cherokee by login as root user.

/usr/local/etc/cherokee/

Now using putty, I typed the following command at terminal. Then for admin the OTP will be generated.

 pi@raspberrypi ~ $ sudo cherokee-admin -b

[01/06/2013 06:37:44.734] (warning) rrd_tools.c:121 – Could not find the

    rrdtool binary. | A custom rrdtool binary has not been defined, and the

    server could not find one in the $PATH.

 [01/06/2013 06:37:44.734] (warning) socket.c:479 – IPv6 support is disabled.

    Configuring for IPv4 support only. | The issue seems to be related to your system.

Cherokee Web Server 1.2.99 (Nov  4 2012): Listening on port ALL:9090, TLS

disabled, IPv6 enabled, using epoll, 4096 fds system limit, max. 2041

connections, caching I/O, single thread

 Login:

  User:              admin

  One-time Password: kgEF1C7KMv1fCYNS

 Web Interface:

  URL:               http://localhost:9090/

 The next step is open internet explorer, type the IP address along with port 9090.

If everything is OK, then the server will start and then the button will change to stop server.

After that I have copied all web support package of controller /home/pi/New1

Then using internet explorer, I have entered the IP address of device.

Note: Remember the default port for web server is 80

Then the web pages start loading without any issues as shown below. I have extended my test by using chrome, firefox and the things are quite normal.

I had the initial issue in firefox that the configuration file was not found. But using internet explorer, I could able to resolve that issue.

First I have used the following command:

cherokee-admin –b

The result is shown below.

Can you able to guess the issue? It is very simple only you need to run the cherokee admin as power user. That means the command should like this:

sudo cherokee-admin –b

Have more question? Write back to me or comment.

WiFi Audio/Video Raspberry Pi and Android

Play Wireless Audio using Raspberry Pi
This is quite easy by using VLC player.

Step:1 Download and install VLC player in your raspberry pi( I am using Raspbian OS)

First ensure you have the latest Raspbian by using following command

 sudo apt-get update 

Then install VLC
sudo apt-get vlc install
Run VLC player, go to view and select web in interface

In Linux it is not easy to get access
VLC in the latest versions uses a file called ‘.hosts’ to define which computers can access the VLC remote player. You need to open this file and edit it:
you will need to edit the hosts file:
the file is in /usr/share/vlc/lua/http/.hosts
To edit this file from the command line (making sure I have permission to save changes), I use

 cd /usr/share/vlc/lua/http/ 
sudo nano .hosts

 # Access-list for VLC HTTP interface 
# $Id$
#
# localhost
::1
127.0.0.1
# link-local addresses
#fe80::/64
# private addresses
fc00::/7
fec0::/10
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
169.254.0.0/16
#End


Then save the file.

Now this is the time to test the VLC player web interface is working or not.

Open the browser in Raspberry and type:
http://localhost:8080


If you see the above screen you are ready from Pi side.

Install VLCdirectpro from Android market and connect to the same network.

Open VLC Direct in your device

Open menu

Go to “Settings”

Click “Automatic Connection Wizard”

Click “Start”. VLC Direct will start scanning the network, looking for VLC.

That’s it! VLC Direct is now configured and ready to use!

Click “Automatic Connection Wizard”

 

For better Audio Quality refer to the following links to install Pulse Audio MPD: