I want my RaspberryPi to perform some actions when the light in a room is switched on or off. To do so, I connected a photocell to the GPIO pins.
Previously, I used some python 3 program that queried the GPIO pin in a loop. The code looks similar to this:
import wiringpi2 as wiringpi
import time
import subprocess
subprocess.call(["gpio", "export", "24", "in"])
wiringpi.wiringPiSetupSys()
last_status = -1
while True:
current_status = wiringpi.digitalRead(24)
if last_status != current_status:
last_status = current_status
print(time.strftime("%H:%M:%S"), " -- ", current_status)
time.sleep(1)
This works somehow, but it has some drawbacks, as the code is neither very precise nor resource-friendly.
I think using an interrupt instead of a loop might be superior in every respect. So I tried something like this:
import wiringpi2 as wiringpi
import time
wiringpi.wiringPiSetupSys()
def print_status():
current_status = wiringpi.digitalRead(24)
print(time.strftime("%H:%M:%S"), " -- ", current_status)
def start_interrupt():
wiringpi.wiringPiISR(24, 2, print_status()) # also tried "wiringpi.INT_EDGE_BOTH" instead of "2" but got the error AttributeError: 'module' object has no attribute 'INT_EDGE_BOTH'
x = wiringpi.piThreadCreate(start_interrupt())
if x != 0:
print("it didn't start")
However, this doesn't work. I tried to find some examples on how to use WiringPi's interrupt-functionality but I failed - I only found examples for C not for Python (3).
Can you help me to get it right?
I have two questions:
- What is the right way to "translate" the loop-solution into an interrupt solution in Python (3)?
- Is there a way to use
INT_EDGE_BOTHinstead of some integer in Python? This would make the code more readable.