While and interesting demonstration of how it works, the demo on the previous page isn't all that useful. Currently all that the code in code.py is doing when an event is triggered is printing the event type and duration to the serial console as it's only meant to demonstrate the basic functioning of the puff detector.
By modifying the basic structure and content of the demonstration code and combining it with bits and pieces from our many CircuitPython demos, you can make the Sip and Puff trigger all sorts of things.
Call Me Maybe?
The sine qua non of the demo code is the pair of on_ functions, on_sip and on_puff that get called when the corresponding pressure event is detected. This type of function is usually referred to as a callback and is very common when writing code that reacts to user input. We will take a look at the on_sip function as an example as the two functions work the same but for different pressure events.
@detector.on_sip
def on_sip(strength, duration):
if strength == puff_detector.STRONG:
print("GOT STRONG SIP")
if strength == puff_detector.SOFT:
print("GOT SOFT SIP")
print("%.2f long" % duration)
on_sip is a simple function that you provide to define the behavior that you want to happen when a sip event is detected. When a sip event happens, It gets called with two parameters,
-
strengthindicates if the event wasSOFTorSTRONGand can be compared to the constants of the same names in thepuff_detectormodule -
durationis the duration of time that the sip event took from beginning to end.
You may wonder "how does the puff detector know what to call?". The answer to that question the the short statement above the on_sip function that starts with an @
@detector.on_sip
This statement tells the detector that the function that follows should be remembered or registered as a function that should be called when the corresponding event happens.
You might imagine leaving a voicemail for your friend where you say "call me on Friday to let me know if you will come to my party". Unfortunately they'll probably miss your party because no one checks their voice mail anymore, but none the less you could think of leaving that message as registering a callback with your friend. If your friend was a Feather STM32F305 Express or other micro running CircuitPython, you might imagine programming them like so:
@friend.on_friday
def on_friday(rsvp):
if rsvp:
print("We're gonna need more guacamole")
else:
print("We're gonna need more tupperware for all this guacamole")
Page last edited March 08, 2024
Text editor powered by tinymce.