Mag Pi Issue 2: In control


2 posts
by mosfet » Fri Jun 22, 2012 6:23 pm
Hi, I'm new to python, and was following the Tandy In Control project by Darren Grant. I got my switch, and counter program working. But I do not know how to turn the count program in Python into a timer program that switches on and off when the switch is pressed.

can someone put me out of my misery and give me some pointers on how to do this.
cheers! I have tried many different objects but keep on getting errors :cry:

The count code is

#!/usr/bin/python
import time
import RPi.GPIO as GPIO
GPIO.setup(11, GPIO.IN)
count = 0
while True:
mybutton = GPIO.input(11)
if mybutton == False:
count = count+1
print "count", count
time.sleep(.2)
Posts: 1
Joined: Fri Jun 22, 2012 6:10 pm
by KenT » Fri Jun 22, 2012 9:12 pm
You need a simple state machine. The example you gave has a state machine, its the button which has two states, on or off.

You want a button press to turn the counter both on and off so you have no state machine and have to implement one in software.

To implement your state machine use a variable called timer-running which has values true or false.

Every time around the loop do:

if timer-running is true and button-pressed=true then
timer-running = false
print count
if timer-running is false and button-pressed=true then
timer-running = true
if timer-running = true then count=count +1
sleep (0.2)

There is a problem with this, if you hold the button down for more than 0.2 seconds the timer will start and stop.

What you need is to detect the edge of the button press and generate a signal called button-pressed-signal. You do this by remembering the state of the button the last time around the loop.


if button-pressed = true and last-button-pressed = false then button-pressed-signal = true
last-button-pressed=button-pressed

Having got the signal use it to trigger the state machine but don't forget to reset the signal after you have used it.

Another potential problem is contact bounce. If the contacts of a switch bounce on and off before settling down you could get false reading, then you are into switch de-bouncing in software or maybe a capacitor across the button contacts. Think about that if you get funny results.

State machines and signals are at the heart of control software, there's probably quite a lot written about them on Google.

Hope this helps.
Pi Presents - A display package for museums, visitor centres, and more
Download from http://pipresents.wordpress.com
Posts: 534
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK