Raspberry Control LED On and Off with For-loop
In this project, we will control the LED on and off with a for-loop to achieve flashing.
Hardware Connection
In this project, we will use the following electronics hardware:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - LED Pack
Similar to before, we connect the LED to D16.
In the last lesson, we have learned how to control the LED on and off. To realize the final Blink program, we only need to make some slight modifications.
Write a Program
First, let's try to modify the program like this:
1 import machine
2 LED = machine.Pin(16, machine. Pin. OUT)
3 LED.value(1)
4 LED.value (0)
Click the “run" button and look at the LED. You will find that the LED just flashes only once very quickly. This is because:
1. The execution speed of the program is so fast that the flash effect is not obvious.
2. We did not set the loop structure for the program, and the flashing part of the program was executed only once.
Let's solve the first problem. Since the problem is that the program runs too fast, we can set a delay between each LED on and off.
At the beginning of the program, we introduce a new function library: utime.
·Note·
Utime Function Library
The utime function library is one of the standard libraries of MicroPython, and its functions provide us with time-related functions such as obtaining time and date, measuring time interval, setting delay and so on.
The commonly used functions are:
• Declare the library used — import utime
• Sleep for the given number of seconds — utime.sleep(seconds)
• Sleep for the given number of milliseconds — utime.sleep_ms(ms)
• Convert the time expressed in seconds into a date-time tuple — utime.localtime([secs])
1 import machine
2 import utime
Next, we use the sleep function in utime to add a delay after each program that operates the LED.
1 LED.value (1)
2 utime. sleep(1)
3 LED.value(0)
4 utime. sleep(1)
The default unit of the sleep function is in seconds unless otherwise specified. By modifying the program, we have set the time for each light on and off to 1 second.
Let's first try to use the for-loop to simply turn the LED on and off. The program is as follows:
1 import machine
2 import utime
3
4 LED = machine. Pin(16, machine. Pin. OUT)
5 for i in range(10):
6 LED.value(1)
7 utime. sleep(1)
8 LED.value (0)
9 utime. sleep(1)
When we execute this program, we can find that the LED stops flashing after ten loops. This is because there are only 10 integers generated by using the range() function, so the for-loop only loops 10 times. When we change range(10) to range(20), the LED loops 20 times.
Of course, no matter how large we set this value to, the loop is always a definite loop. If we want to keep the program running, we need to use the indefinite loop structure to write the program.