Raspberry Pi Binary LED Clock

Raspberry Pi Binary LED Clock

Binary clocks show the time in an unconventional format. They display the hours, minutes and sometimes even seconds as numbers represented in the binary numeral system. Binary clocks and binary watches have grown quite popular today. More and more people work in IT and become familiar with the binary numbers, the native language of our computers. Most who understand binary notation, consider it clean, simple and elegant, so it’s only natural that they perceive binary clocks and watches as cool gadgets.

Once you get the hang of it, reading binary watches is very easy. All you have to understand is that the clocks show binary digits (bits) and that each binary digit represents a factor of two and that you have to add together all the factors which are set (on). For example, 101111 = 1*2^5 + 0*2^4 + 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0 = 1*32 + 0*16 + 1*8 + 1*4 + 1*2 + 1*1 = 32 + 0 + 8 + 4 + 2 + 1 = 47. This might seem a bit complicated at first for the untrained brain, but a little practice will make you read these combinations almost instantly.

The binary digits can only have two states: 0 and 1. This means that a binary watch must display the time using some things that also have two states. And what is more suitable for such a purpose than a light? A light is either on (1) or off (0). To be honest, I’ve never seen a binary watch using anything else than a light for  digits, although I’m sure that people’s creativity is endless and there are some unusual devices out there, but the vast majority of the binary clocks just rely on LEDs for displaying the time. LEDs are very practical for this purpose because they draw very little current, their light is strong enough but not too strong, they come in many different colors, they turn on and off very fast (unlike conventional light bulbs) and they are cheap.

Not so many years ago it was very hard to buy a binary clock or watch. If you wanted one, you had to make your own. Today the situation is different: they are available in large quantities and in many shapes and sizes, from wrist watches to wall clocks. Unfortunately most of them are not 100% binary clocks. Instead they are pseudo-binary clocks, which mix the binary numeral system with the decimal numeral system. For example a real binary clock would display 47 as 101111, while a pseudo-binary clock displays it in two groups of digits: 100 (4) and 111 (7), which means that you have to multiply the value of the first group by 10 and add the value of the second group to it. The market is full of such not real binary clocks. It’s hard for me to understand why people buy them. I mean, if you want binary, why not go for real binary? I have a pseudo-binary wrist watch myself, but I’m just not satisfied with it, so I decided to make a real binary clock to keep in my room. This is how the first prototype turned out:

Raspberry Pi Binary LED Clock

In the following I am going to show you how to make a binary LED clock which is driven by a Raspberry Pi. In other words, we’ll make a circuit with is able to light up some LEDs in any combination and a Raspberry Pi will be responsible for keeping the time and instructing the circuit which LED to tun on and which to turn off. If you are thinking at this moment that using a Raspberry Pi as the brain of the binary clock is a little exaggerated,  you are right. There are many simple circuits that can do the job, the Raspberry Pi is a full general usage computer, using it for keeping time and driving some LEDs is just so much below its capabilities. It’s like shooting a bird with a canon. True. But it’s a great learning project, good practice to get accustomed with using the Raspberry Pi’s GPIO pins to drive custom hardware.

Let’s design our clock in theory first. If we make a clock that displays the time in 24-hour format, the maximum possible value of the hour is 23, which is less than 32 (2^5). This means that we will need 5 LEDs to display the hours. The maximum value for both the minutes and seconds is 59, which is less than 64 (2^6), so we are going to need 6 LEDs for the minutes and for the seconds. That means a total of 17 LEDs used as binary digits on our clock. Now, it may not strike you at first as such, but the fact that we need 17 LEDs, and not 18 or more, is an extremely lucky coincidence. That is because the Raspberry Pi has a total of 17 programmable GPIO pins available on the P1 header, which we can use to drive our LEDs. Many will argue that using all available pins is a terrible waste because there are techniques to drive 17 LEDs using as little as 3 GPIO pins. True. But we want to keep things simple. We don’t want to go into the more complicated stuff, like  serial communication and shift registers, multiplexing, charlieplexing and so on. Let’s stick to the basics with this project by controlling each LED with a separate GPIO pin.

One more thing to keep in mind is that the Raspberry Pi can safely supply a maximum of 16 mA per GPIO pin and 51 mA in total on all pins. Our clock would light up all LEDs simultaneously when the hour is 63, the minute is 31 and the seconds are 31. That is an invalid time value, so it should never happen, unless the controlling software messes things up because of a bug. Let’s plan for the worst though, and design our clock to  give 3 mA of current to each LED (because 17 * 3 = 51). Although most 5 mm LEDs (which we will use) are rated at 20 mA, I have found that they give more than sufficient light even at 1 mA, especially the super bright ones. We are going to choose the resistor values in a way that will supply 3 mA of current to each of our LEDs (blue, white and orange). If you want to use different LEDs or wish to have a different amount of current running through them, use the LED calculator to obtain the appropriate resistor values. Optionally you can add variable resistors connected in series with the normal resistors. This will allow you to control the amount of drawn current and the brightness of the LEDs at any time, after the circuit is done. A good value for the variable resistors may be 10 kOhm, but you can even use higher values and the LEDs will still be bright enough.

Using resistors which will limit the current through the LEDs to 3 mA will guarantee that we do not exceed the maximum ratings of the GPIO pins and we’ll not damage them. This means in theory that we could simply connect the LEDs to the appropriate programmable GPIO pins directly through the resistors. You will notice, however, that in our design we use ULN2003 or ULN2803 integrated circuits to isolate the currents going through the LEDs from the currents coming from the programmable GPIO pins. We do this for the following reasons:

    • We want to make it theoretically possible to use other LEDs or lights with the clock, which need more than 3 mA of current each. Isolating the signal circuit from the light circuit using the ULN2003/ULN2803 ICs makes this possible. This design allows you to give each of the LEDs 20 mA of current, as specified by the manufacturers, although it’s probably a waste of current in most cases. If you exceed the ratings of the GPIO pins, you will have to use a 5V external power supply for giving current to the load circuit. Otherwise you can connect the load circuit too to the 5V power supply pin of the Raspberry Pi.
    • We want to draw the current from the 5V power supply pin of the Raspberry Pi. If we connect the LEDs directly to the programmable GPIO pins, that means that the LEDs will get 3.3V instead. This may be possible, but the resistor values will need to be recalculated. Generally, the 5V power pin is more suitable for our purposes because it’s able to give off more current.
    • All in all, it’s a good idea to decouple the load circuit from the signal circuit because it offers better protection to the Raspberry Pi. It’s safer. You don’t want to risk your Pi, do you?

Raspberry Pi Binary LED Clock

Required parts

  1. 5x LEDs for the hours (I have used blue super bright 5 mm LEDs).
  2. 6x LEDs for the minutes (I have used orange super bright 5 mm LEDs).
  3. 6x LEDs for the seconds (I have used white super bright 5 mm LEDs).
  4. 5x 680 Ohm resistors for the blue LEDs with 3.3 V voltage drop.
  5. 6x 1 kOhm resistors for the orange LEDs with 2V voltage drop.
  6. 6x 680 Ohm resistors for the white LEDs with 3.3V voltage drop.
  7. (Optional) 17x 10 kOhm variable resistors, one for each LED, to be able to control their brightness (and the drawn current) at any time.
  8. 3x ULN2003 or ULN2803 ICs for switching the LEDs with sginals from the Pi.
  9. (Optional) 3 sockets for the ICs to avoid their direct soldering onto the board.
  10. 1x 26-pin male IDC connector.
  11. 1x 26-pin female-female IDC ribbon cable to connect the binary LED clock to the Raspberry Pi. 19 pieces of female-female jumper wires can also be used instead.
  12. 1x stripboard (breadboard) for soldering all the components onto it.
  13. Insulated wire (preferably in many colors) for connections between components on the back of the board.

Raspberry Pi Binary LED Clock

Connections

1. Connect the 5V power supply pin of the Raspberry Pi to the anode (positive leg) of each LED. To identify the 5V power supply pin, read this.

Raspberry Pi Binary LED Clock

2. Connect the ground pin of the Raspberry Pi to the ground pin of each ULN2003/ULN2803 IC. To identify the GND pin of the Raspberry Pi, read this.

Raspberry Pi Binary LED Clock

3. Connect each of the 17 programmable GPIO pins of the Raspberry Pi to an input pin of the ULN2003/ULN2803 ICs. In order for the provided software to function as expected, connect them as follows:

      • GPIO pins 0-4 to the input pins 0-4 of the first IC
      • GPIO pins 5-10 to the input pins 0-5 of the second IC
      • GPIO pins 11-16 to the input pins 0-5 of the third IC

To identify the 17 programmable GPIO pins on the Raspberry Pi, read this.

Raspberry Pi Binary LED Clock

4. Connect the cathode (negative led) of each LED to its own resistor and optionally place a variable resistor in series with the conventional resistor.

Raspberry Pi Binary LED Clock

5. Connect the other legs of the resistors (or  the legs of the variable resistors if you have included them) to the output pins of the ULN2003/ULN2803 ICs. In order for the provided software to function as expected, connect them as follows:

      • The (variable) resistor legs coming from the hour LEDs to the output pins 0-4 of the first IC
      • The (variable) resistor legs coming from the minute LEDs to the output pins 0-5 of the second IC
      • The (variable) resistor legs coming from the second LEDs to the output pins 0-5 of the third IC

Raspberry Pi Binary LED Clock

That’s it, you’re done!

The back of my board didn’t turn out very pretty, but my soldering skills are not that great. If you wish to avoid all the colorful wires on the back of the board, you should consider designing a custom printed circuit for this design and having it made in advance.

Raspberry Pi Binary LED Clock

If you would like to experiment with an even more simple design than the one described here, you could leave out the ULN2003/ULN2803 ICs, the IC sockets and the variable resistors and connect the LEDs with resistors of appropriate value directly to the 17 programmable GPIO pins. you can find more information about how that can be done here.


The Raspberry Pi binary LED clock Bash script

Now that the Raspberry Pi binary LED clock is put together, we’ll need some software to drive it. You can write your own, or you can use the Bash script provided here for download. Controlling the Raspberry Pi‘s GPIO pins from a Linux shell script is probably the easiest method, but it requires the presence of the WiringPi gpio utility in your system. For more information please read this.

Note that controlling your binary LED clock from a Bash script might not be efficient at all. The provided script utilizes about 25% of the Pi’s CPU, which is quite a waste. But if you don’t use the processing power of the Raspberry Pi for much else most of the time, this might be an acceptable solution.

The provided script has the option to output the operations that it’s preforming to the standard output too (not just to the LEDs) and the seconds LEDs can be kept off all the time, obtaining a clock which shows only hours and minutes. You may run this script in background (binaryclock.bash&). For more information start the script with the –help option.


The light show Bash script for the Raspberry Pi binary LED clock

Since the hardware that we have put together for the binary LED clock is basically nothing but some LEDs connected to the GPIO pins of the raspberry Pi and the binary clock logic is implemented 100% in the software, there’s no reason not to use this little piece of custom hardware for some other purposes, like LED animations, for instance. You will find here a Bash script which runs LED animations on it. Just like the binary clock script, it too relies on the WiringPi gpio utility.

The light show script can play the animations randomly or it can show a single animation specified by its name. You can specify the duration of the animations (in seconds) or you can simply instruct it to run them for half or double the default time. It can also write information to the standard output. If you choose to run animations infinitely, it might be practical to run the script in the background (lightshow.bash&). For more information start the script with the –help option.


Video

Below is a video of the Raspberry Pi binary LED clock. It shows not only the necessary components and required connections, but you can also see the clock in action.

 

Downloads

 

 

Controlling the Raspberry Pi’s GPIO pins from a web browser

Wouldn’t it be cool to control things in your home from a web browser? I mean turn on and off the lights, adjust the music volume, open the gate or the garage door, start the garden sprinklers or give the dog a portion of food just by clicking a button in a web browser, perhaps from your smart phone? It certainly would be very exciting! And it is not only possible, but it can also be relatively easy. All you have to do is get a Raspberry Pi, connect some custom hardware which can do your custom task (switch lights on and off, drive motors, send wireless signals to other devices, etc.) to its GPIO pins and write some software which can control the Raspberry Pi’s GPIO pins based on requests received from a web browser. The hardware part heavily depends on what you wish to achieve exactly and will be different for every task. In this article we will address the software part, we will describe a relatively simple way of talking to the Raspberry Pi‘s GPIO pins from a web browser.

 

Raspberry Pi Cup

 

Used technologies/languages/frameworks/tools/applications

As you might have already guessed from the image above, we are going to write Java programs, which will run under a Java web server such as Tomcat and listen to requests from browsers. For the user interface that will appear in the browser we are going to use the excellent Vaadin framework. Our weapon of choice for accomplishing the communication with the Raspberry Pi‘s GPIO pins is a very nice little library called Pi4J.

I’m not going to talk about the benefits of using Java, as that may turn into an infinite discussion, but I am going to say a few words about the components that make up our application.

The Pi4J project is a blessing for those of us who prefer to program the Raspberry Pi‘s GPIO pins in Java. It is not only very straightforward to use and easy to understand, but also well structured. I personally prefer to use it because it offers a very clean object-oriented approach to talking to the hardware. Pi4J is essentially a Java wrapper for the WiringPi library (which is written in C). The Pi4J team runs a very nice website which is full of useful resources and contains everything you need  to know for making a start with Pi4J.

The Vaadin framework is an easy and yet powerful tool to create user interfaces for Java web applications. I am not a Java expert by far and I don’t know how many other good frameworks of this type are out there. What I do know is that with Vaadin you can write nice, clean UI code very fast and that the resulting UI looks good, so it is my preference to use it.

 

Application structure

  1. The Vaadin user interface receives user actions from the web browser.
  2. The event handlers of the Vaadin UI components call the Java user code in our web application, which runs on the Tomcat sever.
  3. Our Java code translates the requests to logical GPIO operations and calls functions from the Pi4J library accordingly.
  4. Pi4J sets the states of the Raspberry Pi‘s GPIO pins as specified.
  5. The state of the hardware connected to the GPIO pins is changed (an LED is turned on/off, a relay is switched on/off, a speaker is sent a signal, etc.).

According the above steps the user action travels from the web browser, through Vaadin, our Java code and Pi4J to the Raspberry Pi‘s GPIO pins and triggers some hardware action. It is also possible to go in the opposite direction:

  1. The state of the hardware connected to the GPIO pins changes.
  2. Pi4J triggers an event based on the change.
  3. Our Java code receives an event and handles the change by modifying the state of the Vaadin user interface components.
  4. The Tomcat sever sends a response to the web browser with the modified state of the Vaadin components.
  5. The web browser displays the change on the user interface (shows a notification, changes the text of some labels, shows/hides some components, etc.).

 

Example application: Turning an LED on/off from a web browser

We will be using the simplest possible hardware for our example application: an LED connected to GPIO pin 0, which will be turned on/off by clicking a button in a browser:

Raspberry Pi model B controlling one LED

Raspberry Pi model B controlling one LED

 

Downloading and installing the prerequisites

Step 1: Download and install your preferred version of the Java Development Kit on the machine on which you are going to develop the application  In our example we will create the application on a Windows system.

Step 2: Download and install the Eclipse development environment on the machine on which you are going to develop the application.

Step 3: Install Vaadin under Eclipse. Open Eclipse and go to the Eclipse Marketplace (Help -> Eclipse Marketplace…). On the Search tab type Vaadin into the Find box and hit Go. It should find “Vaadin Plugin for Eclipse”. Install it.

Step 4: Download and install the Java Runtime Environment or Java Development Kit of your choice on the Raspberry Pi (OpenJDK for example: apt-get install openjdk-7-jdk).

Step 5: Download and install Tomcat on the Raspberry Pi (apt-get install tomcat7). Configure it to listen on your preferred port (we will use 8080).

The Pi4J library will need root privileges in order to control the GPIO pins, so Tomcat must run under the user root and under the group root. On the Raspberry Pi edit your /etc/default/tomcat7 configuration file. Find  the TOMCAT7_USER and TOMCAT7_GROUP variables and make sure they are both set to root:

    • TOMCAT7_USER=root
    • TOMCAT7_GROUP=root

Restart Tomcat: service tomcat7 restart

 

Steps to write the Java web application which listens to web browser requests and communicates with the Raspberry Pi’s GPIO pins

Step 1: Create a new Vaadin project.

In Eclipse go to File -> New -> Other… and on the window that comes up select Vaadin/Vaadin 7 Project (or Vaadin/Vaadin 6 Project or whatever other version you have installed).

Vaadin-GPIO-Project-01---Create-new-Vaadin-project

On the Next page enter a name for your new project (we will use RaspberryPiGPIOExample01). Make sure that your Configuration and Vaadin version are set correctly, than hit Finish.

Vaadin-GPIO-Project-01---New-Vaadin-project-settings

Step 2: Add the Pi4J library to your web application.

    • Download Pi4J from here. If you choose the Direct Download option (easiest), you will receive a zip file. Look inside it and find pi4j-core.jar (for example in pi4j-0.0.5-SNAPSHOT/lib/pi4j-core.jar).
    • Using your file manager of choice, copy the pi4j-core.jar file into your newly crated project’s WEB-INF/lib directory. For example if your Java work space root directory is called JavaWS, then you need to copy the Pi4J file into JawaWS/RaspberryPiGPIOExample01/WebContent/WEB-INF/lib/ (obviously you will have to use here the project name that you have chosen in the previous step).
    • In the Eclipse Project Explorer select the root of your newly created application and refresh it (F5). The Pi4J JAR file should show up under WB-INF/lib.

Step 3: Check out the default Vaadin application code that has been generated automatically. In Eclipse open the Project Explorer and look into your project’s folder, inside Java Resources/src. Open your project’s .java file. You should find something like this:

Vaadin-GPIO-Project-01---The-automaticall-generated-Vaadin-code

Notice that the init() method, which initializes the Vaadin user interface has been generated and that it already contains a label which says “Hello Vaadin user“. We will replace this label with our button which toggles the LED on/off.

Step 4: Write the code which will allow us to control the LED through the Raspberry Pi’s GPIO pin 0. This is how your code should look like:

code_RaapberryPiGPIOExample01

The code can be downloaded from here.

The first essential step in controlling our LED is to acquire an instance of the Pi4J GPIOController class, which will send the signals to the Raspberry Pi‘s GPIO pins:

GpioController gpioController = GpioFactory.getInstance();

Through this instance of the GPIOController we can now initialize (provision) a GPIO pin:

final GpioPinDigitalOutput pin =
gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_00, “MyLED”, PinState.LOW);

We use pin 0, we give it the name “MyLED” and we set it’s initial state to LOW (off)

Now all we have to do in the Vaadin button’s click event handler is to toggle the state of our LED:

pin.toggle();

That’s it! You application code is now ready.

 

Deploying your web application

Step1: Export your web application from Eclipse (File -> Export…) into a WAR file:

Vaadin-GPIO-Project-01---Export-WAR-file

On the Next page make sure that it has the same name as your project and hit Finish:

Vaadin-GPIO-Project-01---Export-WAR-file-settings

Step2: Copy the WAR file to the webapps folder of Tomcat (/var/lib/tomcat7/webapps) onto your Raspberry Pi. For this purpose you can use WinSCP for example.

Step3: Restart Tomcat. This step is most likely not needed, but just in case…

service tomcat7 restart

Give it a minute or two to restart properly.

 

Testing your web application

Your application should now be ready to use. Open a web browser and type in the address bar the following line:

YourDomainOrYourIP:TomcatPort/YourWebApplication

Substitute the values with your own. Examples:

example.com:8080/RaspberryPiGPIOExample01

1:1:1:1:8080/RaspberryPiGPIOExample01

Be patient the first time you load your application, it will take a few seconds.

You should be able to see in your browser an “On/Off” button. Clicking it should turn the LED which is hooked up to the Raspberry Pi‘s GPIO pin 0 On/Off.

Have fun!

 

Downloads

 

Programming the Raspberry Pi’s GPIO pins from command line and Bash script

There are many ways to program the GPIO pins of the Raspberry Pi. The original intent of the Raspberry Pi foundation, back when they designed the Pi, was to make it programmable through Python. And that is one possibility, but people have come up since with ways to control the GPIO pins from C/C++, Java, Ruby, Perl and many other languages/technologies. One of the most surprising, elegant and simple ways to talk to the GPIO pins is from the command line, or if you want to do something more complex, from Bash scripts. For this we have to thank Gordon Henderson, author of the WiringPi library, who also freely supplies with it a command line utility simply named gpio.

The WiringPi library was developed to allow GPIO communication from C/C++ in a style similar to the Arduino Wiring programming language and many wrappers for WiringPi have been created since, which allow us to use other programming languages too for this purpose. But if you want to keep it simple, you can just use the gpio utility to issue simple commands which set the pins to input, output or even PWM mode, to read values from the GPIO pins or to write values to them. For example, let’s say that you want to light up an LED connected to GPIO pin 5 (WiringPi numbering). With two calls to the gpio command line utility you can set the pin mode to output and the pin value to HIGH:

gpio mode 5 out

gpio write 5 1

To turn the LED off:

gpio write 5 0

To read the value of a pin, set it to input mode and get its value:

gpio mode 5 in

gpio read 5

As simple as that! For a detailed description of the gpio utility‘s capabilities visit it’s official page here.

The best part is that, just like any other regular commands, the calls to the gpio utility can be combined in any way to write more advanced shell scripts, and this way it is possible to develop some quite complex functionality. Let us mention, however, that from a performance point of view it’s not a great idea to implement such complex GPIO control in shell scripts, because the speed of the Linux shell and that of the gpio utility is not so great and the scripts can keep the CPU quite busy. On a device like the Raspberry Pi this actually might matter. If your software is more complex and needs good performance, consider some other programming language. you might use the WiringPi library for example from C or C++ and there should be no major difference in the way you can control the pins compared to how you do it with the gpio utility.

Note that before you can control the GPIO pins from command line or from shell scripts, you will need to install the gpio utility on your system. Follow the author’s instructions provided here.

 

Monitoring the used disk space with GPIO-controlled LEDs

A simple example of how we can program the Raspberry Pi’s GPIO pins from a Bash script in order to create a useful utility is the used disk space monitor script. We will use a Bash script which periodically checks how many percents of the disk space is used from a partition, and lights up a green, yellow or red status LED based on the value. For the sake of this example we will light up the green LED if 50% is used at most, we will light up the yellow LED if the used space is between 50% and 80% and we will light up the red LED if more than 80% is used. These limit values can easily be changed in the script, just like the name of the monitored partition, for which we will use dev/root.  The default poling interval is 5 seconds, but it would probably make sense to set it to higher values (60 seconds for example) if the monitored disk is unlikely to become full very fast. The script is designed to run forever, so it needs to be stopped manually (CTRL+C) when no longer needed, but this behavior can easily be changed by modifying the condition of the while loop from always true to something that can actually change.

The three status LEDs (green , yellow, red) will be connected to the GPIO pins 0, 1 and 2 (WiringPi notation) through resistors of appropriate values (we will use 330 Ohm resistors for this example). This is how the wiring diagram looks like:

Raspberry Pi model B controlling 3 LEDs

Raspberry Pi model B controlling 3 LEDs

 

Below is the Bash script which does all the “magic” by issuing several calls to the WiringPi gpio utility (which will actually communicate with the hardware):

#! /bin/bash

#Parameters
diskToCheck=’dev/root’
refreshInterval=5 #Refresh interval in seconds

#GPIO 0 is set to HIGH if the used disk space is between 0%-limit1%
#GPIO 1 is set to HIGH if the used disk space is between limit1%-limit2%
#GPIO 2 is set to HIGH if the used disk space is between limit2%-100%
limit1=50
limit2=80

#Initialize all the GPIO pins to output mode
for i in `seq 0 2`; do gpio mode $i out; done

#Main loop
while (true); do

#Obtain the used disk space percent
usedDiskPercent=`df -H | grep $diskToCheck | awk ‘{ print $5 }’`
usedPercent=${usedDiskPercent%?}
echo -n Used disk space: $usedPercent%” “

#Set all the GPIO pins to LOW
for i in `seq 0 2`; do gpio write $i 0; done

#Set the appropriate GPIO pin to HIGH depending on the used disk space
highPin=0
if [ $usedPercent -gt $limit1 ]; then
if [ $usedPercent -le $limit2 ]; then
highPin=1
else
highPin=2
fi
fi
echo Setting pin $highPin to HIGH
gpio write $highPin 1

#Suspend until next cycle
sleep $refreshInterval

done

You may also download the bash script from here.

 

Connecting to the GPIO pins of the Raspberry Pi

Raspberry Pi - Connecting to GPIO
One of the most exciting features of the Raspberry Pi is the presence of the GPIO pins, which makes it possible to connect the Pi to some custom hardware which could otherwise not be able to communicate with it on standard ports. They are basically some general purpose pins, which you can control from software arbitrarily. They can be used as input, to read information from other devices, such as sensors, for example, or they can be used as output to send signals to external hardware, such as LEDs, motors, speakers, etc. Some of the GPIO pins also have dedicated functions, allowing the Raspberry Pi to communicate with other hardware through some standard protocols (serial communication for example; they can be used as SPI or I2C lines).
In order to be able to connect to the GPIO pins of the Raspberry Pi, we’ll need to clarify where those pins are exactly. We will also have to find a way to unambiguously identify the pins, so we will assign numbers to them and we will refer to them using these numbers. Both (A and B) original models have a total of 26 GPIO pins, organized into one pin header, named the P1 header. The newer Raspberry Pi (model B revision 2) adds 8 more GPIO pins in a new pin header called P5, but they are not the same male pins sticking out of the board that we can find on the P1 header, instead they are some little rings to which one can solder wires, so they target more advanced users, with more serious hardware and soldering skills.
Raspberry Pi Model B Revision 2 GPIO Headers

Raspberry Pi Model B Revision 2 GPIO Headers

Not all the GPIO pins are programmable. Some of them are 5.0 VDC or 3.3 VDC positive power pins, some of them are negative ground pins and a few of them are marked DNC (do not connect). The P1 header has 17 programmable pins and the P5 header adds 4 more.
The following two images show how the pins are organized on the P1 and P5 headers and the numbering of the programmable pins according to the WiringPi numbering scheme (Wiring Pi is a project which makes it possible to program the Raspberry Pi‘s GPIO pins in C/C++ in a style similar to the that of the Wiring programming language used with Arduino. The author of WiringPi, Gordon Henderson, has come up with an abstract numbering of the GPIO pins which makes it easier to identify them. This is called the WiringPi numbering scheme). We will use this numbering scheme to refer to the GPIO pins. The below two images were kindly provided by Pi4J.com (Pi4J is a project based on WiringPi, which aims to offer a nice way to program the Raspberry Pi‘s GPIO pins in Java).
Raspberry Pi P1 Header

Raspberry Pi P1 Header – Image courtesy of Pi4J.com

Raspberry Pi P5 Header

Raspberry Pi P5 Header – Image courtesy of Pi4J.com

 

A more advanced description of the Raspberry Pi’s GPIO pins and of their usage can be found here.

 

Limitations

The maximum amount of current that can be safely drawn from a Raspberry Pi GPIO pin is 16 mA, but the total current drawn from all the pins may not exceed 51 mA. If these limits are exceeded, the GPIO pins may burn out or even the whole Pi may become damaged!

 

Example

So let’s see a simple example: How to connect an LED to a programmable GPIO pin on the Raspberry Pi i order to be able to control the LED from software running on the Pi.

We will use a standard red LED, which has a forward voltage of 2 V and we will connect it to the 3.3 V power pin of the Raspberry Pi. To protect the LED, we will include a 330 Ohm resistor in series with it. As you can calculate it using the LED calculator, this will result in a 4 mA current going through the LED. You may safely allow up to 16 mA of current to go through the LED, so you can use resistors down to 82 Ohms. For non-red LEDs which may have a different forward voltage rating, you may have to use resistors with different values.

The programmable GPIO pin 0 (according to WiringPi numbering) will be set to output mode. Whenever the pin is set HIGH from software, the LED will light, whenever the pin will be set LOW, the LED will stay off.

Raspberry Pi model B controlling one LED

Raspberry Pi model B controlling one LED

The above illustration was created with a great tool named Fritzing.

 

WordPress on Raspberry Pi

WordPress on Raspberry Pi

WordPress is a software that allows users to create nice, content-rich websites or blogs. It is a very popular, widely used, free, open-source content management system. What makes it well organized, and yet flexible, is that it combines a template-based approach with a plug-in system which can extend the basic framework with virtually limitless functionality.

However, WordPress is only the software used to create and manage the content, in order to really have an online, functioning website, it needs to be hosted on a server. This is where the question pops up: what is the best place to host a WordPress site? There are mainly three answers to this question, three alternatives, each one with its advantages and disadvantages:

  1. The most common place to host a WordPress website/blog is wordpress.com. The great thing about this option is that it’s free and that the hosting is fully integrated with the WordPress software, which means that you can just sign up and get a WordPress website up and running in a matter of a few clicks. What is not so great about it that if you choose this option, the flexibility of the WordPress software will be restricted by the fact that on wordpress.com you can only use a few templates that they offer. That may not sound so bad, but it is. The functionality of WordPress software greatly depends on what the used template can do, so if you have more a less advanced template, you won’t be able to do so much. It will very soon become frustrating that you cannot customize many things and that some creation tools are not available. There are more advanced templates that you can buy from wordpress.com, but you still won’t have the freedom to do anything you like.
  2. Another option is to just download the free WordPress software and host your site on a rented server by purchasing a hosting package from some company. Hosting services are relatively cheap nowadays and if you choose a good one your site will most likely be hosted on ultra-fast computers, which will guarantee good performance. Performance actually is an important factor in case of WordPress because the system can be quite heavy and can require some powerful hardware in order to deliver a smooth user experience. Using a hosting service will also guarantee that your website will have minimum downtime and the data will never be lost because of, say, damaged hardware. Most hosting services will have all the required other software installed which is needed by WordPress to run and you will be able to customize your site freely by using any template you can get (and there are many good ones out there, even for free). A not so significant disadvantage can be that you will not be able to use quite any tools to configure your server, to upload content to it, etc. You will be limited to what the hosting company uses.
  3. The third and most flexible option is to host your WordPress site on your own server. The hardware and the software will both fully belong to you and you’ll both have them at hand all the time, so you can do with them anything that crosses your mind at any time. Of course, this introduces problems like making sure you have a static IP address, a speedy enough internet connection, which is always up, a server machine which is running all the time and doesn’t break down, no power blackouts or something to compensate for them (a UPS unit or generator for example) and so on. In other words, this complicates things from a hardware point of view. Hosting your site on your own hardware is a very cool thing and offers you endless flexibility but you must make sure that the hardware functions and connects to the Internet properly 24/7. There were also other problems related to own servers until recently: you needed a computer to run all the time, which consumed  much power (which probably cost more than a hosting plan) and it needed a place in a building, a place where it bothered nobody with the noise it was making. So you had to be really motivated to keep a sever in you room at home if you had no other place for it. This last category of problems has been recently solved when the Raspberry Pi became available. The Raspberry Pi is small, it can be fitted anywhere in your house  it consumes so little power that you will never notice the difference and it is completely fan-less, with no moving components, so it makes absolutely no noise. Now that certainly opens up a whole new world of options. Now you can host your WordPress site on your own Raspberry Pi sever! Of course, you still have to guarantee that it runs all the time and that it has a good, permanent Internet connection. That might not be a big problem in most cases. there is, however, another aspect, which might complicate thing when using the Raspberry Pi with a WordPress website: the Pi has relatively limited hardware resources, it is not very fast and it has little memory, which can be a problem because, depending on the used template and on the managed content, WordPress tends to become resource-hungry. There are ways to attenuate this problem and the Raspberry Pi can successfully be used to host WordPress sites. In the following we’ll look at how this can be achieved.

 

Installing WordPress on the Raspberry Pi

  1. The very first step is to transform your Raspberry Pi into a LAMP server. This is required because WordPress is built upon PHP and MySQL and you will also need an HTTP sever, like Apache, for the site to work. Detailed instructions on how to achieve this can be found here.
  2. The second step is to download the free WordPress software from the official site: wordpress.org. The latest version can be acquired from here.
  3. The third step is to install WordPress on your Pi and do a basic configuration for it to get it working. the official WordPress website has a very good, detailed, step-by-step guide about how this can be done. Following the steps should give you a fully working WordPress website in about 10 minutes and it requires only very basic Linux operation skills, as everything is explained in detail.

 

Optimizing WordPress for the Raspberry Pi

If you have followed the installation steps above, you should have at this point a fully working WordPress website on your Raspberry Pi. However, as soon as you start adding some content to it (a few posts and pages), especially heavier content (images, plug-ins), you will notice that the performance of the website is becoming unacceptable. The loading time of the posts/pages will start to become unbearably long, which will not only annoy you, but also your readers and the search engines will start penalizing your site.

In order to avoid having a sluggish website, we need to make some optimizations. There are many ways to go about this but the keyword is mainly caching. This is because the Raspberry Pi’s processor isn’t particularly fast and the SD card‘s reading speed is also quite low (I think the theoretical limit is 30 MB/s). Caching the elements of your website will allow the Pi to serve your pages a lot faster from memory.

The easiest way to cache the elements of your WordPress website is to use a WordPress caching plug-in. there are a few really good ones out there. The one I have found to work best is WP Super Cache, which reduced the loading time of my pages to about 20% (5 times faster!) after the first access.

In order for WP Super Cache (or other caching plugins) to work, you will first need to switch to a custom permalink format. Read here how to do that.

After installing WP Super Cache, you should go to Plugins/Installed Plugins in your WordPress control panel and click on “Settings” below the caching plug-in. Here are a few settings that I have found to work well:

    • On the “Easy” tab enable the caching (Caching On)
    • On the “Advanced” tab
      • Check the “Cache hits to this website for quick access” box
      • Choose the “Use mod_rewrite to serve cache files” option
      • Check the “Compress pages so they’re served more quickly to visitors” box
    • Expiration options:
      • Cache timeout: 86400 seconds (24 hours)

Besides optimization on a software level, there are a few things that you can do with the hardware too, in order to obtain better performance:

    • Get the newer Raspberry Pi, model B, revision 2, with 512 MB of memory, not the types which have only 256 MB of memory.
    • Use raspi-config from command line to give the system as much memory as you can (by taking it away from the GPU, which will not need it anyway because your Pi sever is probably not going to run much in graphical mode). Leave the minimum amount of memory for the GPU (16 MB for example) and give the rest to your server-related applications.
    • Overclock the Pi’s processor. By default it runs at 700 MHz, but it can be overclocked without much risk even up to 1000 MHz. You can change the processor frquency using raspi-config.
    • Use a fast SD card, preferably one that can achieve 30 MB/s transfer rates.