Monthly Archives: April 2013

Cookbook – Configuring WiFi on Raspberry PI

Raspberry_Pi_LogoPurpose: Following on the earlier Raspberry Pi posts on this Cranfield University site, this cookbook explains how we got the Raspberry Pi to run on a network using a WiFi USB dongle.

Although the default setup for the Raspberry Pi allows wired ethernet connections out of the box, it is useful to enable the Pi to work with WiFi. The first thing you need is to buy a suitable WiFi USB hardware dongle. Before purchasing this, be sure to visit the peripherals site at Select one of the ‘Working USB WiFi Adapters’. We chose the inexpensive ‘USB Wifi Adapter for the Raspberry Pi’, sold by a number of vendors such as the ‘Pi Hut’ ( and Amazon, etc.

Once you have this, insert into the Pi and boot up. When running, we followed the excellent instructions here ( First, we see what devices are recognised on the USB port:


This listed our adapter as:

Bus 001 Device 004: ID 148f:5370 Ralink Technology, Corp. RT5370 Wireless Adapter

Although all drivers are supposed to be pre-loaded, even if you have the latest ‘Wheezy’, it is good practice to update the system to the latest set of drivers. To do this, type:

sudo apt-get update
sudo apt-get install

Once finished you can search for the new device in the APT package cache. We used this command:

sudo apt-cache search ralink

The last word is the actual search string, here ‘ralink’. Before this worked, we had tried a few other strings like ‘RT5370’ – which had returned nothing. Note there is no ‘-‘ before the word search! Anyway, once we tried ‘ralink’ the search worked and it reported:

firmware-ralink – Binary firmware for Ralink wireless cards

Now we installed the latest drivers for our wifi key, thus:

sudo apt-get install firmware-ralink

Once this whirred away and finished updating the drivers, we rebooted the computer:

sudo shutdown -r now

Once the Pi was back up and running, we made sure the USB key was recognised:


Hopefully you will see the ‘wlan0’ interface being listed.

The next step is to configure the wireless key to work with the router. There are  few options here. First you can manually configure everything, and secondly you can use the ‘WiFi Config’ tool on the Pi graphical login screen – as shown. The latter is certainly the easiest option.

Pi_WiFi_ConfigRunning this config tool, the programme immediately spotted the ‘wlan0‘ adapter. Selecting ‘Scan’ enabled the programme to locate the SSID of the network router to connect to. Under the ‘Manage Networks’ tab, we then ‘edited’ the connection to add in the relevant security connection information (eg. WEP, WPA keywords etc ). The first ‘Current Status’ tab then showed a successful connection had been made to the router and an IP address successfully allocated by the router’s DHCP server.

Under the bonnet
So far so good – a working WiFi connection. However, we are using the Pi as a ‘LAMP’ database server (see A dynamic IP address is therefore not ideal if we want to connect to say the Pi MySQL server instance from other devices (e.g. iPhone). We therefore wanted to establish a ‘static’ IP address for the Pi and to do this we need to dive under the bonnet. First move to and edit the network configuration file (‘nano’ is a text editor, the ‘sudo’ runs nano as the root user):

cd /etc/network
sudo nano interfaces

This interfaces file controls access to the various networking interfaces the Pi can use. There is a LOT of discussion on the web of different configurations people use – with varying degrees of success reported. Editing this file must be undertaken carefully – we certainly suggest taking a backup first! To cut a long story short, and following a fair bit of frustration, the following configuration file worked for us:

# The loopback network interface
auto lo
iface lo inet loopback

# The primary wired network interface
auto eth0

# The wireless network interface
auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

# Default connection
iface default inet static

Note the fixed IP address we wanted was on our local subnet. Note also the ‘manual’ setting of the wlan0 network. This setting ensures the ‘/etc/wpa_supplicant/wpa_supplicant.conf’ file (created by the WiFi Config tool above) is read correctly. Lastly, the use of the default setting at the end for the IP address ensures that if the Pi connects, either by wired or wifi link, it still has the same fixed IP address. The original ‘dhcp’ setting line was removed. Note finally that blank lines are ignored and that ‘#’ symbol denotes a comment.

Configuring networks is clearly a complex subject, this post just highlights how we got ours working. There are lots of other examples online.

Formal network interface documentation is also at

The Pi itself also has some standard configuration file examples, worth looking at,  see ‘/usr/share/doc/ifupdown/examples/network-interfaces’, but the file is ‘gzipped’ up and needs unzipping to view it first, thus:

cd /usr/share/doc/ifupdown/examples
sudo cp network-interfaces.gz network-interfaces_examples.gz
sudo gunzip network-interfaces_examples.gz
sudo more network-interfaces_examples

We hope this helps you get your WiFi running smoothly!

Cookbook – Building a Layar Augmented Reality Server on Raspberry PI

Raspberry_Pi_LogoPurpose: Augmented reality is an exciting new area of computing, with many ‘apps’ available. On this Cranfield University site, we will describe building a server for the popular ‘Layar’ app (, builds on the earlier GeoThread project to Build a LAMP server on the Raspberry Pi computer. The Raspberry Pi is an amazing low-cost computer (see The Layar server uses PHP, MySQL and Apache for serving up Layar ‘POI’ (point of interest) objects as a JSON ( data stream from the MySQL database.

The mobile phone and tablet ‘layar’ app allows you to connect to an augmented reality server to look at points of interest etc in the world around you. But what does the data the app ‘consumes’ look like? In this tutorial we use the Raspberry Pi to serve up Layar data as a JSON data stream.

This assumes you have a Raspberry Pi, installed with Apache, MySQL, PHP and PHPMyAdmin, plus vsftpd as per the earlier instructions. Get filezilla and ssh terminal working (or use the tightvnc service).

These notes are really to support and extend the basic ‘Layar’ tutorial at:

Download the layar sample source code (held in a zip file) at:

Unpack the files. Note that we had to undertake this process manually in File Explorer, due to the format of the zipfiles not being accepted by the Windows ‘zip extract’ tool.

There are several parts to the tutorial files that you receive – an SQL script to build and populate the database, and then a number of PHP scripts.

If you are likely to load and reload and reload the SQL script – inevitably one does, then consider editing the SQL script to add these lines above each of their respective database table definitions (thus allowing you to rebuild the tables as required).


Building web services always leads to a few errors until you fix the problems. We find it helps to turning on Apache and MySQL logging on the Raspberry Pi until such inevitable snags are removed. To do this, edit the configuration files thus:

MySQL Logging

To turn on the MySQL logging, edit the MySQL configuration file thus:

cd /etc/mysql/my.cnf
sudo nano my.cnf

then, uncomment the lines:

#general_log_file = /var/log/mysql/mysql.log
#general_log = 1

Now restart MySQL and the logging operation is commenced.

sudo service mysql restart
tail –f /var/log/mysql/mysql.log

Reverse this to stop logging once all is working correctly.

Apache Logging

First, inspect the logfile:

sudo more /var/log/apache

or better still to see only new lines as they appear in (are being written to) the logfile

sudo tail –f /var/log/apache2

Establishing the database

The database is created and administered using the phpmyadmin tool. Create a new database called


Run the supplied Layar example SQL script (use the IMPORT button for the database in phpmyadmin) to create and populate the two database tables.

Create a new db user ‘layar’ (password ‘layar’ – or whatever you wish) and add privileges ‘select, insert, update, delete’ rights to the ‘layar_custom’ database on (you can change the IP later for a public website address if you want to go that far).


Create a new folder in the webserver root called ‘layar’ and copy over the php scripts – e.g. to ‘’

Adjust file permissions for web access (chmod 755 for the folder, 554 for files, owner chown pi)

sudo chmod 775 /var/www/layar
sudo chmod 554 /var/www/layar/*

Next, you need to customise the ‘’ file to enable your specific database credentials. Edit the file and add in your details, thus:

define('DBHOST', '');
define('DBDATA', 'layar_custom');
define('DBUSER', 'layar');
define('DBPASS', 'layar');

The files you uploaded, such as “” have a call that loads in the configuration file above only once. You may find you need to disable this until the tool works. In which case, edit the require code thus:


Changing from ‘require_once()’ to ‘require()’ means the code is read in every time you refresh the browser. Once all works, put it back as was.
Running the Application

From your home networked laptop/pc browser, run You may well need to debug the whole configuration until all error messages are resolved – this is where using the apache and mysql logs can really help bugfix. If you encounter a ‘500’ error, this is likely to mean the MySQL user privileges are an issue. Also note the require_once() / require() issue noted above. Once it works, some ‘application programming interface’ API calls can be tried. Note the Layar name is ‘layername’ (as recorded in the MySQL table ‘Layar’).

Example Rest API calls

This returns a stream of ‘JavaScript Object Notation’ JSON data, e.g.

{"layer":"layername","hotspots":[{"id":"geo_1","imageURL":"http:\/\/\/Layar_banner_icon.png","anchor":{"geolocation":{"lat":52.374118,"lon":4.93425}},"text":{"title":"The Layar Office","description":"The Location of the Layar Office","footnote":"powered by Layar"}}],"errorCode":0,"errorString":"ok"}

API Documentation

Request: see

Returns: see


Once this works and your setup is creating valid JSON data you can turn off all the debugging fixes. These instructions are just the start. Taking things forward, you would now need to place the server in the public domain and reveal (register) the service to your Layar account server for registered layars.

Cookbook – Building a LAMP Server on the Raspberry Pi computer

Raspberry_Pi_LogoPurpose: In this project we wanted to use one of the amazing Raspberry Pi computers ( to build a fully functional ‘LAMP’ environment – that is ‘Linux’ ‘Apache’ ‘MySQL’ and ‘PHP’. On this Cranfield University site, we describe how we did it. Only the basic commands are placed here, see the links to other websites for extra explanations and post-install configurations etc.

Obtaining a Raspberry Pi

We suggest buying a Raspberry Pi with a case and power supply, as well as SDHC card with Raspian OS. However, for experimentation purposes, you may also wish to buy another 4Gb SDHC card (for compatible types, see before purchase). Then you can simply swap cards to try our different configurations (remember, always shut the Pi down before removing the card). You will also need to obtain an Ethernet cable, an HDMI to HDMI cable, a wired USB keyboard and mouse, and a TV that accepts HDMI input. We are also assuming you have a home router with Internet access that the Ethernet cable will plug into.

The initial configuration is done sitting in front of the plugged-in TV, but once ‘SSH’ (and potentially ‘TightVNC’) are installed, the Pi can be left plugged into the router and then be accessed remotely via a separate laptop, connected say wirelessly to the router, either via a secure shell ‘SSH’ client such as ‘Putty’ (, or the graphical ‘TightVNC’ client ( These latter tools need to be installed on the separate computer/laptop first. Do I need TightVNC? TightVNC will be useful if you intend to run graphical programmes off the Pi – however, you don’t need it if you are configuring the Pi just as a server (e.g. web server or database server). In which case Putty will be fine.

New SDHC Card image

If you buy a pre-loaded Raspian card, you don’t need this step, but if you did start with a blank SDHC card these are the steps you need. Take a new SDHC – fat32, 4Gb empty card – formatted if not new. Note, it is best to use an external SDHC USB reader/writer device, rather than the slot built into your laptop if your laptop is not pretty newish.

To format SDHC cards, first download the utility ‘SDformatter’ ( Select ‘Options’ -> ‘format size adjustment on’. Use this tool, not the Windows format programme.

For advice on easy set up of the card, see

Next, download the latest Pi Operating System, called Raspian ‘Wheezy’, from

If you download a windows file, you can unzip the contents to reveal the ‘.img’ imagefile.

Next, to write the image to the blank card, use the SDHC Image writer from -(now at)>

Other scary options that some people use include the ‘flashnul-1rc1′ or the ‘fedora-arm-installer-1.0.3-7-x32’ tools. The ‘flashnul-1rc1’ in particular needs especial care and attention (being in Russian comrade!)

Once Raspian is unpacked some files will be visible on the card in Windows – but don’t edit them in windows! Some files are hidden to Windows so it doesn’t look like a full card. Insert the card then into the Pi and bootup. This should start up and kick off raspi-config. The default account/password is:

User: pi                 Password: raspberry

You should be running in terminal mode, type ‘startx’ to kick off the graphical user window environment (this is something a lot of guides seem to fail to mention!)


Spend a little time now exploring the graphical interface. The menus and system options are available from a drop down menu in the top left corner. Note the very first time you run, you may be presented with the system configuration tool ‘raspi-config’, explained below.

The rest of the article assumes an Ethernet cable connected to the Internet is plugged in. Note there are wireless USB dongles that should work with the Pi ‘out of the box’, instructions for configuring that are elsewhere here on Geothread – see

Basic Configuration

You may find you are either running raspi-config immediately, or else this useful tool can be started at the command line withn the command ‘sudo raspi-config’. Note many of the commands in this tutorial are preceded by ‘sudo’ – meaning run the command with root ‘superuser’ authority.

Once running raspi-config, you can select from a few useful options from its menu, thus:


This option ‘inflates’ the filesystem to fill SD card. This makes the whole capacity of the SDHC card available for storage – a good idea!

ssh server – Enable

The ssh ‘secure shell’ allows programmes like ‘putty’ on a PC to run a terminal session onto the Pi. However to do this the ssh server needs to be running and enabled on the Pi.


Also select the option ‘update’ to update the raspi-config itself.

Once you ‘Finish’, you will pass back to the command line.

Next, you must update the core operating system files. You enter:

sudo dpkg-reconfigure tzdata 
sudo apt-get update 
sudo apt-get upgrade 
sudo apt-get dist-upgrade

This updates the system software – if the Wheezy image was up to date this shouldn’t take too long. If it wasn’t time to make a cup of tea! Open source software gets updated FAR more frequently that proprietary software, so you will need to run the last three commands from time to time to keep the Pi up to date.

To be able to access the Pi remotely, install the TightVNC server if required. This gives a graphical ‘X-Windows’ GUI onto Raspberry from remote laptop/PC/Mac. Note you also need to install TightVNC client on your separate laptop/computer that will be used to access the Pi.

sudo apt-get install tightvncserver

Following the excellent instructions at, or the more recent update at, next you need to configure the tightvncserver. Create a new file called ‘tightvncserver’ in the init.d directory (nano is a text editor programme):

sudo nano /etc/init.d/tightvncserver

Into this file, enter the following:

# /etc/init.d/tightvncserver 
case "$1" in 
        su $VNCUSER -c '/usr/bin/tightvncserver :1' 
        echo "Starting TightVNC Server for $VNCUSER " 
        pkill Xtightvnc 
        echo "TightVNC Server stopped" 
        echo "Usage: /etc/init.d/tightvncserver {start|stop}" 
        exit 1 
exit 0

Give the script executable permission:

sudo chmod 755 /etc/init.d/tightvncserver

Now start or stop the service manually thus (this is the basic model used for dealing with all Debian processes).

sudo /etc/init.d/tightvncserver start
sudo /etc/init.d/tightvncserver stop

Make the TightVNC server start every time the Raspberry Pi starts.

sudo update-rc.d tightvncserver defaults99

Setting an IP Address

By default the Pi uses Dynamic Host Control Protocol (DHCP) meaning it may get a new ‘IP’ address each time it boots up. If we are using the Pi as a web server/database server this could be a nuisance. If so, we can force the Pi to used a ‘fixed IP’ address so it always remains the same.

Following the excellent instructions at, set the IP address from DHCP to fixed. This will make it easier to locate your webserver later.

First, identify the current computer network ‘IP’ address, type:


On a home network, it is likely to be something like 192.168.1.xx. We will fix the Pi as ‘’. Edit the network interfaces configuration file with the text editor ‘nano’, thus:

sudo nano /etc/network/interfaces

Replace the lines

iface lo inet loopback 
iface eth0 inet dhcp


iface lo inet loopback 
iface eth0 inet static 

Note we used  (this being a private network subnet address)

See also for more guidance.

Now reboot the Pi. To do this, type in:

sudo shutdown -r now

This reboots the Pi ‘now’ and then hopefully you can log on again, but this time potentially as a remote session with SSH or TightVNC from your laptop (where the laptop has a wireless connection to the router). Note the IP address is now fixed as noted above. If you have a laptop/PC on the same home network, you can open a command prompt and run ‘ping’ to see if you receive a response from the Pi.

If you use tightvnc, rather than ssh, then on your laptop/pc vncclient installation, you need to enter in the address of the Pi for the connection, e.g. Don’t omit the ‘:1’ at the end of the address!! You can also explore the options to set the screen size ‘geometry’ to 1024×728 with a colour depth of 24bits.

Linux Commands

You need to be familiar with Linux commands. Learning Linux can be daunting – some good documentation is here – best is the one page reference card here

In the next steps, now the basics are in place, we proceed to the installtions of the web and database server software. See also

Apache Web Server and PHP

To install the Apache web server and PHP (find out more here and here, type:

sudo apt-get install apache2 php5 libapache2-mod-php5

To ‘restart’, ‘stop’ or ‘start’ apache, use the following command (varying the last word)

sudo service apache2 restart

Note the Apache webroot location for your webfiles is ‘/var/www

The Apache log files are put in ‘/var/log/apache2

MySQL Database Server

sudo apt-get install mysql-server mysql-client php5-mysql

You need to enter in a database system password, such as ‘raspberry’! Once installed restart and you can hopefully access the MySQL command line prompt thus:

sudo service mysql restart 
mysql  -u pi –p

Check the interactive logon works as user pi. Try and ‘use’ a database and select records:

use mysql 
select * from users;

Use <ctrl>+c to quit

For logging, see


PHP should have been installed also. In the /var/www webroot, create a new file called testphp.php with the ‘nano’ editor, and enter the following. Once created, run the file in the your laptop/pc browser to see the Pi PHP status:

sudo nano /var/www/testphp.php

Enter the text oneliner below into the file.

<?php phpinfo(); ?>

Your laptop/pc web browser ‘should be able to see this web page served up. Enter the IP address we set earlier, plus this file, thus:

In web browser, enter the URL

Hopefully you should see the PHP status page appear.


In PHP you should use the recommended MySQLi command extension to access the MySQL database. It ‘should’ be installed already – but look down the phpinfo() web page above to find it and ensure it is shown as ‘enabled’.

To learn more, see         (but do check the phpinfo() output above first)


To manage the MySQL database, we recommend the excellent ‘phpmyadmin’ MySQL web management console. All the MySQL administration can then be undertaken through a web page.


apt-get install phpmyadmin

Select ‘apache2’ as the web server.

Create a phpmyadmin password, such as ‘raspberry’ (or whatever – but don’t forget it!)

You should now be able to call up the phpmyadmion home page at: – login as root/raspberry

Note user privileges to the MySQL database are all managed via phpmyadmin. Each user account needs to have specified the host from which the user will come to access the database. The ‘%’ (all servers) option didn’t work for us and so we needed to repeat a configuration for servers: ‘’, ‘’, ‘localhost’ and ‘raspberry pi’. A bit fiddly – essentially you open up the privileges for the user and duplicate the settings varying the host each time. To help with this, note that once phpmyadmin is installed, one can see the various options the phpmyadmin user has pre-assigned. Note that connecting to MySQL from the SSH terminal uses ‘localhost’, whereas connecting from a webserver can use ‘’ – so the source varies according to source. One needs to experiment – hmm!

Remember later that if you ever receive a ‘500’ error on the webserver when trying to access the database, it is likely due to the incorrect privileges. You may need to look at the webserver apache logfiles in a new window (‘/var/log/apache2’) to actually see the error:

sudo more /var/log/apache

or better still, to see only new lines as they appear in the logfile:

sudo tail –f /var/log/apache2


We need the means to get web pages we write off the laptop/pc onto the Pi webserver. For this, we need an ftp daemon running to upload files onto Pi – we suggest using vsftp, it is the best (but not the only) ftp server for debian.

sudo apt-get install vsftpd

Based on the instructions at, now edit the vsftp configuration file.

sudo nano /etc/vsftpd.conf

Search down through the file and change the following lines:
anonymous_enable=YES Change To anonymous_enable=NO
#local_enable=YES Change To local_enable=YES
#write_enable=YES Change To write_enable=YES

Also, add a line to the bottom of the file:
Quit the editor and restart the vsftp server.

sudo service vsftpd restart

We suggest NOT following the additional steps in some guides for messing (post install) with pi account line in passwd file etc. We trashed an installation doing this. You ‘should’ be able to just sudo apt-get the vsftp server and reboot – as we did second time round. Make the minor fixes to vsftp configuration file described above. But we suggest to do these edits and nothing else.

On your laptop/pc, you need an ‘ftp’ client . We suggest the freely available ‘filezilla’ ftp client ( for transferring files across by ftp. and Login to the Pi as user pi. Save the configuration to access the Pi to facilitate future access.

Web files

Set webroot file privileges

sudo chown -R pi /var/www

Now a set of website files can be copied from the PC/laptop with filezilla to this folder and accessed from the laptop/pc webbrowser thus:

Disk capacity free

Here’s how you can establish how much disk space is left over. After all of the above we had used about 1.8Gb on the 4Gb SDHC card.

df –h

Shutting Rasperry Pi down

sudo shutdown –h now

To reboot/restart it when running

sudo shutdown –r now


The Raspberry Pi is an excellent training tool for LAMP installations and can even be serviceable for light operational tasks. It is an educational tool though and a really great way to learn Linux, Apache, PHP, MySQL etc… One great advantage is the SDHC card filesystem. You can keep several installations and configurations on different cards and, as long as machine is correctly powered down, swap cards and reboot as required.

Backing up these SDHC cards is not easy and not always predictable. Tools like the win32diskimager and flashnul-1rc1 can image a card to a ‘.img’ file, but the file may a. not fit back onto a formatted card of same capacity, and b. not work anyway after reboot. Googling shows there are a lot of approaches taken – which is best though isn’t clear! Have fun!