Test Your Reactions - Hardware Projects - Raspberry Pi Projects (2014)

Raspberry Pi Projects (2014)

Part III. Hardware Projects

Chapter 9. Test Your Reactions

by Dr. Andrew Robinson

In This Chapter

• Getting started interfacing hardware with the Raspberry Pi

• Working with basic electronic circuits

• Getting started with electronic components, including transistors and resistors

• Wiring up a switch and an LED

Think you’ve got fast fingers? Find out in this chapter as take your first steps in hardware interfacing to build a reaction timer. You’ll program the Raspberry Pi to wait a random time before turning on a light and starting a timer. The timer will stop when you press a button.

Welcome to the Embedded World!

For some people the idea that computers aren’t always big black or beige boxes on desks is a surprise, but in reality the majority of computers in the world are embedded in devices. Think about your washing machine – to wash your clothes it needs to coordinate turning the water on, keeping it heated to the right temperature, agitating your clothes by periodically spinning the drum, and emptying the water. It might repeat some of these steps multiple times during a wash, and has different cycles for different types of fabric. You might not have realised it’s a computer program. It takes inputs from switches to select the wash and sensors that measure water temperature, and has outputs that heat the water and lock the door shut, and motors to turn the drum and open and close valves to let water in and out.

image

Take a moment to consider the number of appliances and gadgets that need to measure inputs, do some processing to reach a decision and then control an output in response.

A modern kitchen is crammed with computers that watch over and automate our appliances to save us effort. Computers aren’t just embedded in practical products either; they’re in electronic toys and entertainment devices. After working through this chapter and the other examples in this book you’ll be on your way to designing your own embedded systems to make your life easier, or entertain you.

Before you get too carried away connecting things up it’s worth considering a couple of warnings that will protect you and your electronic components.

Good Practice

Electricity can be dangerous, so it is important to use it safely. The muscles in your body are controlled by tiny electrical signals, and these can be affected if electricity flows through your body. Your heart is a muscle that can be stopped by an electric shock.

The flow of electricity can cause heating, which will either cause burns to your body (sometimes deep within tissue) or can cause a fire.

image

Electricity can kill! Only experiment with low voltages and currents, and never work with mains. If you are ever in doubt, then you should check with someone suitably qualified.

Hardware is less forgiving than software; if you make a mistake with code, you might get an error, the program might crash, or in rare cases you might cause your Raspberry Pi to reset. If you make a mistake in hardware, then you can cause permanent damage. As such, hardware engineers tend to check and double-check their work before applying the power!

When experimenting you should beware of short-circuiting your projects. Make sure that nothing conductive touches your circuit. Tools, metal watchstraps and jewellery, unused wires, spare components and tin foil have all been known to damage circuits – keep your working area clear of anything you don’t need and make sure that nothing metallic can accidentally touch your Raspberry Pi or circuit.

Static Discharge

You may have felt a small electric shock due to static sometimes. This occurs when a charge builds up and then discharges to a conductor, which you feel as a small shock. If you are holding a component when this happens, that large voltage will flow through the component and may damage it. Other objects such as plastic can become charged too and then discharge through a component. As such, you should take care to avoid this static discharge through components or circuits. In industry, conductive work surfaces and wrist straps are earthed to prevent static buildup. This may be an extreme solution for a hobby; you can discharge yourself by touching something earthed like a water tap, and avoid working on surfaces that are prone to picking up static charge like plastics – for example, avoid working on nylon carpets or plastic bags.

image

You may have noticed components are supplied in antistatic bags, or static-dissipative bags or static-barrier bags. These bags are made from special plastic designed to protect the contents from being zapped by static discharges and conduct any charge away. Beware that some of these bags can be slightly conductive and so may interact with your powered-up circuit.

Obtaining Components

Another difference with hardware is that you can’t download everything you need from the Internet! However, you can do the next best thing and order parts online. There are a number of online electronics retailers that supply parts, including the two worldwide distributors of the Raspberry Pi, element14/Premier Farnell/Newark and RS Components. Pimoroni, SparkFun, SK Pang, Cool Components, Adafruit and other web stores have a smaller range but cater well to electronic hobbyists.

Maplin Electronics and Radio Shack have shops on the high street with a smaller selection of parts.

An Interface Board

Although the Raspberry Pi has a general purpose input/output (GPIO) connector that you can connect to directly, as a beginner, it is easier to use an add-on board. An interface board can offer some protection to your Pi against burning out if you get your wires crossed!

PiFace Digital

This chapter uses the PiFace Digital interface because it is very easy to use. PiFace Digital has eight LEDs on it so that you can start controlling hardware without any electronics knowledge. Later in this chapter you’ll connect your own LEDs and switches to PiFace Digital with the screw terminals. Hopefully you’ll go on to use more advanced boards, and eventually you may want to design an interface board of your own!

image

In computing, digital refers to things that can either be on or off – there’s no in between. In contrast, analogue devices have many points between their maximum and minimum values. A button is digital in that it is either on or off. A temperature is an example of something that is analogue.

Setting up PiFace Digital

PiFace Digital communicates using Serial Peripheral Interface (SPI) bus. It’s a standard means of connecting peripheral devices to microprocessors. Before you use PiFace Digital with the Raspberry Pi you need to install some software.

SPI

SPI consists of four wires to communicate data from a master (the microprocessor) to a slave device (the peripheral). Data is sent serially (that is, the voltage on a wire is switched on and off to communicate a binary number) over time using four wires as shown in Figure 9.1.

Figure 9.1: Example SPI transaction: The microprocessor sends data 11011101, and the device sends 11110011.

image

• One wire is used for data from the master to the slave (named master output slave input [MOSI]).

• Data going to the master from the slave is sent on another wire (named master input slave output [MISO]).

• The serial clock (SCK) wire is used to synchronise the master and slave so they know when a valid value is being sent (that is, that MISO and MOSI have momentarily stopped changing).

• The slave select wire, or sometimes called chip select (SS or CS), selects between multiple slave devices connected to the same MOSI, MISO and SCK wires.

Installing PiFace Digital Software

Chapter 1, “Getting Your Raspberry Pi Up and Running”, mentions drivers that the operating system loads. These make it easy for programmers to write code to interact with hardware devices. Rather than bloat the operating system with drivers for every possible type of hardware, Linux has driver modules. These are loaded separately when needed. As PiFace Digital talks over SPI you need to ensure that the SPI driver is loaded so the Raspberry Pi hardware sends the correct electrical signals on the expansion pins. You will also need to install a Python library that makes the SPI driver easy to use from your Python code.

It is possible to install PiFace Digital software on Raspbian as a Debian package with one command. However, in the future you might need to install software that isn’t packaged, or perhaps want to use PiFace Digital on a different distribution that doesn’t use Debian packages. As such the following steps show how to manually install software from the source.

Loading the SPI Driver Module

Check to see if the SPI driver is loaded. Type lsmod to list all modules. If it is loaded, you will see the following line. Don’t worry about the numbers on the right; it is the module name spi_bcm2708 which is important.

spi_bcm2708 4401 0

If it is not listed, you need to enable the module. Although the driver module is included, Linux “blacklists” some modules so they are not loaded. To un-blacklist the module, edit the file /etc/modprobe.d/raspi-blacklist.conf. You can insert a # in front of the line blacklist spi-bcm2708 to comment it out, or delete the line completely. Use your favourite editor to edit the file, such as leafpad, nano or vi. For example, you use nano by typing the following:

sudo nano /etc/modprobe.d/raspi-blacklist.conf

Enter # at the start of the line blacklist spi-bcm2708 like so:

#blacklist spi-bcm2708

Save the file. If using the nano editor, press Ctrl + X and then confirm that you want to save the file before exiting.

image

Commenting out is a way of making the computer ignore what is on that line. It works by turning the line into a comment. Comments are text intended for the user and not interpreted by the computer.

It is better to comment a line out rather than delete it as it makes it easier to restore later by uncommenting (that is, removing the comment marker). Python also uses # for comments, so you can temporarily remove a line of code by putting a # at the start of the line.

Restart the Raspberry Pi by typing sudo reboot.

After reboot log in and type lsmod again, and you should see spi_bcm2708 listed. Programs send a message over the SPI bus by writing characters to a special file. Type ls -la /dev/spi* to check whether the special file exists. If you’re successful, Linux will show at least one file. If you receive a message such as No such file or directory, you need to check that the SPI driver module is functioning correctly.

Installing Python Modules

With the spi_bcm2708 module loaded, Linux can talk SPI to peripherals. The next step is to install programs that will make the driver easier to use and send the correct messages over the SPI bus to control the hardware:

1. Make sure that the Raspberry Pi is up to date. Because the Raspberry Pi will check the Internet for updates, you need to make sure that your Raspberry Pi is online. Then type sudo apt-get update.

Wait until Linux downloads and updates files, which can typically take a couple of minutes.

2. Install the necessary packages by typing sudo apt-get install python-dev python-gtk2-dev git.

Linux will list any other programs necessary and tell you how much additional disk space is required. Confirm that you want to continue by typing Y and pressing enter. After a few minutes the programs will be installed.

3. Type cd to return to your home directory and then get the latest software to control PiFace by typing the following:

git clone https://github.com/thomasmacpherson/piface.git

This will copy the latest PiFace code and examples into your home directory. Type ls piface to list the contents of the directory that have just been downloaded.

Git and Source Code Management

Git is a source code management (SCM) system that keeps track of different versions of files. SCMs are necessary when multiple people work on the same project. Imagine if two people were working on a project and changed the same file at the same time. Without SCM the first person’s changes might get overwritten by the second. SCMs instead help manage the process and can merge both contributions. They also keep previous versions (like wikis do) so it’s possible to go back.

Git was initially developed by Linus Torvalds for collaborative development of the Linux operating system but then used by many other projects. There are other SCMs such as SVN, CVS and Mercurial, which provide similar functions.

GitHub (http://github.com) is a website that hosts projects using Git. It’s designed for social coding, so everyone can suggest changes and contribute to improving a project. As the Raspberry Pi has such a strong community, there are many projects on GitHub (including the code for Linux itself) for the Raspberry Pi that everyone can contribute to.

GitHub offers free accounts and tutorials so as you become a more proficient coder, you might as well try using source code management for your project. It can be really useful if you start working with a friend or want to go back to a previous version of your code.

4. So that all users of the Raspberry Pi can use the SPI bus, you need to change the permissions on the /dev/spi* files. PiFace Digital provides a handy script to set SPI permissions. Run the script by typing

sudo piface/scripts/spidev-setup

5. Restart by typing

sudo reboot

Lastly, you need to install the Python modules that will make it easy to send the correct messages on the SPI bus.

6. Log in again and type cd to get back to the home directory.

7. Change the directory to the piface directory and then the python directory by typing cd piface/python.

8. Install the Python module that talks to PiFace Digital by typing sudo python setup.py install. After a few minutes the necessary files will be installed, and you will be ready to start testing with real hardware.

9. Finally, shut down the Pi and remove the power before connecting the PiFace interface by typing sudo halt.

image

It is useful to know how to install software manually, but if in the future you want to install PiFace Digital with one command, instructions are provided at www.piface.org.uk.

Connecting PiFace Digital

Disconnect the power before connecting or disconnecting anything to or from the Raspberry Pi. This ensures that you don’t accidentally short anything and is generally safer. Position PiFace Digital so it lines up with the edges of the Raspberry Pi and check that all 26 pins of the expansion port line up with the holes in the connector. Gently push the PiFace interface down, making sure that you don’t push sideways to bend the pins. If it is correctly lined up, it should slide smoothly. Connect the power, log in and start X, as described in Chapter 1.

Using the Emulator

This book mentions the importance of regular testing and checking that subsystems work before moving on. This is a great excuse for turning some lights on and off. There’s something satisfying about seeing a computer responding to you, lighting a light, obeying your command! Next you will use the PiFace emulator to check that your Raspberry Pi can talk to your PiFace Digital.

Start the emulator by typing piface/scripts/piface-emulator in a Terminal window. The emulator window will appear as shown in Figure 9.2.

As you want to manually control the outputs, in the PiFace Emulator window click Override Enable.

Toggle Output Pin 1 on by clicking it. The PiFace interface will click as the relay turns on, and the corresponding LED will illuminate. Notice the graphic on-screen updates to show the LED being on, the contacts have changed over on the relay and the first output pin is on.

Try turning multiple output pins on, and notice how the on-screen display updates. Try the All On, All Off and Flip buttons to discover what they do.

Figure 9-2: The PiFace Emulator.

image

When you are finished flashing lights and trying the various options close the emulator. You’re now ready to program your Raspberry Pi to take control!

Interfacing with Python

You first meet the Hello World program in Chapter 2, “Introductory Software Project: The Insult Generator”. The hardware equivalent of Hello World is flashing a light, which similarly, although not exciting in itself, is the first step in getting a computer to start controlling the world. After you’ve mastered this, there’s no limit to what you can start controlling!

Turning a Light On

First, write the code to turn an LED on:

1. Double-click IDLE to begin entering code interactively.

2. Type the following:

import piface.pfio as pfio

pfio.init()

pfio.digital_write(0,1)

3. The first LED should be lit.

image

Chapter 2 mentions that there are two versions of Python – Python 2 and Python 3. Similarly there are two versions of IDLE; IDLE (used in this book) that corresponds to the Python 2 command python and IDLE3 that corresponds to Python 3.

The import statement tells Python to use the piface.pfio module so it can talk to the PiFace interface. You must call pfio.init() to check the connection and reset the PiFace hardware. The digital_write(outputpin,value) function takes outputpin, which selects the LED, and value, which determines if it is turned on. So digital_write(0,1) sets the first LED to have the value 1 (on). This function will be familiar if you have ever programmed the Arduino.

image

Computers start counting at 0 as this makes some operations and calculations more efficient. You should see why as you learn more about computers and programming.

Flashing a Light On and Off

Next, you’re going to write a program that flashes the LED with a timer:

1. Create a new window in IDLE by going to the File menu and clicking New Window.

2. Type the following:

from time import sleep

import piface.pfio as pfio

pfio.init()

while(True):

pfio.digital_write(0,1)

sleep(1)

pfio.digital_write(0,1)

sleep(1)

3. Go to the Run menu and choose Run Module (or press F5).

4. Click OK when Python displays the message Source Must Be Saved.

5. Enter a filename and then click Save.

6. You will see a message saying RESTART, and then Python should run your code. If an error message appears, go back and correct your code and try running it again.

You’ve now written the hardware equivalent of Hello World – an LED that flashes. The next examples will show how to make the Raspberry Pi respond to the world, as you will learn how to read inputs.

image

As an extension, you could try flashing a more complex pattern – change the rate the LED flashes at or try flashing multiple LEDs.

Reading a Switch

For a computer to respond to its environment, it needs to be able to read inputs. First you will use the graphical emulator to display the status of the inputs.

Showing Input Status Graphically

In the emulator, click the Keep Inputs Updated check box as shown in Figure 9.3. The interval sets how often the inputs are read; for most cases, it is fine to leave it on 500ms.

Figure 9-3: Enable the Keep Inputs Updated check box to show the status of inputs.

image

Test the input by pressing one of the buttons on the bottom left of PiFace. As shown in Figure 9.4, the on-screen representation changes to indicate the switch that has been pressed.

Figure 9-4: The status of inputs are shown in the emulator.

image

You can close the emulator for now by clicking the cross in the top-right corner of the window.

Reading Inputs with Code

As you saw earlier, you can control outputs using the function digital_write. Logically, as you might expect, to get the value of inputs, you use the digital_read function. Let’s write a simple example:

1. Type the following Python code interactively:

import piface.pfio as pfio

pfio.init()

pfio.digital_read(0)

Python prints 0.

2. Hold down button number S1 and type pfio.digital_read(0) again.

Python prints 1.

3. Now read the next button along (S2). Type pfio.digital_read(1). Notice how the argument of the function specifies which input to read.

You have seen how easy it is to read an input. Next, you are going to combine turning a light on and reading an input to build a reaction timer.

The Reaction Timer

Now is the time to find out if you’ve got fast fingers by building a reaction timer game.

Type the following code in a new window and then save it as reactionTimer.py:

from time import sleep, time

from random import uniform

import piface.pfio as pfio

#Initialise the interface

pfio.init()

print "press button one when the light comes on"

#Sleep for a random period between 3 and 10 seconds

sleep(uniform(3,10))

#Turn LED on

pfio.digital_write(0,1)

#Record the current time

startTime = time()

#Wait while button is not pressed

while(pfio.digital_read(0)==0):

continue #continue round the loop

#Button must have been pressed as we've left loop

#Read time now

stopTime = time()

#Time taken is difference between times

elapsedTime = stopTime-startTime

#Display the time taken. str is required to convert

#elapsedTime into a string for printing

print "Your reaction time was: " + str(elapsedTime)

#Turn LED off when finished

pfio.digital_write(1,0)

Run the code by pressing F5 from IDLE.

All the lights will go out. Wait until the LED comes on and then press button 0 as fast as you can. The program will print your reaction time.

Next, you’ll see if your reactions are any faster with a big red button as you wire up a simple circuit.

Meet PiFace Digital’s Connections

The PiFace Digital interface makes it very easy to wire up simple digital circuits so that you can connect your Raspberry Pi to switches and actuators like lights or motors in the real world. Figure 9.5 labels the connectors on PiFace Digital.

Figure 9-5: PiFace Digital’s connectors.

image

Electrical Circuits

Modern computers work with electricity, so to interface with them, you need to understand the basics of how it behaves.

Electricity is the flow of tiny particles, called electrons, that carry a charge. Think of electrons as always wanting to get home; for example, with a battery, the electrons want to get back into the other terminal. As the electrons move through components in a circuit on their way home they do work. This work might be to emit light in an LED or move a motor around. If the electrons do not flow, no work is done (and the LED does not shine). Figure 9.6 shows three circuits, but only one has a path for electrons to leave the power source, pass through a component to do work and return home again!

Electronics is all about controlling electrons’ journeys! In many cases it is about making or breaking a complete path for electrons to flow.

In describing circuits, there are a few terms that you may come across:

• Voltage – this is, in electrical terms, how “strongly” the electrons are pulled home – that is, how much work they can do while they flow through the circuit. Think of it a bit like a water wheel and a reservoir. The greater the distance the water falls, the more work it can do turning the water wheel as it flows past. Voltage describes the work that can be done and is measured in volts – for example, an AA battery has a voltage of 1.5V between its terminals. If another one is connected end to end, then there is greater potential to do work, a voltage of 3V.

• Ground, or 0V (or sometimes referred to as negative) – a reference point to measure voltage from. If a point in a circuit is at ground, then it is at 0V, and no work can be done. With the water example, if the water is on the ground, it can’t fall any further so can’t be harnessed to do any work.

• Resistance – how easily the electrons can flow. Different substances allow electrons to flow with different degrees of ease. Conductors, such as metals, have a low resistance and make it easy for the electrons to flow. Insulators, such as plastics, have high resistances, which make it hard for electrons to flow. Different materials resist the flow of electrons by different amounts. Even water has a fairly low resistance, so it will allow electricity to flow through it, which is why you shouldn’t use your Raspberry Pi in the bath!

You can think of these like this: Voltage describes the potential to do work (analogous to the height of water), and current describes the rate electricity follows (the rate of flow of water passing a point). Resistance describes how easily electricity flows through a material – voltage, resistance and current are interrelated – without a voltage existing between two points, no current will flow. The resistance between the two points affects how much current will flow. If you want to know more, look up Ohm’s law online.

Figure 9.6: Electricity needs a complete circuit to flow and do work.

image

Inputs

The screw terminals next to the on-board switches are used to connect external switches. There are eight inputs, numbered 0-7 from the outside of the board to the middle, followed by a connection to ground. PiFace Digital will register an input if there is an electrical connection between the input terminal and ground – that is, there is a path for electrons to flow.

Relays

When you turn either of the first two outputs on you should notice that PiFace clicks. This sound is as the contacts in the relay (the large rectangular components) change over. A relay can by thought of as a computer-controlled switch. You’ll use relays in Chapter 10, “The Twittering Toy”.

Outputs

As well as controlling the on-board LEDs and relays, PiFace Digital has “open-collector” outputs that can be used to control circuits. You can connect to these outputs with the screw terminals next to the LEDs.

The term open collector describes how the output transistor is connected. Transistors are the switches at the heart of computers – there are tens of millions of transistors in the processor at the heart of the Raspberry Pi. Luckily they’re only tens of nanometres (a nanometre is a thousand millionth of a metre – you could fit 2000 transistors across the width of a human hair) in size. Although transistors behave in a similar way to switches and relays, the direction current flows through them affects how they behave, which needs to be considered when connecting to them.

image

There are different types of transistors, which allow current to flow in different ways. For simplicity this chapter just uses examples of the type NPN.

Open-collector outputs can just sink current. That is, they allow current to flow to ground; they are not a source for current. This means that circuits have to be wired up from a power source, through the component being controlled, through the transistor and then to ground. Figure 9.7 shows a typical setup. Remember, current has to flow for electricity to do work, so until the transistor turns on and allows current to flow to ground the LED will not come on. The transistors on PiFace already have the connection to ground wired up.

Figure 9-7: How to wire up an open-collector output.

image

Connecting a Switch and an LED

Enough theory! It’s time to wire up the components. For the example, you’re using a switch that incorporates an LED, but you could use a separate LED and switch. You will wire them up as shown in Figure 9.8.

Figure 9-8: Wiring up the LED and switch to the Raspberry Pi.

image

Making Connections

There are a variety of ways to join wires and components together. Figures 9-9 through 9-12 show different ways of making connections. Important considerations are that the joint is secure and that you have a good connection; otherwise, the joint will create a high resistance or come apart.

• Wires can be twisted together (as shown in Figure 9.9) – this is a quick and easy method, but not very secure. Wrapping insulation tape helps to hold things more securely and prevents other connections from shorting.

Figure 9.9: Twisting wires.

image

• Screw connectors (in some forms, sometimes called choc-bloc) (see Figure 9.10) – these hold wires together under a screw. They’re quick, easy and fairly secure, but are quite bulky.

Figure 9.10: Screwing terminals.

image

• Breadboard, sometimes called binboard (see Figure 9.11) – is great for experimenting. Breadboard has rows of strips of metal that grip and connect wires. Components can be inserted directly into the breadboard, which makes it good for prototyping circuits. Wires are only loosely gripped so they can be pulled out – good for reuse, but not very secure or permanent. Some cheaper breadboards suffer from poor connectors.

Figure 9.11: Using a breadboard.

image

• Solder (shown in Figure 9.12) – this is the most permanent way of making connections. Solder is a mixture of metals and is heated with a soldering iron until it melts and joins the connectors together. It’s also possible to re-melt solder to separate connectors, although this is not always easy without damaging the components. Solder will also only join certain types of metals – for example, it won’t stick to aluminium. Soldering can be a bit tricky at first; it takes a bit of practise to apply just the right amount of heat in the right place to avoid melting insulation, damaging sensitive components or burning your fingers! It’s best to practise to join some scrap components and wire as your first few attempts might be unsuccessful.

It’s best to become familiar with all methods of making connections; then you can use whichever method is most appropriate at the time. And, if nothing else, learning how to solder with molten metal can be fun!

Figure 9.12: Soldering.

image

Cut four lengths of wire 20cm long and strip about 7mm of the insulation off each end. If you are using stranded wire (that is, there isn’t a single core, inside the insulation, but lots of fine strands), twist the strands together with your fingertips.

image

You can “tin” the wires with a soldering iron. This prevents metal whiskers sticking out that can accidentally short, causing undesired connections. To tin wires, twist them together, then run along the metal from the insulation to the tip with a soldering iron on the top and solder on the bottom. Try and get the speed right so just enough solder flows to bind all the strands together.

Connect a Switch

Connect one switch to an input terminal (such as input 0) and the other to the ground (0V) terminal as shown in Figure 9.13. Start the emulator up to show the state of the inputs. Press the button and check that the input is registered. If nothing happens, check your wiring. Note that as pins 0-3 are wired in parallel to the switches, the terminal and corresponding switch indicate together.

Figure 9-13: Wiring up a switch.

image

Connect an LED

You will connect the LED to the open-collector outputs. Remember open-collector outputs cannot supply current; they are essentially a switch that connects the terminal to ground. You'll create a circuit where the current will flow from the 5V terminal, through a resistor (to limit the current so the LED is not damaged) and through an LED and into the output terminal. When the output terminal is turned on it allows current to flow to ground, completing the circuit and illuminating the LED. Remember LEDs only work if current flows through them one way, so it matters which lead you connect to positive. For most LEDs the longer leg indicates the anode, which should be connected to the resistor and then the 5V terminal. A complete circuit diagram is available on the book's website (www.wiley.com/go/raspberrypiprojects).

Some switches with built-in LEDs can safely work at 5V so you do not need a resistor. However, most normal LEDs would be damaged by a voltage of over 2V. If you are using a normal LED, you need to put about a 330Ω resistor in series with the LED. Chapter 8 has more information about using resistors with LEDs. Connect the longer leg of the LED and resistor together and then connect the other leg of the resistor to the 5V terminal. Now is a good time to check if the LED will work. Briefly touch the other lead of the LED, called the cathode, to GND. You should see the LED glow. If not, check your wiring and make sure that you have identified the anode and cathode correctly. (You shouldn’t have damaged the LED if you got the polarity wrong.)

When you know the circuit works, disconnect from the ground and then connect to the transistor via one of the output terminals – such as output 0. When the transistor is turned on, it will allow the current to flow to ground and complete the circuit, so the LED will illuminate. Turn the output on from the emulator and check that it lights.

Playing with the Reaction Timer

Now that you have connected an LED and switch, rerun the reaction timer program. Again the LED should light after a random time, and the switch should stop the timer. Now that you know your wiring and circuit works, you can really start to have fun – try different output devices, wire up a buzzer instead of the LED and see if your reactions to sound are quicker. You could perhaps mount a feather on a motor and test your reaction to touch. You might find this reaction to be quicker. This is because the inputs (nerves in the skin) can send a message to the outputs (muscles) without going through a complicated processing system (your brain) – the principles of computing apply to lots of other systems too! Experiment with different input switches too – you could attach a switch to different parts of your body and see if they respond as fast as your hand.

Have a go at making your own switch! Instead of a pre-made switch, you could wire up pieces of aluminium foil as the contacts and detect when they are connected. Maybe you could make a pressure pad for your foot, or have pieces of foil taped to your knees and complete the circuit by bringing them together.

image

Connect up multiple switches and LEDs and modify the code to make a game. You could have a different score for each button, or deduct points if you press the wrong button at the wrong time. You could build your own game like whack-a-mole.

When you become more experienced at coding, if you are really adventurous, you could create a network version and play against a friend over the Internet.

What Will You Interface?

Computing becomes more interesting when it is connected to the world. Interfacing allows computers to sense and manipulate the world through inputs and outputs. Most computers sense the world by detecting a voltage on an input pin, and affect the world by allowing a current to flow through an actuator such as an LED or motor. Relays can be considered as an equivalent to switches, whereas open-collector outputs have to be wired up in a particular way.

With a basic understanding of electricity and the right sensors and actuators you can make the world a smarter place. As computers become more sophisticated we can build even smarter solutions. In the future, you might build a robot that would listen for your commands. Although that may seem complicated to program, as you have seen, computing is about breaking a challenge down into lots of simple parts, and then each little part becomes solvable.