Raspberry Pi Projects For Dummies book cover

Raspberry Pi Projects For Dummies

By: Mike Cook and Jonathan Evans Published: 07-13-2015

Join the Raspberry revolution with these fun and easy Pi projects

The Raspberry Pi has opened up a whole new world of innovation for everyone from hardware hackers and programmers to students, hobbyists, engineers, and beyond. Featuring a variety of hands-on projects, this easy-to-understand guide walks you through every step of the design process and will have you creating like a Raspberry Pi pro in no time. You’ll learn how to prepare your workspace, assemble the necessary tools, work with test equipment, and find your way around the Raspberry Pi before moving on to a series of fun, lively projects that brings some power to your plain ol’ Pi.

  • Introduces Raspberry Pi basics and gives you a solid understanding of all the essentials you’ll need to take on your first project
  • Includes an array of fun and useful projects that show you how to do everything from creating a magic light wand to enhancing your designs with Lego sensors, installing and writing games for the RISC OS, building a transistor tester, and more
  • Provides an easy, hands-on approach to learning more about electronics, programming, and interaction design for Makers and innovators of all ages

Bring the power of Pi to your next cool creation with Raspberry Pi Projects For Dummies!

Articles From Raspberry Pi Projects For Dummies

8 results
8 results
Raspberry Pi Projects For Dummies Cheat Sheet

Cheat Sheet / Updated 03-27-2016

You can connect your Raspberry Pi to the Arduino and get even more out of both boards, and there are several methods for making this connection. The Raspberry Pi has a variety of GPIO pins that you can use in your projects, but it helps if you know the functions of the various pins. Finally, the Raspberry Pi can power devices in several ways — which can come in handy as you build projects.

View Cheat Sheet
Raspberry Pi GPIO Pin Alternate Functions

Article / Updated 03-26-2016

The general-purpose input/output (GPIO) pins can be switched between input or output and have a pull-up or pull-down resistor enabled, but there are a host of other peripherals in the Raspberry Pi chip that can be switched to these pins. You can see the basic arrangement for one pin, GPIO 18. All the other pins have a similar arrangement but with different blocks to select from. The numbers on the switch are the three-bit register value that have to be set in the collection of alternate function select registers. Note that the Alt numbers have little relationship to the bit patterns you actually set. Although there are 54 GPIO lines in the Raspberry Pi’s processor, only 28 are brought out to the P1 connector on the board (less on the non-plus models); the rest are used for actually making the processor act like a computer (things like the SD card, USB connector, and LEDs). On the B+ and A+ models, you have the first 28 GPIO pins; on earlier models, you have a subset of these. Most diagrams you find give you only a selection of these alternate functions. Here, you can see all the alternate functions and where they appear on the GPIO connector. The first thing to spot is that there are two types of “nothing here”: One is blank and the other is labeled as . It’s likely that these reserved functions are used for factory testing of the chip or for functions not disclosed in the data sheet. The blank ones are simply not implemented. For the full gory tale, the BCM2835 ARM Peripherals document is where you want to look, but here’s a quick look at some of the functions: ALT 0: Where most of the interesting and useful alternate functions are as far as the Raspberry Pi is concerned. The SDA and SCL 0 and 1 are the two I2C buses, and the TXD0 and RXD0 are the serial connections. The GPCLK lines are a general-purpose clock output that can be set to run at a fixed frequency independent of any software. The PWM pins provide the two pulse width modulated outputs; the SPI 0 is the serial peripheral interface bus lines. Finally, the PCM pins provide pulse code modulated audio outputs. ALT 1: The pins are used as a secondary memory bus. Due to the design of the Raspberry Pi, this is of no use at all. ALT 2: The only ALT 2 pins brought out the to the GPIO pin header are reserved. ALT 3: The most useful pins here are the CTS0 and RTS0 lines; these are handshaking lines for the serial module if you need them. The BSC lines are for the Broadcom Serial Controller, which is a fast mode I2C-compliant bus supporting 7-bit and 10-bit addressing and having the timing controlled by internal registers. The SD1 lines are probably for the control of an SD card, but the BCM2835 ARM Peripherals document makes no other mention of it. It isn’t the way the Raspberry Pi accesses the SD card anyway. ALT 4: The SPI 1 lines are a second SPI bus. And the ARM pins are for a JTAG interface. JTAG is a way of talking to the chip without any software on it. It’s very much used for the initial tests on a system during development, although it can be used for hardware debugging as well. ALT 5: The useful pins here are the second serial port data and handshaking lines. The PWM lines are exactly the same PWM lines that are switches to GPIO 12 and 13 under ALT 0, only this time they’re switched to GPIO 20 and 21. There are also two of the general-purpose clock lines along with another copy of the ARM JTAG signals.

View Article
10 Great Raspberry Pi Online Resources

Article / Updated 03-26-2016

The Internet is a wealth of information on the Raspberry Pi, some more reliable than others. Here are some extremely useful and reliable sites — ones you’ll want to check regularly: Adafruit: The legendary Limor Fried’s company offerings for the Raspberry Pi. Named after Ada Lovelace, a collaborator with Charles Babbage and all-around mathematical genius. Baking Pi – Operating Systems Development: Direct from the University of Cambridge’s Computing Laboratory comes a comprehensive set of tutorials. The site also contains lots of interesting links to other places. element14 Community: This is the community space of major distributor Farnell/Newark Electronics. It offers news, competitions, tutorials, help, and advice. The standard of advice is excellent — this is not a blind-leading-the-blind website. Hackaday: The skull-and-crossbones logo gives you a hint that this is a hard-core hacking site. It isn’t always the most sympathetic site for the Raspberry Pi because the Pi is aimed at beginners, but even Hackaday users acknowledge the genius things that people do with the Pi. The MagPi: A great free online monthly magazine on the Raspberry Pi. It contains articles ranging from beginner to advanced, and back issues are available for free download. Mike Cook: This is the website of Mike Cook. Here, Mike offers interesting Raspberry Pi stuff and tutorials about electronics. The Pi Store: Here you can download the free Educational User Manual for use in your home or school. Raspberry Pi Blog: The official blog of the Raspberry Pi Foundation. You always get the news here first, along with outstanding projects, videos, and educational activities. The Raspberry Pi Guy: Matt Timmons-Brown is a young guy who produces great video tutorials on most aspects of the Raspberry Pi. This is his site. RasPi.tv: On this YouTube channel, Alex Eames talks about the Raspberry Pi, as well as programming, electronics, and physical computing.

View Article
Facial Recognition on the Raspberry Pi: The Future Today

Article / Updated 03-26-2016

Want your Raspberry Pi to do something cool? The human eye can instantly identify characteristics of an individual that tells us many things about that person, at a glance. Within seconds of looking at someone, you typically know that person’s gender, approximate age, and height, and you may be able to identify who the person is (if you’ve met him before). You form impressions about people by the way they look, what they wear, the way they move, and their facial expressions. The human brain processes all these variables in a matter of seconds. Teaching a computer to do all this has been a focal point of image processing research for decades. Image processing has evolved significantly. Today, a computer can identify facial features like eyes, nose, ears, and the size and shape of the face. These facial metrics (known as biometric data) form a fingerprint-like identifier that is unique to every individual. The creation of facial biometric data was the first step in creating complete recognition. The second step was being able to match the data to a database of biometrics and associate it with an individual’s identity. The human eye can quickly process facial characteristics, but the human brain can store only a few hundred faces reliably. After a while, we tend to forget people’s names and often need to relearn information about people. Computers, on the other hand, excel at storing and matching data. Facial recognition software has evolved to the point where computers can process an image and match it against a database of millions of people in seconds. Law enforcement has led the way with the development of facial recognition systems that can identify criminals against a watch list in real-time. If you’ve traveled through an airport recently, chances are, your facial biometric data has been captured and matched against a watch list. Having your biometric data stored in a database has raised privacy concerns. Storing biometric data without consent has been a topic of discussion and debate for privacy groups for years and, in some cases, had led to the creation of policies to protect a person’s identity. In addition to privacy concerns, there are also fraud concerns. Having your facial fingerprint matched to what is known as metadata (name, address, and Social Security number, for example) is a major identity theft risk. In order to combat this risk, software vendors have created biometric encryption algorithms to encrypt the data within the database and also provide an almost unbreakable link between the biometric data and the metadata. More recently, image processing research has made advances that will open up information contained in images on the Internet. Search engines are starting to be able to identify the content of a picture and not have to rely on text-based metadata tags that need to be manually created by the image owner. Using image processing, a search engine can now search every image on the Internet. Using pattern recognition software, it can identify the content of a picture and automatically create captions like “male child playing with a dog in a park.” Consumer products have also gotten in on the act. Cellphone applications have been developed to be able to take a picture of a scene and instantly match it to a database of scenes that can provide more information on what you’re looking at, as well as overlay information like street name or shop name, for example. Embedded electronic boards, like the Raspberry Pi, now have the processing power required to process facial images in real-time and match them against a watch list. This has made the accessibility of this technology available to hobbyists who can quickly build their own image-processing systems using the Raspberry Pi, a webcam, and some open-source software. Having computer vision on a computer as small as the Raspberry Pi dramatically reduces the footprint of the hardware and opens up new possibilities for how this technology can be deployed. Wearable technology like glasses with cameras and built-in screens are also starting to come to the fore. Who knows? Perhaps someday you’ll be able to walk down the office corridor and not have to remember the name of the person walking toward you. Just by looking at the person, her name could pop up on the glasses screen so you could greet her with her name. Maybe “someday” is today.

View Article
The Lorenz Attractor in RISC OS on the Raspberry Pi

Article / Updated 03-26-2016

Interested in a new Raspberry Pi project? The Lorenz attractor almost singlehandedly originated a whole branch of science chaos theory. It seems fitting that a man who worked for so much of his life in Cambridge, Massachusetts, be remembered for a program that runs on an operating system designed in Cambridge, England. Edward Norton Lorenz was working on systems to predict the weather. He had constructed a simple mathematical model of how the atmosphere convection should behave. It boiled down to a system of three ordinary differential equations. He was using one of the earliest computers in the 1950s to solve these equations by numerical methods because there is no analytical way to solve them. This involved repeated calculations or iterations of values in order to home in on the result. The output of one set of calculations was fed into the input of another. This is a well-known technique first invented by Isaac Newton; the results either home in on the correct answer, getting smaller and smaller, or shoot off into infinity. What Lorenz found was a class of equations that neither homed in on one result nor shot off to infinity but did something in between. It produced what appeared to be a cycling result with the same values repeating in a pattern. However, closer inspection revealed that although the results did cycle, they never repeated — in other words, they cycled without end but stayed within certain bounds. A sort of never-ending, never-repeating finite set of numbers. This pattern of numbers consisted of three values that would change with respect to each other. If you were to use these numbers to plot a position in three-dimensional space, they would describe a line or orbit that never repeated but went on forever. This shape was later christened a fractal, and this class of fractals is known as a strange attractor. No matter what the initial starting conditions were, the equations always ended up on this curve (hence, the name attractor, and because it’s an odd thing to happen, the word strange). The shape of this curve is a twisted figure-eight loop known as a butterfly curve or the Lorenz attractor. In 1969, Lorenz described the butterfly effect, which states that an almost insignificant change in initial conditions (like the beating of a butterfly’s wings) could cause a large change in the outcome of an iterated system. All that Lorenz had to visualize his numbers with was a crude teleprinter, but these days we have high-speed computers with graphic displays Lorenz never dreamed of. It’s comparatively easy to see his curve in more detail than Lorenz ever could. The implementation of the BASIC language in RISC OS makes it easy to write a program to display the Lorenz attractor very quickly and in great detail. This is shown in the following code. 10 : REM The Lorenz Attractor - by Mike Cook 20 : MODE 28 30 : CLS:CLG 40 : PROC_Size 50 : S=Ymax%/80:SX=Xmax%/70:SZ=2 60 : N%=70:F%=0:INC=4E-3 70 : SX%=Xmax%/2:SY%=Ymax%/2:SZ%=0 80 : X=-6.5:Y=-8.8:Z=20 90 : P1=10:P2=28:P3=2.66666 100 : 110 : REPEAT 120 : N%=N%+1 130 : IF N%>200 THEN N%=0:GCOL 0,RND(63) TINT 255 140 : D1=P1*(Y-X) 150 : D2=P2*X-Y-X*Z 160 : D3=X*Y-P3*Z 170 : X=X+D1*INC 180 : Y=Y+D2*INC 190 : Z=Z+D3*INC 200 : PROC_PLOT(X,Y) 210 : TIME=0 220 : REPEAT 230 : UNTIL TIME>0 240 : B%=ADVAL(-1) 250 : UNTIL B%<>0 260 : A$=GET$ 270 : IF A$ ="s" THEN *ScreenSave Attract 280 : END 290 : 300 : DEF PROC_PLOT(X,Y) 310 : X%=X*SX:Y%=Y*S 320 : X%=X%+SX%:Y%=Y%+SY% 330 : IF F% = 0 THEN MOVE X%,Y% ELSE DRAW X%,Y% 340 : F%=1 : REM move only the first time 350 : ENDPROC 360 : 370 : DEF PROC_Size 380 : SYS"OS_ReadModeVariable",-1,3 TO ,,Ncolours% 390 : SYS"OS_ReadModeVariable",-1,4 TO ,,Xfact% 400 : SYS"OS_ReadModeVariable",-1,5 TO ,,Yfact% 410 : SYS"OS_ReadModeVariable",-1,11 TO ,,XLim% 420 : SYS"OS_ReadModeVariable",-1,12 TO ,,YLim% 430 : Xmax%=XLim%< The initial starting positions are given in line 80, and the parameters of the equation are given in line 90. The main loop in the program goes from line 110 to line 280. This simply repeats until you press any keyboard key. If the key you press is an S, then a screen dump is done to save a picture of the screen in sprite format. The loop works by lines 140 to 160 finding the difference in values from the last to the present iteration. The iteration calculation is then scaled with the variable INC, which is set to be 0.004 in lines 170 to 190, and the resultant number is plotted on the screen. Notice how only the x and y values are plotted, giving a view looking into the z-axis. You can change the two variables passed in the PROC PLOT call to be any two values to get a different view on the curve. You can combine the x, y, and z values in this call to give any angle of orthographic projection if you like. For example, making the following changes to the code will give an isometric view of the curve: 42 : C1= 0.707107 : C2 = 0.408241 43 : C3 = 0.816597 : C4 = -C2 200 : PROC_PLOT(C1*X + C1*Z, C2*X + C3*Y + C4*Z) Lines 210 to 230 simply make a time delay, making it longer by increasing the number at the end of line 230 or eliminating it altogether by skipping these three lines. The PLOT procedure itself simply scales the two points and then shifts them to the middle of the screen. Finally, if it’s the first time plotting, it gives a move command; otherwise, it gives a draw from the last point graphics command. The Size procedure gets the size of the screen in pixels so the graph fills the screen, and lines 120 and 130 add a bit of variety by changing the line’s color every 200 points.

View Article
Powering from the Raspberry Pi

Article / Updated 03-26-2016

A common question is “Will the Raspberry Pi power this?,” to which the answerer is always “What do you mean by power?” Basically, there are three ways a Pi can power something and each has a separate answer. Sourcing the power from the GPIO pin The GPIO pins are quite fragile on the Raspberry Pi, compared with other boards like the Arduino. Each GPIO pin can source (provide the current) or sink (suck the current into the pin to switch something to ground) about 16mA. The total amount of current sourced or sunk from all pins added together should be restricted to about 50mA, which spreads out to about 3mA each for the non-plus models. The only thing you should be directly powering from a GPIO pin is an LED, and only with a low current at that. Everything else needs to go through some sort of driver — normally a transistor or FET. Also, the output voltage is only 3V3, so many devices need more voltage as well as more current. Sourcing the power from the Pi This is where the signal to control something is derived from the GPIO pins, but the actual power to drive it is from the 3V3 or 5V internal power lines of the Raspberry Pi. Using the 3V3 supply is tricky because that line is going through the onboard voltage regulators and there is a limited amount of spare current available before you get overheating of the regulators. Don’t take any more than 50mA from this power rail. If you want more, consider using a voltage regulator on the 5V line. Much more promising is the 5V line because it’s derived from the same power source that is powering the whole Pi. Because the Pi takes up to 800mA at peak, if you power the Pi with a 2A supply, you could take about 1.2A from the 5V lines. Parallel up the two 5V pins on the GPIO connector and at least two grounds to reduce the resistance introduced by the connector. But at the upper end of this current draw, expect a bit of voltage droop — you might get a volt or so lost and end up with only about 4V. Sourcing the power from an external supply There are times when you need a voltage higher than 3V3 or 5V to control a device. If this is the case, you need a separate power supply. This means that the ground or –ve terminal of the external power supply must be connected to the ground of the Raspberry Pi. A common fear here is that this will in some way damage the Pi, but as long as it’s only the ground that’s connected, there is nothing to worry about. For example, a typical application might be to drive a 12V relay. The way a transistor works ensures that the 12V does not leak back into the Raspberry Pi. The relay contacts are completely separate from the Pi; this is said to be isolated. Any sort of coil or inductor must have a diode to protect against back EMF; this is a large reverse voltage spike that occurs when the relay coil’s current is removed and the magnetic field collapses. The diode shorts this out and prevents it from causing any damage. The 1K resistor in the base of the transistor ensures that you don’t draw too much current from the GPIO pin. This circuit is applicable to other things as well — for example, instead of the relay coil, you can have a motor.

View Article
Raspberry Pi Projects: LEGO Brick Alternate Language

Article / Updated 03-26-2016

Need a new Raspberry Pi project? You can run quite a few third-party languages on the LEGO brick, but ev3dev puts a cut-down version of Linux on the brick. You don’t need to change anything on the brick because ev3dev runs off a micro SD card inserted into the brick. You can easily revert your LEGO brick back to the original state by simply unplugging the SD card. The bulk of the installation work involves creating the SD card with the Linux distribution on it. It’s sort of like creating the SD card for the Raspberry Pi itself. At ev3dev.org, you can find instructions on creating the SD card under the Mac, PC, or Linux operating system. After you create the SD card, you can plug the brick into the Raspberry Pi. You have to connect the brick directly into one of the Raspberry Pi’s USB sockets (as opposed to a USB hub) in order for it to work. You communicate with the LEGO brick from the Raspberry Pi by using a Secure Shell (SSH) session. Open up a command-line window and set up a session. This is what you’ll see: ssh [email protected] [email protected]’s password: _____ _ _____ _|___ / __| | _____ __ / _ / / |_ / _` |/ _ / / | __/ V / ___) | (_| | __/ V / ___| _/ |____/ __,_|___| _/ Debian GNU/Linux jessie on LEGO MINDSTORMS EV3! The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Wed Nov 5 11:45:33 2014 from 192.168.2.1 [email protected]:~# To Linux, everything is a file, and the LEGO motors are no exception. You talk to them by writing to a file, and you get back information by listing a file. Because this is Linux, the normal command-line prompts still work and you’ll find it useful to use cd to change directory and ls to see what files are at the current directory level. To use this system from within Python, you have to manage an SSH session from within a program. Most people recommend using Pexpect, but you may have more success with Paramiko. Install it using the following: pip install paramiko -–upgrade The following code shows you how to open, run, and close an SSH session from Python. ''' ssh Sesson for EV3dev ''' import paramiko import sys import math, time, os # Create an SSH client ssh = paramiko.SSHClient() shell = " ; debug = True def main(): print"Wait for brick to be contacted" login() print "Now talking to brick" send_command("lsn") # Linux list directory ssh.close() print "Now shutting down" sys.exit() # functions for accessing EV3dev def login(): global shell ssh.load_system_host_keys() ssh.load_host_keys(os.path.expanduser( "~/.ssh/known_hosts")) # Make sure that we add the remote server’s # SSH key automatically ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy()) paramiko.util.log_to_file("ev3brick.log") # Connect to the EV3 brick # change password to your own ssh.connect("10.42.0.3", username="root", password="legobrick9") # Create a raw shell shell = ssh.invoke_shell() wait_for_prompt() send_command("cd /sys/class/tacho-motorn") #makes commands shorter def wait_for_prompt(): # Create a new receive buffer receive_buffer = " while not "#" in receive_buffer: # Get the receive buffer receive_buffer += shell.recv(1024) if debug : print receive_buffer def send_command(command): shell.send(command) receive_buffer = " while not "#" in receive_buffer: receive_buffer += shell.recv(1024) if debug or "-bash" in receive_buffer : print receive_buffer if __name__ == '__main__': main()

View Article
Recognizing and Coping with Contact Bounce on the Raspberry Pi

Article / Updated 03-26-2016

You may need to cope with contact bounce for your next Raspberry Pi project. Reading a switch is quite simple. It returns either a 0 or a 1, depending on whether the switch is pressed. Switches should always be connected between the general-purpose input/output (GPIO) input pin and ground and either enable the internal pull-up resistor or fix an external resistor to them. When a switch is closed, it makes a path to ground. You read a logic low or zero when this path is made. You may see other arrangements where a switch is connected between the GPIO input pin and 3V3, but this is not recommended because switches are normally on long wires. Routing long wires connected to ground is less risky than connecting to a power voltage. This is how you wire a switch. Although a switch to ground with a pull-up resistor to a high voltage can read only 1 or 0, most switches are a little more complex. For example, take a 1-pound bag of sugar and drop it from about 6 inches onto a hard surface like a table. It hits the surface with a thud and stops. Now try the same thing with a Ping-Pong ball, and you’ll see that it bounces. The first bounce of the Ping-Pong ball isn’t as high as the height you dropped it from, but it’s quite high. Then the ball falls and bounces again, only slightly lower. This continues with smaller and smaller bounce heights until the ball comes to rest. Notice that the lower the bounce, the shorter the time between bounces; the bounces speed up until the ball comes to rest. Switch contacts are like that — they’re rigid surfaces coming together quickly, and they bounce. So much so that if you examine the logic levels the switch gives out, you’ll see not a simple transition from a high to a low but a succession of transitions getting closer and closer together until a steady level is reached. This is known as a dirty edge or contact bounce. This rapid changing from 0 to 1 can be a problem if the computer is looking at the switch very rapidly. In fact, this happens much more rapidly than a user can press a button, but sometimes circumstances or code will let this happen. To illustrate the problem, look at the following code, hook up a switch between GPIO 2 (pin 3) and ground (pin 6). This pin has a pull-up resistor fitted on the board. # Bounce Problem shows contact bounce # Author: Mike Cook import time import wiringpi2 as io io.wiringPiSetupGpio() io.pinMode(2,0) # to input lastPress = io.digitalRead(2) count = 0 pressTime = time.time() print"testing push button" while True: press = io.digitalRead(2) if press == 0 and lastPress != press: count += 1 pressTime = time.time() if count >= 5: print"five presses" count = 0 lastPress = press The technique used here is to count five switch presses and then print out when the computer has counted them all. If you try this, you may find that it prints out that it has detected five presses after four or even three presses, as well as every five. In short, it is unreliable because contact bounce is causing erroneous counts. To investigate this deeper, you need to measure the interval between presses. This is done with the following code. # Bounce Measure # measures contact time interval # Author: Mike Cook import time import wiringpi2 as io io.wiringPiSetupGpio() io.pinMode(2,0) # to input lastPress = io.digitalRead(2) count = 0 startTime = time.time() interval = [0.0,0.0,0.0,0.0,0.0] print"testing push button" while True: press = io.digitalRead(2) if press == 0 and lastPress != press: interval[count] = time.time() - startTime count +=1 startTime = time.time() if count >= 5: print"five presses ",interval count = 0 startTime = time.time() lastPress = press The interval between each switch press is recorded in a list. This is derived from the system time clock and counts the number of seconds since the system booted up. By subtracting the system time from the time of the current press, you get the time since the last press. The result of running this program is shown here: five presses [1.2872810363769531, 0.25738978385925293, 6.198883056640625e-05, 0.27149009704589844, 6.699562072753906e-05] five presses [2.247836112976074, 0.31453490257263184, 0.32202887535095215, 0.2885620594024658, 0.33057308197021484] five presses [1.048125982284546, 3.504753112792969e-05, 0.5636959075927734, 0.43523192405700684, 0.4095041751861572] five presses [14.676625967025757, 0.24735713005065918, 0.24397802352905273, 0.33951711654663086, 0.34607601165771484] Notice that the code makes no attempt to reduce the number of significant bits in the readings, but have a close look at some of them, and you’ll see that some end with an e-05. That is the default way of saying 10 to the power of –5; this is known as the exponent format and is the default way floating point numbers are shown in most of computing. So, forgetting the ridiculous number of places after the decimal point, this number, 6.12e–05, is interpreted as 0.0000612 or 61.2 microseconds (uS), which is way faster than any human can press anything. This is an example of contact bounce. You don’t see every bounce because the computer only samples the logic level of the line at discrete intervals. The way to prevent this from happening is to introduce a dead time — that is, to ignore the switch for a specific time after a press has occurred. On many occasions, this will happen naturally because you might have a print statement or some other code that takes up some time before the switch is looked at again. If not, a simple solution would be to add a delay just after the switch has been detected so that nothing is done during the potential bounce time. However, for the ultimate debounce, you need to make a note of the time a switch transition is detected. Then when another transition is detected, only treat it as real if a specific time has elapsed between the last real transition and the present time. An example of this is shown in the following code. # Bounce Solution # How to cope with bounce # Author: Mike Cook import time import wiringpi2 as io io.wiringPiSetupGpio() io.pinMode(2,0) # to input lastPress = io.digitalRead(2) count = 0 pressTime = time.time() print"testing push button" while True: press = io.digitalRead(2) if press == 0 and lastPress != press and (time.time() - pressTime) > 0.025: count += 1 pressTime = time.time() if count >= 5: print"five presses" count = 0 lastPress = press Here the secret is the extra test in the if statement that checks that at least 25 milliseconds (mS) have elapsed before a transition is taken as real. Different types of mechanical switches bounce to a different degree. Depending on exactly what your code is and how fast it runs, this may or may not be a problem. If you do experience “phantom” transitions on reading a mechanical switch, it’s likely to be contact bounce. If so, you can use one of the techniques described here to eliminate the effect.

View Article