[Diaoye learns programming] MicroPython manual pyboard specific port library pyb.LED

Insert image description here

MicroPython is a lightweight version of the interpreter designed for running the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most core syntax of Python.
2. Directly access and control hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. Powerful module system, providing file system, network, graphical interface and other functions.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small and the memory usage is small. It is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

MicroPython application scenarios include:
1. Rapidly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Things to note when using MicroPython:
1. Memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here

pyboard is a compact and powerful electronics development board running MicroPython. It connects to your PC via USB, giving you a USB flash drive to save Python scripts, and a serial Python prompt (REPL) for on-the-fly programming. Micro USB cable required. Available for Windows, Mac and Linux.

MicroPython is a complete rewrite of the Python (version 3.4) programming language so that it fits and runs on microcontrollers. It includes many optimizations so it runs efficiently and uses very little RAM.

MicroPython runs bare metal on a pyboard, which is essentially a Python operating system. The built-in pyb module contains functions and classes for controlling the peripherals available on the board, such as UART, I2C, SPI, ADC and DAC. Watch this video for an overview of pyboard.

Insert image description here

MicroPython's pyb.LED is a class for controlling a single LED (light-emitting diode), which allows you to switch and adjust the brightness on the LED on the board. Its basic definition is as follows:

You can create an instance of pyb.LED by passing in an LED number or alias, such as led = pyb.LED(1) or led = pyb.LED('RED'). LED numbers or aliases can be 1-4, corresponding to red, green, yellow and blue LEDs respectively.
You can use the led.on() method to turn the LED on to maximum brightness.
You can use the led.off() method to turn off the LED.
You can use the led.toggle() method to toggle the state of the LED. If the LED is on, turn it off. If it is off, turn it on.
You can use the led.intensity() method to get or set the brightness of an LED. The brightness range is 0 (off) to 255 (fully on). If no parameters are given, the brightness of the LED is returned. If arguments are given, sets the LED brightness and returns None.

MicroPython's pyb.LED is a class for controlling a single LED (light-emitting diode), which allows you to switch and adjust the brightness on the LED on the board. Its main features, application scenarios and precautions are as follows:

Its main features are:

It can support four LEDs, namely red, green, yellow and blue LEDs. Each LED has a number and alias, which can be used to create instances of pyb.LED.
It can support LED switching and brightness adjustment, and can be used to achieve different effects, such as flashing, breathing, gradient, etc.
It can also support LED switching and can be used to implement some simple logic or feedback, such as switch status, error prompts, warning signals, etc.

Its application scenarios include:

Can be used to display various information, such as power status, network status, temperature status, etc.
Can be used to achieve various effects, such as heartbeat lights, running water lights, rainbow lights, etc.
Can be used to implement some interesting projects or games, such as Morse code, combination locks, guessing games, etc.

Its precautions include:

When using pyb.LED, you should choose the appropriate LED number or alias, and pay attention to the color and position of the LED.
When using pyb.LED, you should pay attention to the brightness range and adjustment method of the LED, and set the appropriate brightness value as needed.
When using pyb.LED, be aware of the current and power consumption of the LED and avoid overloading or overheating.

The following are several practical application cases of MicroPython's pyb.LED:

Case 1: Heartbeat light: Use red LED to simulate the effect of heartbeat, and use brightness adjustment to achieve the effect of breathing. code show as below::

import pyb

# 初始化红色 LED
led = pyb.LED(1) # 假设红色 LED 的编号为 1

# 主循环
while True:
    # 循环改变 LED 的亮度,从 0 到 255 再到 0
    for i in range(256):
        # 设置 LED 的亮度为 i
        led.intensity(i)
        # 延时一段时间,控制呼吸速度
        pyb.delay(2)
    for i in range(256):
        # 设置 LED 的亮度为 255 - i
        led.intensity(255 - i)
        # 延时一段时间,控制呼吸速度
        pyb.delay(2)

Case 2: Flowing water lamp: Use four LEDs to simulate the effect of running water, and use switches and delays to achieve the effect of movement. code show as below::

import pyb

# 初始化四个 LED
leds = [pyb.LED(i) for i in range(1, 5)] # 假设四个 LED 的编号分别为 1, 2, 3, 4

# 主循环
while True:
    # 循环点亮每个 LED,并关闭前一个 LED
    for i in range(4):
        # 点亮第 i 个 LED
        leds[i].on()
        # 如果不是第一个 LED,就关闭前一个 LED
        if i > 0:
            leds[i-1].off()
        # 延时一段时间,控制移动速度
        pyb.delay(200)
    # 关闭最后一个 LED
    leds[3].off()

Case 3: Guessing game: By using three LEDs to simulate the results of guessing, a touch sensor is used to input the user's choice. code show as below::

import pyb

# 初始化三个 LED
leds = [pyb.LED(i) for i in range(1, 4)] # 假设三个 LED 的编号分别为 1, 2, 3
# 定义三个 LED 对应的猜拳选项,分别是剪刀、石头、布
options = ['scissors', 'rock', 'paper']
# 定义一个字典,表示猜拳的胜负关系
rules = {
    
    
    'scissors': 'paper',
    'rock': 'scissors',
    'paper': 'rock'
}

# 初始化触摸传感器
touch = pyb.TouchScreen() # 使用板子上的触摸传感器

# 定义一个函数,用于获取用户的输入
def get_user_input():
    # 循环等待用户触摸屏幕
    while True:
        # 如果检测到触摸
        if touch.z > 100:
            # 获取触摸的位置,并将其映射到三个区域之一,分别对应三个 LED
            x = touch.x * 3 // touch.Z_MAX
            # 返回用户选择的选项
            return options[x]

# 定义一个函数,用于生成电脑的输入
def get_computer_input():
    # 随机选择一个选项
    return random.choice(options)

# 定义一个函数,用于判断猜拳的结果
def judge(user, computer):
    # 如果用户和电脑选择相同,返回平局
    if user == computer:
        return 'draw'
    # 如果用户选择的选项能赢电脑选择的选项,返回胜利
    if rules[user] == computer:
        return 'win'
    # 否则,返回失败
    return 'lose'

# 定义一个函数,用于显示猜拳的结果
def show_result(user, computer, result):
    # 清空所有 LED 的状态
    for led in leds:
        led.off()
    # 根据用户和电脑的选择,点亮相应的 LED,使用白色
    leds[options.index(user)].on()
    leds[options.index(computer)].on()
    # 根据猜拳的结果,闪烁相应的 LED,使用白色
    if result == 'win':
        leds[options.index(user)].toggle()
    elif result == 'lose':
        leds[options.index(computer)].toggle()
    elif result == 'draw':
        for led in leds:
            led.toggle()

# 主循环
while True:
    # 获取用户和电脑的输入
    user = get_user_input()
    computer = get_computer_input()
    # 判断猜拳的结果
    result = judge(user, computer)
    # 显示猜拳的结果,并等待一段时间
    show_result(user, computer, result)
    pyb.delay(3000)

Case 4: Control LED light flashing:

import pyb

# 初始化LED对象
led = pyb.LED(1)

# 控制LED灯闪烁
led.toggle()
pyb.delay(1000)
led.toggle()
pyb.delay(1000)

In this example, we use the pyb.LED() function to initialize the LED object and specify the LED light to use (in this case, light 1). Then, we use the toggle() method to toggle the state of the LED light so that it flashes. By using the pyb.delay() function, we set the time interval between the LED light turning on and off to control the frequency of blinking.

Case 5: Control multiple LED lights to flash at the same time::

import pyb

# 初始化LED对象
led1 = pyb.LED(1)
led2 = pyb.LED(2)
led3 = pyb.LED(3)

# 控制多个LED灯同时闪烁
for _ in range(5):
    led1.toggle()
    led2.toggle()
    led3.toggle()
    pyb.delay(500)

In this example, we use the pyb.LED() function to initialize three LED objects respectively, representing different LED lights (here, lights No. 1, 2, and 3). Then, we use the toggle() method to switch the status of multiple LED lights at the same time, making them flash at the same time. By using the pyb.delay() function, we set the time interval for each blink.

Case 6: Control the brightness of LED lights::

import pyb

# 初始化LED对象
led = pyb.LED(1)

# 控制LED灯的亮度
for brightness in range(0, 256, 10):
    led.intensity(brightness)
    pyb.delay(100)

In this example, we use the pyb.LED() function to initialize the LED object and specify the LED light to use (in this case, light 1). Then, we use the intensity() method to control the brightness of the LED light. Through the loop, we gradually adjust the brightness of the LED light, from 0 to 255, increasing by 10 each time. By using the pyb.delay() function, we set the time interval for each brightness adjustment.

Case 7: Control LED light flashing

import pyb
import time

# 创建LED对象
led = pyb.LED(1)

# 闪烁LED灯
while True:
    led.toggle()
    time.sleep(0.5)

This example program creates an LED object led and connects it to LED light 1. Then, in an infinite loop, the LED light's state is switched by calling the led.toggle() method to achieve the LED light's flashing effect. Use the time.sleep() method to control the blinking interval.

Case 8: Button control LED light switch

import pyb

# 创建LED对象
led = pyb.LED(1)

# 创建按键对象
switch = pyb.Switch()

# 按键控制LED灯开关
while True:
    if switch():
        led.on()
    else:
        led.off()

This example program creates an LED object led and connects it to LED light 1. Then, create a key object switch to detect the key status. In an infinite loop, the key status is detected by calling the switch() method. If the key is pressed, the led.on() method is called to turn on the LED light; if the key is released, the led.off() method is called to turn off the LED light. In this way, the switch function of the button-controlled LED light is realized.

Case 9: Use PWM to adjust LED light brightness

import pyb

# 创建LED对象
led = pyb.LED(1)

# 创建定时器对象
timer = pyb.Timer(2, freq=1000)

# 创建通道对象
channel = timer.channel(1, pyb.Timer.PWM, pin=pyb.Pin.board.X1)

# 使用PWM调节LED灯亮度
duty_cycle = 50  # 占空比,范围为0-100

while True:
    channel.pulse_width_percent(duty_cycle)

This example program creates an LED object led and connects it to LED light 1. Then, create a timer object timer and configure its frequency to 1000Hz. Next, create a PWM channel object channel by calling the timer.channel() method, connect it to pin X1, and set the channel mode to PWM. In an infinite loop, the PWM duty cycle is adjusted by calling the channel.pulse_width_percent() method to control the brightness of the LED light. The duty_cycle variable represents the duty cycle, ranging from 0-100. The brightness of the LED light can be adjusted according to needs.

These sample programs demonstrate the use of the pyb.LED class, which can be used to control the blinking and switching of LED lights and adjust the brightness of LED lights using PWM. Specific application scenarios and usage methods may vary according to actual needs.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132884927