@fuzzy OK. here is a variant of the fist version which counts down the total duration every second:
from machine import Pin, Timer, idle
DEFAULT_HIGH = const(2)
DEFAULT_LOW = const(4)
DEFAULT_DURATION = const(10)
class BLINK:
def __init__(self, pin, high = DEFAULT_HIGH, low = DEFAULT_LOW, duration = DEFAULT_DURATION):
self.start(pin, high, low, duration)
def start(self, pin, high, low, duration):
self.pin = pin
self.times = [high, low]
self.duration = duration
self.state = 0
self.count = self.times[self.state]
self.pin(self.state)
self.timer = Timer.Alarm(self.timerCallback, 1.0, periodic=True)
def timerCallback(self, timer):
self.duration -= 1
if self.duration <= 0:
self.pin(0) # or whatever final state you like
self.stop()
else:
self.count -= 1
if self.count <= 0:
self.state = 1 - self.state
self.count = self.times[self.state]
self.pin(self.state)
def stop(self):
self.timer.cancel()
def run():
pin = Pin("P5", mode=Pin.OUT)
blink = BLINK(pin, 1, 1, 10)
while blink.duration > 0:
idle()
run()