Category Archives: Raspberry Pi

IMG_20140516_201633 - Copy4

AberCam Minor Upgrades

With the weather now sunny and warm, AberCam’s tupperware box was acting like a greenhouse, with CPU and GPU temperatures soaring to 60°C+ (by contrast, they are now below 40°C). The solution to this included chopping up a belvita breakfast biscuit box (other breakfast biscuits are available) to shield its sides and top, the front of the box already has a silver heat shield to protect the camera from the sunlight.

IMG_20140516_201714

 

For AberCam’s last couple of weeks of streaming, I have placed it outside the window again where it gets a slightly cleaner view. Also had to modify how the wind speed sensor was secured to the window, as it was previously held in place by the large and heavy window sitting on top of the end of the piece of wood. With the window now open, the safety ropes attached to the end of the wind speed sensor bit of wood have been clamped to the window sill, and a foam chock placed underneath to keep it vaguely level.

Matt

IMG_20140227_153628

Starting Scripts on Start-up – Wind Speed Sensor

Cron is great for starting normal scripts on startup, but scripts that require sudo (administrator / superuser privileges) need to be run in a different way. During my dissertation, I found that init.d scripts can be used to easily start other scripts on boot, even ones requiring superuser access (e.g ones that access Pi hardware, like the GPIO pins).

a0-windspeedsensor.sh init.d script:

#! /bin/sh
# /etc/init.d/a0-windspeedsensor.sh

### BEGIN INIT INFO
# Provides: a0-windspeedsensor
# Required-Start: $remote_fs $syslog $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start wind speed sensor script
# Description: Start wind speed sensor script
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case “$1″ in
start)
echo “Starting windspeed.py script”
# run application you want to start
/usr/bin/python /var/www/windspeed.py &
;;
stop)
echo “Killing windspeed.py”
# kill application you want to stop
PROCESSID=$(sudo ps aux | grep “/usr/bin/python” | grep “windspeed.py” | awk ‘{print $2}’ | awk “NR==1″); sudo kill -9 $PROCESSID
;;
*)
echo “Usage: /etc/init.d/a0-windspeedsensor.sh {start|stop}”
exit 1
;;
esac

exit 0

Explanation:

The first section is the init.d information, specifying what the script provides, and that it should be ran after all other scripts ($all).  It also specifies on which run levels the script will be started and stopped (e.g start when booting in all modes, stop when shutting down/rebooting etc).

In the start case, the windspeed python script is started, in the background. In the stop case, the process ID is found for the running script, and is then killed.

The script is named a0-…. so that it will run first before any other script that I create, which will be named a1, a2… as the scripts run in alphabetical order. This just keeps things tidy and running in a known order.

This script is placed into /etc/init.d/ then registered with the update-rc.d command e.g: sudo update-rc.d a0-windspeedsensor.sh defaults. This will create relevant symbolic links in the relevant rc.d start up and shut down folders, so that the script will start on boot automatically. The permissions need to be set to 755 on the init.d script: sudo chmod 755 a0-windspeedsensor.sh.

Give it a test, and you’re good to go!

Matt

IMG_20140227_153625 (2) thin

AberCam Upgrade 3 – Wind!

Got a wind speed sensor from Maplin’s Ebay shop for £2.50. Stuck it in a bit of polystyrene and used my computer’s case fans to blow air at it for testing purposes. I imagined there would be a little motor in there, and different (tiny) voltages would determine how fast it was spinning – nope that was wrong. What happens (I imagine with a magnet and reed switch, as I’ve found some use that) is that every half a revolution, it makes (or breaks, can’t remember) the circuit, so I just plugged this straight onto my breadboard where I had been testing push-to-make buttons with Python, Pi GPIO and interrupts (really easy to do, and eats 90% less CPU than just having the script whirl round in a while True: loop).

wind sensor

After a bit of maths to convert the RPM to mph (basically speed = distance/time, and time = 1/frequency(rpm)) I started to get some realistic values. Also after some research, most desk fans blow air at about 4mph if you are a foot or two away from it, so used one to test my results were feasible.

Next I got a bit of wood, drilled some holes in the end of it so the wind speed sensor and its wire could be secured, and stuck it out the window.

abercam looking at wind speed sensor

Other News

In other news, I was in some credits!

credits

Some of the footage taken by me of the Aberystwyth storms made it into the programme “The Storm That Stole Christmas” on Channel 4 (27th Feb, 9pm), so I was listed in the credits!

Matt

AberCam Upgrade 2 – Focus

Had the problem that AberCam’s webcam with its autofocus kept focusing on the dirty window that it was sat behind, so had a look to see if it was possible to stop the webcam autofocusing, and stumbled upon this great tool called uvcdynctrl. Downloadable here (or for the pi, use apt-get install uvcdynctrl), and there are some examples and a list of functions and explanations here.

With uvcdynctrl, you can stop the camera autofocusing (uvcdynctrl -d /dev/video0 [if its the only camera - video zero] -s [set] “Focus, Auto” [param] 0 [value - zero in this case].

A good idea is to -g [param] before you set it, so you know what the parameter was set to before you changed it. Also you can -S (capital S) and save a backup of the config file.

Another feature is being able to edit the zoom! e.g: uvcdynctrl -s “Focus (absolute)” 3 [try values 1-5 inclusive].

Also just found a great feature – uvcdynctrl -vc (verbose list of controls – tells you the bounds and step sizes for each param!)

Currently playing with the pan and tilt (e.g of a zoomed in image, my camera doesn’t physically move), managed to get them to each set once, but once attempted to be set, each defaults to the value 36000 and won’t move again. Looks like it could be to do with the webcam driver – oh well, not essential.

Looking at buying a little wind speed sensor to compliment AberCam’s temperature sensor!

AberCam’s focused view:

abercam view

Abercam Upgrade

Finally got around to adding the temperature sensor to Abercam. The temperature sensors I got (DS18B20 ones I believe) use the Dallas 1-Wire protocol to communicate with the Pi, meaning you can attach many temperature sensors in parallel, and the Pi can differentiate between them all and interrogate them individually, without having to use tons of GPIO pins, one for each sensor.

I dug out a 4.7k ohm resistor that I used for this Adafruit tutorial regarding temp sensing on the Pi, and used PHP from this YouTube video to get the temperature.

The PHP script simply opens the w1_slave files, finds and nicely formats the temperature. The HTML uses JQuery to request the .php file every 5 seconds and updates the HTML accordingly.

 

Hang about, I haven’t got PHP on my Pi

No problem, if you aren’t using a LAMP server – e.g I’m using lighttpd for my webserver, install php with the command:

sudo apt-get install php5-common php5-cgi php5

 

This guide I have refered to suggests installing the PHP MySQL libraries if you are using MySQL. Another good, similar, guide is here.

sudo apt-get install php5-mysql

 

After, enable the fastcgi-php module and reload the server:

sudo lighty-enable-mod fastcgi-php

sudo service lighttpd force-reload

Abercam with temp

That all works lovely on a local network, but when using my website to try and access the Pi to get the temperature, I ran into the problem of being stopped from accessing another server and displaying its information on my webpage due to the threat of cross-site scripting attacks. Ways to get round this are make an API or possibly use cURL. I also considered using FTP to upload a file every minute from the Pi containing the current temperature, which would be included in the webpage. Currently, I am using the below script, with a 20 second timeout, and the line “header(‘Access-Control-Allow-Origin: *’);” in the php file it is accessing.

This works really well now, with the page requesting an updated temperature every 20 seconds. Might have to revert to the FTP solution if getting the temp from the Pi is too slow or causes it too much extra traffic.

Matt

 

The Scripts

temp.php

<?php
//File to read
$file = ‘/sys/bus/w1/devices/28-000004abb89f/w1_slave’;

//Read the file line by line
$lines = file($file);

//Get the temp from second line
$temp = explode (‘=’, $lines[1]);

//Setup some nice formatting
$temp = number_format($temp[1] / 1000, 1, ‘.’, ”);

echo $temp;
?>

 

HTML

<html>
<head>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js” type=”text/javascript”></script>

<script type=”text/javascript”>
$(document).ready(function(){
refreshTemp();
});

function refreshTemp(){
$(‘#tempHolder’).load(‘temp.php’, function(){
setTimeout(refreshTemp, 5000);
});
}
</script>
</head>
<body>
<div id=”tempHolder”></div>
</body>
</html>

 

Abercam Viewers, Pi Rover, PiMS

Abercam

As we have been in the middle of a good storm here in Aberystwyth, Abercam has again been getting a good few hundred different people viewing it every day, and over 3000 page views this month. As well as streaming live images of Aberystwyth all over the world, I also tasked it with taking a snapshot every couple of seconds, which I have made into time lapses and stuck on YouTube here.

abercam shots

 

Pi Rover

Found this great YouTube video of a chap who has done many different random things such as making a little printer and milling machine using the Pi, but what interested me most was he has also built a Pi Car… And you can drive his little Pi Rover here: http://www.homofaciens.de/technics-robots-rover-control_en_navion.htm

 

PiMS

PiMS? Yes it has Pi in it. Its the topic I have chosen for my dissertation here in my final year at Aberystwyth. I will be creating a Raspberry Pi Management System that will manage engines such as those found in the Internal Fire Museum of Power in Cardigan. The system will monitor different temperatures, fluid levels (water/oil/fuel etc) and engine speed, notifying museum staff if any of these falls outside a set range.

 

Now back to work…

Matt

 

 

Pi Door Lock

Retrofitted to my door lock, I present to you my Raspberry Pi door unlocker:

Although in this picture it was powered by the Pi Car mobile 1200mAh battery, it is now powered off the mains. The 4 AA batteries power the servo, which has a lifting strength of 15kg/cm. The servo pulls a piece of string to pull back the catch – opening the door.

The quickly-built web interface, with currently a simple JavaScript check for the password validity (I know, I should use server-side checking or MD5 hashing at least, but hey – its only a prototype!)

<input id=”code_input” type=”tel” name=”enteredcode” onfocus=”clearThis(this)” autocomplete=”off” /><br />

The code for the input box: type = “tel” brings up the numeric keyboard on phones, clearThis is a JavaScript function (function clearThis(target){ target.value= “”; } ) that clears the box when clicked. I also turned the browser’s autocomplete off. When a correct password is entered, the following script is run:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
#GPIO.output(7, True)

p = GPIO.PWM(3,50)
p.start(7.5)

try:
p.ChangeDutyCycle(10.5)
#time.sleep(2)
p.ChangeDutyCycle(7.5)
time.sleep(3)
p.ChangeDutyCycle(10.5)
#GPIO.output(7, False)
time.sleep(1)

except KeyboardInterrupt:
p.stop()
GPIO.cleanup()

GPIO.output(7, False)
GPIO.cleanup()

This script changes the duty cycle of the PWM being supplied to the servo (changes the servo angle), from 10.5 (rest) to 7.5 (string pulled) for 3 seconds and back to 10.5 again.

Matt

AberCam – Raspberry Pi Webcam

Bought a few more Raspberry Pis, and have got one gazing at the sea outside my window here in Aberystwyth. You can view it (if its on) here.

Pi Camera in its Poundland tupperware box

Pi Camera in its Poundland tupperware box

Changing Public IP address

With TalkTalk, at least every time our router reboots we get a new public IP address – which is difficult when the abercam webpage is looking for our router at a specific address. To combat this:

I used curl to get the webpage output of: http://ipecho.net/plain – which displays your public IP address. (Could use wget/lynx command line browser like: lynx –dump)

 curl  http://ipecho.net/plain > <filename>.php

Then put the result of this into a file, and uploaded it to my website

 curl -T <filename containing ip address>.php ftp://<ftp server name(.co.uk)>/public_html/ –user <username>:<password>

Where the filename is the name of the file where your IP address is written, ftp server name is your website name (matthewrobbins.co.uk), and the username and password are the ftp details for your website.

Now in the HTML page where the router address was used, I inserted a PHP include of the recently uploaded file containing the IP address. It now looks like:

<img style=”-webkit-user-select: none;” src=”http://<?php include(“<filename>.php”); ?>:<port>/?action=stream” />

Where the filename is the name of the file with the IP address in it, and the port is the one you have set your router to forward incoming connections to the Raspberry Pi (e.g 8080).

Last thing, set a cronjob to run the script every hour or so, bingo. Might be worth adding in an ‘if new_ip == old_ip, end. Else, continue and upload the new one..’ to save unneeded ftp connects and file overwrites. My end bash script looks like: (make sure to put in FULL file paths!)

curl http://ipecho.net/plain > /home/pi/Documents/code/static/ipaddress.php
curl -T /home/pi/Documents/code/static/ipaddress.php ftp://matthewrobbins.co.uk/public_html/ –user <username>:<password>

 

Update

The PiCam worked fine outside my window, but when I moved it sideways, the webcam stream became very jolty and stopped. Pings also stopped returning to the Pi. I believe this is due to the puny looking BT homehub that we have providing us WiFi (it doesn’t even have an external antenna!), so I’ve plugged in my trusty Tenda access point, which promptly set itself up and started working without any help needed. After changing it from WEP to WPA/WPA2 (I know, I know.. but some of the laptops in my house used to only support WEP…), I then had the fun challenge of not only getting one port forward working correctly, but two – as traffic had to be directed through the router (homehub) to the access point (Tenda), then to the Pi.

After setting this all up logically (Homehub forwards port 8080 to the external IP of the Tenda access point, then the Tenda forwards 8080 to the Pi), to my great surprise, everything started working after a couple of reboots (that both devices did NOT tell me I must do). I also found this great guide on portforward.com on double router port forwarding, which is a similar situation.

Update 2

Changed my IP address updater script to ensure that it will always upload an IP address (rather than a 404 or 503 error from the webpage):

(—- to indicate indentation)

#!/bin/bash
ip=$(curl http://ipecho.net/plain)

if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
—-echo ‘Good IP’
—-echo $ip
—-echo $ip > /home/pi/Documents/code/static/ipaddress.php
—-curl -T /home/pi/Documents/code/static/ipaddress.php ftp://matthewrobbins.co.uk/public_html/ –user <username>:<password>
else
—-echo ‘Bad IP. Exiting’
—-echo $ip
—-exit
fi

Also attached little rubber feet to the bottom of the tupperware box, as well as adding a safety rope tied to a bag of shoes in my room, as redundancy in case the wind gets stronger.

Matt

 

Quiet Time

Sorry about the quiet period, I’ve been making the most of my time back at home after finishing my Internship at Google, and also have had a problem with updating WordPress. The problem turned out to be the disc that my site resides on, is full. After a couple of weeks of waiting, 000webhost appeared to fix the problem, I assume moving my site to a disc with free space, but neglected to also move my SQL databases with it, meaning that WordPress and Ministar Galactica broke. Combine this with a PHP error that I saw a few months ago here, but recently on the Aber-links site, which was fixed by the line “define(‘WP_MEMORY_LIMIT’, ’128M’);” to the wp-config.php file, which now overrides the default maximum PHP memory limit that my host sets.

A few quick notes:

Google

It is with much regret that I handed in my laptop and badge in Google London, as my year-long internship was over. I have had an amazing time, and am thoroughly grateful to the company for taking me on and providing me with so many opportunities to expand my knowledge in many fields from both computer maintenance and software engineering, to large scale computer fleet management and more. I have visited many offices around the world, met many techs and other employees, and made a lot of friends. It was sad to leave, but I hope to once again roam the floors of Google in the future.

Pi Cars

Pi Car 01 is still happily roaming, and his brother has just got a few upgrades (smaller breadboard, V2 black WiFi antenna like Pi Car 01 etc). I do hope to get a Raspberry Pi Camera to test out at some point .

Kickstarter

I have funded many many things, and successful projects are starting to arrive. A more in-depth post with pictures will follow, but in the meantime, check out kickstarter’s discover projects page – I would recommend the ‘Design‘ and the ‘Technology‘ sections.

Matt