Reputation: 93
I'm trying to get my Raspberry Pi to blink a LED for 5 seconds, and then another one for 5 seconds as well. So I have two functions, one for blinking my red LED, and another for the blue one. I used utime.sleep(0.5)
for the functions to turn off the LEDs every half second.
def blink_red():
RED.toggle()
BLUE.value(0)
utime.sleep(0.5)
def blink_blue():
BLUE.toggle()
RED.value(0)
utime.sleep(0.5)
For the execution of the code, I made use of utime.sleep(5)
in hopes of getting each function to run for 5 seconds, however it doesn't make the LEDs blink. It turns the red led on for five seconds, and the blue one on for 5 seconds as well.
while True:
blink_red()
time.sleep(5)
blink_blue()
utime.sleep(5)
Which parts of my code do I need to change or is there a more pythonic way of doing this?
Edit: I am running micropython
Upvotes: 0
Views: 834
Reputation: 312410
It turns the red led on for five seconds (while the blue one is off), and then turns the blue one on for 5 seconds (while red is off as well).
It sounds like your code is doing what you've asked it do do.
Your loop is running:
blink_red()
time.sleep(5)
blink_blue()
utime.sleep(5)
When you call blink_red()
:
# you toggle the RED LED (once)
RED.toggle()
# you turn off the blue LED
BLUE.value(0)
# you wait 0.5 seconds
utime.sleep(0.5)
# ...and then you return to the main loop
Now you're back in the loop, and you call time.sleep(5)
.
Do you see where this is going?
If you wanted blink_red()
to blink the red LED for five seconds, you would need something like:
def blink_red():
BLUE.off()
for i in range(5):
RED.toggle()
utime.sleep(0.5)
RED.toggle()
utime.sleep(0.5)
And your while
loop would look like this:
while True:
blink_red()
blink_blue()
(Assuming that you rewrote blink_blue
as well.)
Here's a complete program; I was running this using micropython on an ESP C3 (so it's possible it will have slightly different syntax than micropython on the Pi, but it should be largely the same):
try:
import time
except ImportError:
import utime as time
from machine import Pin
RED = Pin(3, Pin.OUT)
BLUE = Pin(5, Pin.OUT)
PINS = [RED, BLUE]
def blink_pin(pin):
for i in range(5):
pin.on()
time.sleep(0.5)
pin.off()
time.sleep(0.5)
# ensure everything is off to start
for pin in PINS:
pin.off()
while True:
blink_pin(RED)
blink_pin(BLUE)
Upvotes: 2