LED reference chart.

Raspberry-Pi-GPIO-Layout-Revision-2

Below is a quick reference to where the LED`s and photocell need to be plugged into . If you need any help in wiring up LED`s to the Pi the please have a look at Gordons Projects. A quick search on ebay and should find all the components you`ll need. I used a breadboard with a breakout connector so the Pi can be quickly plugged / unplugged . A little note for the wiring the long leg goes to the Pi pin the other to ground. The LED`s I choose are low power so adding a resistor to them left them very dim.

Led name Colour Referance name GPIO pin Gpio name
Reverse 1 White BLED1 8 GPIO14
Reverse 2 White BLED2 10 GPIO15
Indicator Right 1 Yellow SRLED1 3 GPIO2
Indicator Right 2 Yellow SRLED2 5 GPIO3
Indicator Left 1 Yellow SLLED1 19 GPIO10
Indicator Left 2 Yellow SLLED2 21 GPIO9
Break 1 Red Brake1 16 GPIO23
Break 2 Red Brake2 18 GPIO24
Head Light 1 White HLED1 22 GPIO25
HeadlLight 2 White HLED2 24 GPIO8
Photcell Sensor 26 GPIO7
  

Moving the car and having some fun with the lights.

2013-10-05 14.50.35Moving the car and having fun with the lights. 

The first part of the code is just setting up the GPIO and referencing the pins to make life a bit easier. After that we created a couple of function . Function allowed us to add features as we went along.

Function names and what they do. 

all_off  – This function sets all pins except the brake lights. This gives the effect of the parking lights being on when the car is at a stop.

cleanup – Just a standard GPIO cleanup.

BlinkRight / BlinkLeft- Uses a for loop to flash the yellow LED giving the impression of car indicators. It takes 2 variables which are set by the function fleft and fright . In my version it is set to blink 6 times . 1 blink every 0.5 seconds.

forward – Moves the car forward for 1 seconds . The time can be change by setting the value in the sleep function on line 88 . So sleep(5.0) would be forward for 5 seconds. This functions also turns the parking lights off.

backwards – It is the same as forwards but we go backwards. The time can be changed by changing line 98 . This function also turns off the parking lights and turns on the reverse lights too.

fright / fleft – This function moves the car forward and turns the steering in which ever direction you have chosen. It is one the most complex functions for this project. In it we have the car going forward , turn left/right , turn the parking led`s off and calling the BlinkRight / BlinkLeft function aswell.

allLights – this function was designed as a bit of a diagnoses tool but I kept it as it was fun.It flashes all the LED`s on and off 20 times.

The running code.

From line 147 we have the code the allows us to use the functions. First we do create a couple of variables.

Intro – Is just a quick message welcoming to the program and setting out the keys you can use and what they do.

running – This is a Boolean . It is set to True and allows the while loop on line 165 to run.

Now the fun bit 20 lines of code and endless amounts of fun.

First we Print the Intro variable and our while loop starts up because running == True . It sets the parking brakes to on and the car is ready. key is a raw input that asks the user which direction they want to go. I have used an if statement however a switch would work just as well and would have the benefit of being expand more easily than an if statement.

The options we have are :-

  • f    –    calls the forward function.
  • b   –    calls the backwards function.
  • fr  –    calls the fright function.
  • fl   –    calls the fleft function.
  • l    –    calls the allLights function . The time of flashes and frequency can be set here also. We have set to 20 times and the frequency every 0.5 second.
  • q    –   changes the Boolean value to False and kills the while loop.

After that a nice message is printed and GPIO.cleanup does it`s job.

#!/usr/bin/env python
# Pi car python code by julian and kyle milligan
# version 1.0 beta
""" Must be run as root - sudo python car.py """

import time, datetime, RPi.GPIO as GPIO , os

#referance name and gpio pin number
FORWARD = 11
BACK = 12
LEFT = 13
RIGHT = 15
BLED1 = 8
BLED2 = 10
SRLED1 = 3
SRLED2 = 5
SLLED1 = 19
SLLED2 = 21
BRAKE1 = 16
BRAKE2 = 18
HLED1  = 22
HLED2  = 24

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
#Remember to setup the GPIO pin as input or output
GPIO.setup(FORWARD, GPIO.OUT)
GPIO.setup(BACK, GPIO.OUT)
GPIO.setup(LEFT, GPIO.OUT)
GPIO.setup(RIGHT, GPIO.OUT)
GPIO.setup(BLED1, GPIO.OUT)
GPIO.setup(BLED2, GPIO.OUT)
GPIO.setup(SRLED1, GPIO.OUT)
GPIO.setup(SRLED2, GPIO.OUT)
GPIO.setup(SLLED1, GPIO.OUT)
GPIO.setup(SLLED2, GPIO.OUT)
GPIO.setup(BRAKE1, GPIO.OUT)
GPIO.setup(BRAKE2, GPIO.OUT)
GPIO.setup(HLED1, GPIO.OUT)
GPIO.setup(HLED2, GPIO.OUT)

GPIO.setwarnings(False)
#functions

def all_off(): #turns all of the pins off - always call at the end to save battery
    GPIO.output(FORWARD,0)
    GPIO.output(BACK,0)
    GPIO.output(LEFT,0)
    GPIO.output(RIGHT,0)
    GPIO.output (BLED1,0)
    GPIO.output (BLED2,0)
    GPIO.output(SRLED1,0)
    GPIO.output(SRLED2,0)
    GPIO.output(BRAKE1,1)
    GPIO.output(BRAKE2,1)

def cleanup(): #cleans up the GPIO pins
    GPIO.cleanup()

def sleep(sleepTime=1):
    time.sleep(sleepTime)

def BlinkRight(numTimes,speed):
    for i in range(0,numTimes):## Run loop numTimes
        GPIO.output(SRLED1,1)
        GPIO.output(SRLED2,1)
        time.sleep(speed)
        GPIO.output(SRLED1,0)
        GPIO.output(SRLED2,0)
        time.sleep(speed)
    all_off()

def BlinkLeft(numTimes,speed):
    for i in range(0,numTimes):## Run loop numTimes
        GPIO.output(SLLED1,1)
        GPIO.output(SLLED2,1)
        time.sleep(speed)
        GPIO.output(SLLED1,0)
        GPIO.output(SLLED2,0)
        time.sleep(speed)
    all_off()

def forward():
    print("Going forward")
    GPIO.output(BRAKE1,0)
    GPIO.output(BRAKE2,0)
    GPIO.output(FORWARD,1)
    sleep(1.0)
    all_off()

def backwards():
    print ("Going backwards")
    GPIO.output(BRAKE1,0)
    GPIO.output(BRAKE2,0)
    GPIO.output (BACK,1)
    GPIO.output (BLED1,1)
    GPIO.output (BLED2,1)
    sleep(1.0)
    all_off()

def fright():
    print ("Going forward and turning right")
    GPIO.output(BRAKE1,0)
    GPIO.output(BRAKE2,0)
    GPIO.output(FORWARD,1)
    GPIO.output(RIGHT,1)
    BlinkRight(6,0.5)
    sleep(2.0)
    all_off()

def fleft():
    print ("Going forward and turning left")
    GPIO.output(BRAKE1,0)
    GPIO.output(BRAKE2,0)
    GPIO.output(FORWARD,1)
    GPIO.output(LEFT,1)
    BlinkLeft(6,0.5)
    sleep(2.0)
    all_off()

def allLights (numTimes,speed):
    for i in range(0,numTimes):## Run loop numTimes
        GPIO.output(SLLED1,1)
        GPIO.output(SLLED2,1)
        GPIO.output(SRLED1,1)
        GPIO.output(SRLED2,1)
        GPIO.output(BLED1,1)
        GPIO.output(BLED2,1)
        GPIO.output(BRAKE1,0)
        GPIO.output(BRAKE2,0)
        GPIO.output(HLED1,0)
        GPIO.output(HLED2,0)
        time.sleep(speed)
        GPIO.output(SLLED1,0)
        GPIO.output(SLLED2,0)
        GPIO.output(SRLED1,0)
        GPIO.output(SRLED2,0)
        GPIO.output(BLED1,0)
        GPIO.output(BLED2,0)
        GPIO.output(BRAKE1,1)
        GPIO.output(BRAKE2,1)
        GPIO.output(HLED1,1)
        GPIO.output(HLED2,1)
        time.sleep(speed)
    all_off()

#varibles

Intro = "Welcome to Julian and Kyle`s Pi Car program\n\
Please use the following commands to move the car\n\
f = forwards\n\
b = backwards\n\
fr = forwards and turn right\n\
fl = forwards and turn left\n\
br = backwards and turn right\n\
bl = backwards and turn left\n\
l = all ligths on\n\
q = quit\n\
\n\
enjoy."

running = (True)
print (Intro)

while (running == True):

    GPIO.output(BRAKE1,1)
    GPIO.output(BRAKE2,1)
    key = raw_input("which way - ")

    if (key == "f"):
         forward()
    elif (key =="b"):
         backwards()
    elif (key =="fr"):
         fright()
    elif (key =="fl"):
         fleft()
    elif (key =="l"):
         allLights(20,0.5)
    elif (key =="q"):
         running = (False)

print (" Hope you had fun ")
GPIO.cleanup()

  

Light activated headlights for the Pi-Car.

Code for the head lights.

photocell

#!/usr/bin/env python

# Example for RC timing reading for Raspberry Pi
# Must be used with GPIO 0.3.1a or later - earlier verions
# are not fast enough!

import RPi.GPIO as GPIO, time, os

#referance name and gpio pin number
HLED1  = 22
HLED2  = 24
sensor = 26

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
#Remember to setup the GPIO pin as input or output
GPIO.setup(HLED1, GPIO.OUT)
GPIO.setup(HLED2, GPIO.OUT)

DEBUG = 1
GPIO.setmode(GPIO.BOARD)

runningLights = (True)

def RCtime (RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)
        time.sleep(1.0)

        GPIO.setup(RCpin, GPIO.IN)
        # This takes about 1 millisecond per loop cycle
        while (GPIO.input(RCpin) == GPIO.LOW):
                reading += 1

        return reading

print ("Light program running!!!")
while (runningLights == True):
        lightSensor = RCtime(sensor)
        #print lightSensor

        if ( lightSensor > 400):
                GPIO.output(HLED1,1)
                GPIO.output(HLED2,1)
        elif ( lightSensor < 400):
                GPIO.output(HLED1,0)
                GPIO.output(HLED2,0)

GPIO.cleanup()

This code was adapted from the tutorial from Adafruit . The only change I have made is setting up the 2 LED`s (HLED1 and HLED2 ) and added an IF statement . The IF statement switch`s on the led`s if the light drops below 400 and of if it`s over 400. I got this figure by hours of experimentation by switching the bedroom light on and off. The print statement is there just so I know the program is running correctly. Hopefully in the future I will ingrate this code with the main code.

  

Temp recording and upload live to Google Doc`s

This project is a mismatch off a couple of project on-line at the moment . I will reference all the sites where I got the information from. In a nutshell this project takes the temperature from a DS18B20 sensor. This is a great piece of kit as it only needs 3 leads attached to it and 2 off those are 3.3v and ground. The resistor is used to pump up the voltage on the output pin to keep the Pi happy. Because the digital sensor is accessed by it serial number it means more sensors can be added and no extra resistors just extra cables. The idea of this project was to explorer putting live data on-line. In fact my 9 year son came up with an idea for this project. Dad he said ” we could put this in nanny`s house and keep an eye on her temp in the house and even link up some LED`s too” . So I can see this becoming a stand alone project. So have a read try it out and let`s get cooking.

Ingredients 

1. DS18B20 digital temperature sensor

2. 4.7k Resistor

3. Couple of jumper cables

4. Google Account

breadboard-ic

 

Follow the diagram to wire up the sensor and resistor. To test the sensors is working follow this guide from Adafruit`s site.

 

 

Pre heat

First you`ll need to create a blank spreadsheet on google drive. Rename it what you want I called mine Temperature_Log in cell A1 type Date/Time , B1 Temp In and C1 Temp Pi . you can call these what ever you like. Then delete all the other rows. If you do not your data will be entered right at the bottom.

Next we need to download a new python module called gspread . code from Daniel Hansen

wget https://pypi.python.org/packages/source/g/gspread/gspread-0.0.15.tar.gz
tar -zxvf gspread-0.0.15.tar.gz
cd gspread
sudo python setup.py install

Once this is done here is the code to make it all work.

#!/usr/bin/python3
#
import os, glob, time, gspread, sys, datetime # all normal imports and the gspread module
#
#Google account details
email = 'foobar@gmail.com'# your google email
password = 'foobar`s password'# your google password
spreadsheet = 'Temperature_Log' #the name of the spreadsheet already created
#
#attempt to log in to your google account
try:
gc = gspread.login(email,password)
except:
print('fail')
sys.exit()
#
#open the spreadsheet
worksheet = gc.open(spreadsheet).sheet1
#
#initiate the temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#
#set up the location of the sensor in the system
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
#
#
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
#
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c
#
# Return CPU temperature as a character string
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return res
#
while True: #infinite loop
tempin = read_temp() #get the temp sensor
temppi = getCPUtemperature() #get the pi temp
values = [datetime.datetime.now(), tempin , temppi]
worksheet.append_row(values) #write to the spreadsheet
print(values)
time.sleep(600) #wait 10 minutes

Hopefully if all this worked you should see the temp from the sensors , temp of the CPU and time and date in your SSH connection and live on your Google spread sheet.

gdriveputty

 

 

 

 

 

References.

Adafruits Tutorial on DS18B20 

Daniel Hansen Tutorial on DS18B20

  

Test DS18B20 sensor

  1. sudo modprobe w1-gpio
  2. sudo modprobe w1-therm
  3. cd /sys/bus/w1/devices
  4. ls
  5. cd 28-xxxx (change this to match what serial number pops up)
  6. cat w1_slave
modprobe.png

The interface is a little unreliable, but fortunately it tells us if there is a valid temperature to read. It’s like a file, so all we have to do is read

The response will either have YES or NO at the end of the first line. If it is yes, then the temperature will be at the end of the second line, in 1/000 degrees C. So, in the example above, the temperature is actually read as 20.687 and then 26.125 degrees C.

If you have more than one Sensor connected, you’ll see multiple 28-xxx files. Each one will have the unique serial number so you may want to plug one in at a time, look at what file is created, and label the sensor!

  

UltraSonic Sensors

Ebay Kit
The Sensor is powered by a +5v rail from pin 2 of the Pi. The trigger pin comes from pin 16 (Gpio23) and this tell the sensor to start measuring. The echo pin in normally low until the sensor sends an output then it goes +5v for the time the sensor took to measure the distance. This is the reason for the resistors as the GPIO can only handle a +3.3v.

Diagram

The Code

#!/usr/bin/python
# Import required Python libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
#
# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO = 24
#
print "Ultrasonic Measurement"
#
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
#
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
#
# Allow module to settle
time.sleep(0.5)
#
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
#
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
#
# Calculate pulse length
elapsed = stop-start
#
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
#
# That was the distance there and back so halve the value
distance = distance / 2
#
print "Distance : %.1f" % distance
#
# Reset GPIO settings
GPIO.cleanup()

  

Ultrasonic Rocket launcher

rl

rocket launcher diagramThis is the code and diagram to fire the big trak rockets using the ultra sonic sensor on the Pi. The aim is to have the the rocket pod attached to Big Trak with the sensor at the front.The code is simple it will ask for a distance i normally say 80 (8cm).It will then print out the measurements every second until there is one below 80 then it`s fires the rockets , takes a picture using the call function and switches the LED on. This code is a work in progress so if you see any way to improve it I would like to hear.

Diagram in PDF 

#!/usr/bin/python
#
#
# Author : Julian and Kyle Milligan
# Date : 09/01/2013
# Import required Python libraries
import time
import RPi.GPIO as GPIO
from subprocess import call
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO = 24
GPIO_FIRE = 4
#
print "Ultrasonic Measurement"
#
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
GPIO.setup(GPIO_FIRE,GPIO.OUT) # Fire
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# GPIO.output(GPIO_FIRE, False)
#
# Allow module to settle
time.sleep(0.5)
#
# set distance to trigger
setdistance = input('Please enter a value to trigger the camera:')#on screen prompt to fire
while True:
time.sleep(0.1)
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
s = start
quit =0
#
while quit ==0:
quit = GPIO.input(GPIO_ECHO)
start = time.time()
if start - s > 0.1:
quit = 1
#
if start - s < 0.1:
while GPIO.input(GPIO_ECHO) == 1:
stop = time.time()
#
elapsed = stop-start
#
distance = elapsed * 34300
distance = distance / 2
#
print "Distance : %.1f" % distance
#
if distance < setdistance:
call (["raspistill -o image.jpg"], shell=True) # take a picture with Pi Camera
print "Fire"
GPIO.output(GPIO_FIRE,True) ## Turn on GPIO pin 7 fire the rockets
#
# Reset GPIO settings
GPIO.cleanup()

  

Stream a web cam from the Pi

Ingredients

1. Raspberry Pi with network / internet connection.

2. Web Cam newer the better

 

Pre Heat ( software you need to download)

Log into the pi via SSH and run the command sudo apt-get install motion 

This is the only bit of extra software you need.

You do need to make some changes to the config files.

sudo nano /etc/motion/motion.conf
**change deamon off to deamon on
**change webcam_localhost on to off
**change control_localhost on to off

save the changes.

sudo nano /etc/default/motion
**change start_motion_daemon=no to yes

Cooking ( adding it all together )

Start the service by running  sudo service motion start

Find the IP address of your Pi.

On another machine or phone browse to the address of your PI and add :8081 to the end example 192.168.0.22:8081 .

This should show the live feed from your webcam.

Making it look good

On another machine open notepad and copy the text below in to it :-

<!DOCTYPE html>
<html>
<head>
<meta content=”text/html; charset=iso-8859-1″ http-equiv=”Content-Type”>
<title>WebCam Stream from Pi</title>
<style type=”text/css”>
<!–
#apDiv1 {
position: absolute;
width: 423px;
height: 278px;
z-index: 1;
left: 6px;
top: 33px;
}
body,td,th {
color: #000;
}
body {
background-color: #0CF;
}
–>
</style> </head>
<body>
<div id=”apDiv1″> <img style=”-webkit-user-select: none” src=”http://192.168.0.22:8081/”>
</div>
Live Stream from my Pi
</body>
</html>

 

Save it as webcam.html , then open it in a browser and again you should see the feed . The important bit is in apDiv1 this is the code that displays the stream . Make sure to change the IP address to your PI.

I found you can not have to streams open on the same machine so if the webpage does not load make sure you do not have any other streams open.

<?php echo “Hello World”; ?>

  

Time Lapse Code for the Raspberry.

2013-08-04 12.47.47

Ingredients 

1. Raspberry Pi with network / internet connection.

2. Camera

3. Something to support your camera .Lego works great .

2013-08-04 12.47.47

 

 

 

 

 

 

 

Pre Heat ( software you need to download)

Log into the pi via SSH and run the command sudo apt-get install memcoder 

This is the only bit of extra software you need it encodes all the pictures into a video at full HD.

Cooking ( adding it all together )

Create a folder called TL  ( mkdir TL ) and change directory into it ( cd TL )

To run the time lapse run the command

raspistill -o myimage_%04d.jpg -tl 30000 -t 43200000

Ok let`s break it down raspstill – o means take a picture with options

myimage is the file name and the _%04d increments by 1 each time a picture is takin .jpg is the file format.

-tl 30000 is the time between pictures . 30000 = 30 seconds.

-t 43200000 is the time for the project to run. 43200000 = 12 hours there 3600000 milli seconds in 1 hour.

Ok it should happily be taking pictures  just run ls -l to see all the pictures.

When it`s finished it run , run the command ls *.jpg > stills.txt this will create a text file form the mencoder software.

and finally run mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -o tlcam.avi -mf type=jpeg:fps=24 mf://@stills.txt

This will create the video file for you . I like doing on the PI however some people say it does run slow I don`t care it`s taking 12 hours to make whats and 30mins. Transfer the file or watch it on the Pi and hay presto you just cooked a Time Lapse.

One tip if your going to do a night shot then cover the led if your filming through a windows the reflection is a pain and could wreck the video.

<?php echo “Hello World”; ?>

 

  

1st Time Lapse

2 hour`s in 5 seconds time lapse.

Done with a Raspberry Pi and Pi Camera . It took 120 shots and compressed them into a 5 second video. No we are not being invaded by aliens it is the red light from the camera this will be covered in future ones.

I used the command – raspistill -o timelapse%04d.jpg -t 75000000 -tl 60000

and ls *.jpg > stills.txt to create the list. You`ll need to sudo apt-get install mencorder for the next bit.    mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -o tlcam.avi -mf type=jpeg:fps=24 mf://@stills.txt   .

This creates the video file.