[Diao Ye Learns Programming] MicroPython Manual OpenMV Cam pyb.delay

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
OpenMV Cam is a small, low-power microcontroller board that allows you to easily implement applications using machine vision in the real world. You can program OpenMV Cam using high-level Python scripts (provided by MicroPython OS) instead of C/C++. The technical parameters of OpenMV Cam include the following aspects:

1. Processor: OpenMV Cam H7 Plus uses STM32H743II ARM Cortex M7 processor, running at 480 MHz, with 32MB SDRAM + 1MB SRAM and 32 MB external flash memory + 2 MB internal flash memory. OpenMV Cam M4 V2 uses STM32F427VG ARM Cortex M4 processor running at 180 MHz with 256KB RAM and 1 MB flash memory.
2. Image sensor: Both OpenMV Cam H7 Plus and OpenMV Cam M4 V2 use the OV7725 image sensor, which can capture 320x240 8-bit grayscale images or 320x240 16-bit RGB565 images at 75 FPS at resolutions higher than 320x240. Capable of shooting at 150 FPS at 320x240.
3. I/O interface: OpenMV Cam H7 Plus and OpenMV Cam M4 V2 both have the following I/O interfaces:
(1) Full-speed USB (12Mbs) interface, connected to the computer. When the OpenMV Cam is plugged in, a virtual COM port and a "USB flash drive" will appear on your computer.
(2) The μSD card slot is capable of 100Mbs read/write, allowing your OpenMV Cam to record video and extract machine vision material from the μSD card.
(3) The SPI bus operates at a speed of up to 54Mbs, allowing you to simply transmit image stream data to the LCD expansion board, WiFi expansion board, or other controllers.
(4) I2C bus (up to 1Mb/s), CAN bus (up to 1Mb/s) and asynchronous serial bus (TX/RX, up to 7.5Mb/s) for connection with other controllers or sensors.
(5) A 12-bit ADC and a 12-bit DAC.
(6) There are interrupts and PWM on all I/O pins (there are 9 or 10 I/O pins on the board).
4. LED: Both OpenMV Cam H7 Plus and OpenMV Cam M4 V2 are equipped with one RGB LED (tri-color) and two bright 850nm IR LEDs (infrared).
5. Lens: Both OpenMV Cam H7 Plus and OpenMV Cam M4 V2 are equipped with a standard M12 lens interface and a default 2.8 mm lens. If you want to use a more professional lens with your OpenMV Cam, you can easily purchase it and install it yourself.

Insert image description here
The pyb.delay function of MicroPython's OpenMV Cam is used to add a delay to the program, that is, to pause execution for a period of time. Its main features, application scenarios and matters needing attention will be explained in detail below.

main feature:

Precise delay control: The pyb.delay function can provide precise delay control in milliseconds. By specifying the delay time parameter, the program can pause for the specified time when executing the pyb.delay function, and then continue executing subsequent code.

Easy to use: MicroPython is a simple and easy to learn programming language, and the pyb.delay function is one of the built-in functions provided by OpenMV Cam. Its use is simple and clear, just call the function in the code and specify the delay time, without complex configuration and settings.

Precise time control: The pyb.delay function can provide more precise time control and is suitable for scenarios where time requirements are not very strict. It can be used to control the execution speed, time interval, and scheduled tasks of the program.

Application scenarios:

Task scheduling and time control: The pyb.delay function can be used for task scheduling and time control. When writing a program, you can use the pyb.delay function to control the time interval between tasks to achieve functions such as scheduled execution and scheduled event triggering.

Sensor sampling: OpenMV Cam is often used with various sensors to collect environmental data. During the sensor sampling process, data may need to be collected at different time intervals. In this case, the pyb.delay function can be used to control the sampling time interval.

Teaching and learning: The pyb.delay function is one of the basic knowledge of MicroPython programming. It is important for beginners to learn and understand the concept and application scenarios of delay. During the teaching process, the concept and application of delay can be demonstrated and practiced by using the pyb.delay function.

Things to note:

Delay time unit: The delay time parameter of the pyb.delay function is an integer value in milliseconds. When using it, the delay time needs to be set reasonably according to specific needs and actual conditions.

Blocking caused by too long delay: If a too long delay time is used in the program, it may cause the program to be unable to respond to other tasks or events during the delay period, resulting in blocking. Therefore, when designing a program, it is necessary to set the delay time reasonably according to actual needs to avoid unnecessary problems caused by too long delay.

Accuracy considerations: The delay time provided by the pyb.delay function is not absolutely accurate and may be affected by the system and hardware. In application scenarios with strict time requirements, other more precise time control methods may be needed, such as using hardware timers.

In summary, the pyb.delay function of MicroPython's OpenMV Cam is a function used to add delay in the program. It has precise delay control and is easy to use. It is suitable for scenarios such as task scheduling, time control, sensor sampling, and teaching and learning. When using it, you need to pay attention to factors such as the delay time unit, blocking caused by too long delay, and accuracy considerations, and set and use the delay function reasonably according to specific needs and application scenarios.

Case 1: Using pyb.delay() to implement delayed photography

Analysis: In this case, we will use the pyb.delay() function to implement the delayed photography function. First, we need to import the OpenMV Cam module, and then set the camera resolution and frame rate. Next, we will use a loop to continuously capture images and call the pyb.delay() function after each capture to implement the delay. Finally, we save the captured image to a file.

Code:

import sensor, image, time

# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)

# 捕获图像并延时
while True:
    img = sensor.snapshot()
    print("拍照中...")
    time.sleep(1000)  # 延时1秒
    img.save("photo_{}.jpg".format(time.time()))

Case 2: Using pyb.delay() to implement time-lapse video

Analysis: In this case, we will use the pyb.delay() function to implement the time-lapse video function. First, we need to import the OpenMV Cam module, and then set the camera resolution and frame rate. Next, we will use a loop to continuously capture images and call the pyb.delay() function after each capture to implement the delay. Finally, we save the captured image to a file.

Code:

import sensor, image, time

# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)

# 捕获图像并延时
video = sensor.snapshot()
while video is not None:
    img = video.snapshot()
    print("录像中...")
    time.sleep(1000)  # 延时1秒
    img.save("video_{}.avi".format(time.time()))
    video = None

Case 3: Using pyb.delay() to implement delayed moving target tracking

Analysis: In this case, we will use the pyb.delay() function to implement the delayed moving target tracking function. First, we need to import the OpenMV Cam module, and then set the camera resolution and frame rate. Next, we will use a loop to continuously capture images and call the pyb.delay() function after each capture to implement the delay. At the same time, we need to detect moving targets in the image and restart the timing after the target disappears.

Code:

import sensor, image, time

# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)

# 初始化目标位置和计时器
target_pos = [(100, 100)]
target_timer = 0

# 捕获图像并处理
while True:
    img = sensor.snapshot()
    # 检测目标位置变化
    if target_timer > 0:
        new_pos = (img.find_blob(target_pos[0], scale=3, threshold=0.8)[0].rect())
        if new_pos != target_pos:
            target_timer = 0
            target_pos = new_pos
        else:
            target_timer -= 1
    else:
        target_timer = 5  # 设置目标跟踪延时时间(单位:秒)
    print("跟踪中...")
    time.sleep(1)  # 延时1秒
    img.save("image_{}.jpg".format(time.time()))

Case 4: Controlling motor rotation time

import pyb  
from pyb import PWM, delay  
  
motor = PWM(pyb.Pin('X1'), freq=100) # 初始化电机引脚为PWM输出,频率为100Hz  
  
for i in range(10): # 控制电机转动10次  
    motor.duty(1000) # 设置电机占空比为1000  
    delay(500) # 延时500毫秒,即0.5秒  
    motor.duty(0) # 停止电机转动  
    delay(500) # 延时500毫秒,即0.5秒

Interpretation of key points:
First initialize the motor pin to PWM output and set the frequency to 100Hz. In one cycle, the motor is controlled to rotate 10 times. Each time it rotates, set the motor duty cycle to 1000, which is the maximum speed, and then delay for 500 milliseconds, or 0.5 seconds, to stop the motor from rotating, and then delay for another 500 milliseconds. Control the rotation time of the motor through the pyb.delay function to achieve precise control of the rotation angle and speed of the motor.

Case 5: Time-lapse photography

import sensor, image, time, pyb  
  
sensor.reset() # 初始化摄像头  
sensor.set_pixformat(sensor.RGB565) # 设置像素格式  
sensor.set_framesize(sensor.QVGA) # 设置帧大小  
sensor.skip_frames(time = 2000) # 等待摄像头稳定  
  
for i in range(10): # 拍摄10张照片  
    img = sensor.snapshot() # 拍摄照片  
    delay(1000) # 延时1000毫秒,即1秒

Interpretation of key points:
First initialize the camera and set the pixel format and frame size. In a loop, 10 photos are taken. Each time you take a photo, use the snapshot() function to take a photo, and then delay it by 1000 milliseconds, which is 1 second. Use the pyb.delay function to delay taking pictures to avoid the camera being affected by jitter or light changes when taking pictures.

Case 6: Delayed execution

import pyb, machine  
  
led = machine.Pin('X2', machine.Pin.OUT) # 初始化LED引脚为输出模式  
delay(5000) # 延时5000毫秒,即5秒  
led.on() # 打开LED灯  
delay(5000) # 延时5000毫秒,即5秒  
led.off() # 关闭LED灯

Interpretation of key points:
First initialize the LED pin to output mode. Then delay 5000 milliseconds, which is 5 seconds. During the delay period, program execution is suspended. After the delay is over, turn on the LED light, delay for another 5000 milliseconds, and then turn off the LED light. Delayed execution is implemented through the pyb.delay function, so that in some cases, some operations can be performed after waiting for a period of time.

Case 7: Time-lapse photos:

import sensor
import image
import lcd
import time
import pyb

lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.run(1)

while True:
    pyb.delay(5000)  # 5秒延时
    img = sensor.snapshot()
    lcd.display(img)

Interpretation of key points:
This program uses the sensor module and LCD module of OpenMV Cam to take time-lapse photos and display them on the LCD.
Use lcd.init() to initialize the LCD display.
Use sensor.reset() to reset the camera sensor.
Use sensor.set_pixformat(sensor.RGB565) to set the image pixel format to RGB565.
Use sensor.set_framesize(sensor.QVGA) to set the image frame size to QVGA (320x240).
Use sensor.run(1) to start camera image streaming.
In an infinite loop, make the program continue to perform the following operations:
use the pyb.delay(5000) function for a 5-second delay.
Use sensor.snapshot() to capture the camera image and store it in the variable img.
Use lcd.display(img) to display an image on the LCD display.

Case 8: Delayed triggering of external devices:

import pyb

trigger_pin = pyb.Pin('P0', pyb.Pin.OUT)

while True:
    trigger_pin.value(1)  # 触发外部设备
    pyb.delay(1000)  # 1秒延时
    trigger_pin.value(0)  # 停止触发
    pyb.delay(5000)  # 5秒延时

Interpretation of key points:
This program uses the pyb module of OpenMV Cam to control the delayed triggering of external devices.
Create an output pin object named trigger_pin and connect it to the external device.
In an infinite loop, have the program continue to do the following:
Use trigger_pin.value(1) to set the pin high to trigger an external device.
Use the pyb.delay(1000) function to perform a 1 second delay.
Use trigger_pin.value(0) to set the pin low to stop triggering.
Use the pyb.delay(5000) function to perform a 5-second delay.

Case 9: Button delay control:

import pyb

button_pin = pyb.Pin('P1', pyb.Pin.IN)
led_pin = pyb.Pin('P2', pyb.Pin.OUT)

while True:
    if button_pin.value() == 1:  # 按钮被按下
        led_pin.value(1)  # 点亮LED
        pyb.delay(5000)  # 5秒延时
        led_pin.value(0)  # 熄灭LED
    else:
        led_pin.value(0)  # 熄灭LED

Interpretation of key points:
This program uses the pyb module of OpenMV Cam to control the button delay to control the LED on and off.
Create an input pin object named button_pin, connected to the button.
Create an output pin object named led_pin and connect it to the LED.
In an infinite loop, have the program continue to do the following:
If the button is pressed (button_pin.value() == 1):
Use led_pin.value(1) to light the LED.
Use the pyb.delay(5000) function to perform a 5-second delay.
Use led_pin.value(0) to turn off the LED.
Otherwise, i.e. the button is not pressed:
use led_pin.value(0) to turn off the LED.
These sample codes show how to use the pyb.delay() function to perform delay operations in MicroPython and OpenMV Cam. You can modify and extend these sample codes to suit your needs and specific hardware configuration.

Please note that the above cases are only for expanding ideas and may contain errors or inapplicability. Different hardware platforms, usage scenarios and MicroPython versions may lead to different usage methods. In actual programming, you need to adjust it according to your hardware configuration and specific needs, and conduct multiple actual tests. It is important to ensure that the hardware is connected correctly and to understand the specifications and characteristics of the sensors and devices used.

Insert image description here

Guess you like

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