Hardware Reference
In-Depth Information
Let's create a class that takes care of setting off the buzzer when there is an
incoming message:
#Declare inputs and outputs.
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN)
GPIO.setup(25,GPIO.OUT)
GPIO.setwarnings(False)
class AsyncTask:
def __init__(self):
self.run_state = True
#avoiding the channel argument throws an error
def terminate(self,channel):
self.run_state = False
def add_callback(self):
GPIO.add_event_detect(18,GPIO.FALLING, callback=self.
terminate)
def run(self):
while self.run_state == True:
GPIO.output(25,GPIO.HIGH)
time.sleep(1)
GPIO.output(25,GPIO.LOW)
time.sleep(1)
GPIO.remove_event_detect(18)
In the AsyncTask class, the buzzer can be set off by triggering a
separate thread to call the run function. This sets off the buzzer
with a one-second interval.
The add_callback method is used to turn off the buzzer when the
button is pressed. The add_event_detect method waits for the state
of GPIO #18 to change from high to low. This turns off the buzzer by setting
run_state to False . While exiting the infinite loop, we remove the
callback functions using the remove_event_detect method.
When a client (Arduino, laptop, or another Raspberry Pi) sends a message
to the server, the thread is initialized and a callback function is registered
as follows:
async_task = AsyncTask()
async_task.add_callback()
thread = Thread(target=async_task.run, args=())
thread.start()
 
Search WWH ::




Custom Search