Sunday, June 30, 2013

Taking LEDs to the next level: web controlled GPIO ports

***UPDATE: github repository of code: https://github.com/bugbiteme/ledctrl.blog

In my last post I covered the basics on how to get an LED to turn on with a very simple Python script.  From there I created an application that turns on an LED if an IP address is detected on the network.

What I really want to do is be able to create a web based interface that can be used to control the GPIO outputs over the network. Being that my knowledge of Python is limited, I decided to take a break from the pi and hone some Python skills via the excellent (and FREE!) course over at learnpythonthehardway.org. And now I am back!

The Author of Learn Python the Hard Way assumes you are a complete n00b, and walks you all the way up to the grand finally project of creating a web based Python application. Perfect! Just what I needed!

I started at chapter one and went all the way to the end. After learning just enough to be dangerous, I put together a little web based app that displays a button for the green LED, a button for blue LED and a button for the red LED. Once a user clicks one of the three buttons, the corresponding LED lights up on the bread board and its status along with the other two lights after each click. A user can open the application on their mobile device (iPhone in my case) and control the LEDs via the web browser.

Here is an example of how it works:

Using by mobile phone, point to running app's url (all lights off here):


Click the green button and the green LED is turned on, and the web application is updated to show that it is on:



Click the red button and the red LED is turned on, and the web application updates to show that it and the green LED are now on, and so on and so forth...


The code for making LEDs turn on and off is simple enough, but getting the web framework working was the main hurdle for me, along with getting the code to generate dynamic web content on the fly.

The framework I used was web.py. This  framework was chosen due to the fact that it was used in the tutorials mentioned above, and plus, if it was good enough for Aaron Swartz, it's good enough for me. As I get more experience I may play with other frameworks such as django, but web.py seems tiny and simple enough for the pi.

Following the setup process here for installing the needed packages and setting up the directory structure, then working my way up to the chapter on getting user data from a web form (yes, I read every chapter and did every exercise in each one). I was able to get this thing going.

After many trials and errors, I was able to create a web application called ledctrl which does just what I want it to do.

The main code for my apps is located in the ledctrl/bin directory. The file is called app.py, which does all of the work. I decided to start using more of an object oriented approach in my Python coding, since that is what I'm used to doing in other languages. After the code snipped, I'll explain what I was thinking when I wrote it:


First of all, let's look at the class I created called LightSwitch

  • LightSwitch is a class I defined which initializes the GPIO and the current LED color being passed to it in the __init__() function, since these don't need to be global operations.


  •  flip_switch() is a method in LightSwitch which flips the current LED opposite of what it is already set to. This is done by checking the current status:
    • led_status = GPIO.input(self.LED)
      • if light-status is GPIO.LOW, then the LED is off already, so flip it to on, otherwise flip it off. Simple.
  • get_light_statuses() is a method in LightSwitch which returns the current statuses of all three LEDs as a dictionary data structure. The values in this dictionary are needed for generating the correct buttons in the dynamically generated HTML.


All of these class methods are executed from the Index class, which instantiates a LightSwitch object.

Any time the Index class renders the HTML form in either GET or POST, it passes the dictionary of LED statuses to the HTML template.

I also put in a global DEBUG flag, to print stuff out while I'm testing my code. Very helpful, and you can leave all your print statements in the code and set the DEBUG flag to "False" when you are ready to "go-live" ;)

The HTML form which passes information back and forth between my main python code looks like this (sorry for the formatting due to the long lines of HTML code):



The HTML form gets the dictionary of light_statuses. If the dictionary is valid, it looks at each LED color in the dictionary, and if the status for the LED is off (0) or on (1) display the corresponding HTML code for that color. Maybe there is a better way to generate this code (I'm sure there is), but this is what I got to work!

And here it is in action:

Monday, June 17, 2013

More fun with the pi!


Getting the hang of this!

LEDs
Input buttons
Light sensors 
Serial to USB

All at the same time!

Tuesday, June 11, 2013

Getting LEDs to light up with Raspberry Pi's GPIO with Python

In order to get into some hardware related projects with the RASPI, I figured it would be a good idea to figure out how to do some very basic stuff with the GPIO.

The first project I think anyone does is make the LEDs light up. There are plenty of tutorials out there with bits of information scattered about, but I'll try to use my experiences to supply all the information (and references to information) here.

First of all, it is a good idea to know what each pin does on the Raspberry Pi GPIO and get your Pi all ready and set up to work with Python.


Here is a great tutorial via adafruit that gives you a quick and dirty overview the GPIO, steps to take and libraries to install in order to program it via Python.


Once you have that all set up, in order to make an LED light up programmatically, you need to have it wired properly between a resistor that is connected to one of the numbered GPIO pins (4, 8, 7, 17, 22, 23, 24 or 25),  and the ground pin (GND).

I wired my LEDs using the adafruit Pi Cobbler and a breadboard, but you could attach wires directly to the GPIO if so inclined.

Here is the example I followed for connecting LEDs to the Pi's GPIO.

And here is mine wired up to three LEDs:


In this example I have my LEDs wired up to GPIO ports:
  • GREEN_LED = 24
  • RED_LED = 23
  • BLUE_LED = 18
The resistors are the ones that came with my kit and are rated at 560 ohm 5%, and resistors rated between 330 ohm and 1000 ohm are fine.

Here is a handy resistor decoder I use now and then.

In the above picture, the black wire is contacted between the GND pin and the negative blue column on the bread board.

Here is a diagram (note the totally fake cobbler)



For the red LED, the resistor is connected to GPIO pin 23 and an unused row on the breadboard (row 18..chosen arbitrarily). The positive end of the LED (long wire) is also in row 18 and the negative end (short wire) is connected the the blue negative column where the ground wire is connected.

I did the same for the other two LEDs but with their respective GPIO ports. Green was further away from the GPIO pin, so I used the yellow and green jumper wires to make a similar circuit.

Once everything was connected, I wrote a simple Python program to cycle through the LEDs. Somehow it worked!

Here is the code, and then some 'splainin':

#!/usr/bin/env python

import RPi.GPIO as GPIO, time, os

SLEEP_TIME = 1

GPIO.setmode(GPIO.BCM)
GREEN_LED = 24
RED_LED = 23
BLUE_LED = 18

GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.setup(BLUE_LED, GPIO.OUT)

try:

    while True:
        print "Red Light"
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)
        GPIO.output(BLUE_LED, False)
        time.sleep(SLEEP_TIME)  
        
        print "Blue Light"
        GPIO.output(RED_LED, False)
        GPIO.output(BLUE_LED, True)
        GPIO.output(GREEN_LED, False)
        time.sleep(SLEEP_TIME)          
        
        print "Green Light"
        GPIO.output(BLUE_LED, False)
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
        time.sleep(SLEEP_TIME)
        
except KeyboardInterrupt:
      GPIO.cleanup()
        

Break it on down:

GREEN_LED = 24 

24 is the GPIO pin. I don't like to hard code values and plus it makes code more readable/maintainable when you do things this way.


GPIO.setup(GREEN_LED, GPIO.OUT)

Initialize the GPIO pin used for the green LED for output


GPIO.output(GREEN_LED, True)

Turn the LED on


GPIO.output(GREEN_LED, False)

Turn the LED off


GPIO.cleanup()

Uninitialize all the GPIO pins

And there you have it!

Here is a little Python code that pings an IP address. Once an IP address pings back, an LED is turned on. In this example, when one of three iPhones is detected on my home network, an associated LED will light up. The light will turn back off if the IP address becomes unreachable.

#!/usr/bin/env python

# This program will detect specific IP address on the network and 
# Enable an LED if it is detected 

import RPi.GPIO as GPIO, time, os
from subprocess import call


SLEEP_TIME = 1

host1 = "192.168.1.128" # my iPhone
host2 = "192.168.1.108" # wife's iphone
host3 = "192.168.1.186" # an iPad

GPIO.setmode(GPIO.BCM)
GREEN_LED = 24
RED_LED = 23
BLUE_LED = 18

GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)
GPIO.setup(BLUE_LED, GPIO.OUT)

def detect_IP(ip_add, color_led):
 ping_command = "ping -c 1 %s > /dev/null 2>&1" % ip_add
 
 if call(ping_command, shell=True) > 0:
  GPIO.output(color_led, False)
 else:
  GPIO.output(color_led, True)
 
try:

    while True:
        detect_IP(host1, GREEN_LED)
        detect_IP(host2, RED_LED)
        detect_IP(host3, BLUE_LED)
        time.sleep(SLEEP_TIME)  
        
except KeyboardInterrupt:
      GPIO.cleanup()
        

Your Pi is ready

My Raspi finally arrived yesterday (jeesh a little over a week to arrive from adafruit). My son and I instantly unpacked it.