Posts: 1
Joined: Fri Jun 22, 2012 6:10 pm

Mag Pi Issue 2: In control

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

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

Posts: 759
Joined: Tue Jan 24, 2012 9:30 am
Location: Hertfordshire, UK
Contact: Website

Re: Mag Pi Issue 2: In control

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

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 toolkit to produce multi-media interactive display applications for museums, visitor centres, and more
Download from

Return to “Python”

Who is online

Users browsing this forum: No registered users and 10 guests