Public Domain via

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 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.

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, 

  • strength indicates if the event was SOFT or STRONG and can be compared to the constants of the same names in the puff_detector module
  • duration is 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 @


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:

def on_friday(rsvp):
  if rsvp:
    print("We're gonna need more guacamole")
    print("We're gonna need more tupperware for all this guacamole")

Make it Your Own

To get the sip and puff to do all manner of thinks, all you have to do is make your own functions that do what you want to happen when a pressure event happens, and then register it as a callback. That's all there is to it!

This guide was first published on Feb 17, 2020. It was last updated on Jul 17, 2024.

This page (Extending the Capabilites) was last updated on Mar 08, 2024.

Text editor powered by tinymce.