pythonadafruit-circuitpython

How to do something like if "this" for 3 seconds, then "that"


I'm using CircuitPython and I'd like to turn on and LED when the light sensor is covered for 3 seconds and up, but I couldn't figure it out.

Is it done with the time.sleep command ?

My current code:

while True:
    print("Light:", cp.light)
    time.sleep(0.2)
       if cp.light < 10: # if light sensor gets a reading of less than 10 lux
           time.sleep(3)
           cp.red_led = True
           time.sleep(0.1)
           cp.play_tone(262, 1)
           cp.play_tone(294, 1)
       else:
           cp.red_led = False

Solution

  • You can keep a count of the number of times you've seen low light in a row.

    When it gets to 15 (which = 5 * 3 # 5 being the number of times a second you are checking and 3 being the number of seconds of low light which lead you to switch on the red light) you switch on the red light and play the sounds (after a slight pause) and you don't then alter count until the light level goes greater than 10.

    count = 0
    while True:
        print("Light:", cp.light)
        time.sleep(0.2)
        if cp.light < 10: # if light sensor gets a reading of less than 10 lux
            if count < 14:
                count += 1 # not yet had 3 seconds of continuous low light so just count
            elif count == 14: # if there has been 3 seconds of less than 10 lux then switch on the light and make sounds              
                count += 1
                cp.red_led = True
                time.sleep(0.1)
                cp.play_tone(262, 1)
                cp.play_tone(294, 1)
        else:
            if count == 15: # if we have had at least 3 seconds of low light then the red led will be on
                cp.red_led = False # switch it off
            count = 0 # this shows we currently aren't in low light