My project for the evening was rather simple. I just wanted to get the button input to work in a useful way using Python. The button wiring was the same as before. Just a 10k resistor and connecting to the voltage supply and the GPIO pin. This time, I used pin 24 instead of pin 23. Here's the basic code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
count = 0
while True:
inputValue = GPIO.input(24)
if(inputValue == True):
count = count + 1
print("Button pressed " + str(count) + " times.")
time.sleep(.01)
The basic issue with this code is that it doesn't count very accurately. If you hold the button down, it keeps counting it every time it loops. The Getting Started book suggests using a .3 second pause to avoid that, but I don't like that solution. I want to make sure that the button knows when it's being held down and when it has been released. This was simple enough:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
count = 0
while True:
inputValue = GPIO.input(24)
if(inputValue == True):
count = count + 1
print("Button pressed " + str(count) + " times.")
ReinputValue = GPIO.input(24)
while(ReinputValue == True):
print("Button is still down.")
time.sleep(.01)
ReinputValue = GPIO.input(24)
print("Button released. Total button pushes: " + str(count))
time.sleep(.01)
Browsing around a bit aimlessly, I stumbled on an article about using interrupts: How to use interrupts with Python. This scheme basically takes the looping code out of the program and makes it more efficient because it won't be asking whether the button is up or down all the time. The idea of the interrupt is that it isn't going to think about the button until the button is pressed. I'm thinking of it like a doorbell. You only respond to the doorbell when it has been pushed, not when it's not being pushed. I'm going to have to read up on it before I try to run it.
And that's all I'm going to do tonight.
No comments:
Post a Comment