Monday, November 11, 2013

Raspberry Pi meets Galileo - Controlling Galileo GPIO via Pi

I wanted to control my Galileo's GPIO remotely based on user input and since I had my Raspberry Pi lying around, I decided to put it to work. Using a Raspberry Pi to control an Arduino board has been documented before, so with a little bit of exploring, I narrowed it down to 2 methods:
  1. pyserial - Allows the Pi to  communicate serially via USB. Requires a sketch to be uploaded to the Galileo first. The Pi sends commands serially to control different actions on the Galileo
  2. pyfirmata - Similar to pyserial but doesn’t require a sketch to be pre-loaded. Has the ability to drive an Arduino directly.
I will talk about #1 here since I hit issues with #2 which I will try and address sometime later.
 
Example below uses a GUI to turn the LED on Galileo pin 13 on/off.
 
Step1:
Upload this sketch to the Galileo
 
/*
Turns an LED on/off based on serial input from the Pi
*/

// Pin 13 has an LED connected on most Arduino boards.

// give it a name:

int led = 13;


// the setup routine runs once when you press reset:

void setup() {              

// initialize the digital pin as an output.

pinMode(led, OUTPUT);    
Serial.begin(9600);

}

// the loop routine runs over and over again forever:

void loop() {

if (Serial.available())

  {
    char ch = Serial.read();
   if (ch == 'a') {  

             digitalWrite(led, HIGH);   // turn the LED on

               }
   if (ch == 'A') {  

             digitalWrite(led, LOW);   // turn the LED off

               }
   }
}
Step2:
Install serialpy on the Raspberry Pi

Download pyserial-2.6.tar.gz
Make a temp folder and move the downloaded file into it.
cd temp   #Change to the temp directory   
gunzip pyserial-2.6.tar.gz    #to unzip it
tar –xvf pyserial-2.6.tar    #to untar it
cd pyserial-2.6   #move into the new folder
sudo python setup.py install   #to install it
 
Step 3:
Python script to send serial commands to the Galileo
 
import socket
from Tkinter import *

UDP_IP = "192.168.1.92"
UDP_PORT = 5005


#print "UDP target IP:", UDP_IP
#print "UDP target port:", UDP_PORT


sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP


MSG_LEDON = "LED ON"
MSG_LEDOFF = "LED OFF"

root = Tk()

def on() :
   sock.sendto(MSG_LEDON, (UDP_IP, UDP_PORT))
   return
 
def off() :
  sock.sendto(MSG_LEDOFF, (UDP_IP, UDP_PORT))
  return

 
Button(text='LED ON', command=on).pack()
Button(text='LED OFF', command=off).pack()
 
root.mainloop()
Step4:
Run the python script on the Pi. You should see a GUI like this:
  

Clicking the on/off buttons should result in the desired output on the Galileo LED.
  
The delay over serial was not noticeable for this particular applications. Plan is to play around with some motor control next.
 

No comments:

Post a Comment