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

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.freq function of MicroPython's OpenMV Cam is used to set the main frequency of the OpenMV Cam, that is, the clock frequency of the controller.

main feature:

Controller clock frequency setting: The pyb.freq function can be used to set the clock frequency of the OpenMV Cam controller. By adjusting the clock frequency, you can change the controller's operating speed and performance. Higher clock frequencies increase computing speed and responsiveness, while lower clock frequencies reduce power consumption and heat generation.

Flexibility: The pyb.freq function provides flexible frequency setting options. Users can choose the appropriate clock frequency based on specific needs and application scenarios. OpenMV Cam supports multiple predefined clock frequency options, and custom frequencies can also be set to meet specific needs.

Real-time: The pyb.freq function can dynamically set the clock frequency while the program is running. This means that the clock frequency can be flexibly adjusted in different stages or tasks according to real-time needs to achieve the best balance of performance and power consumption.

Application scenarios:

Performance optimization: The pyb.freq function can be used in performance optimization application scenarios. By increasing the clock frequency of the controller, the code execution speed can be accelerated and the efficiency of image processing, calculation and algorithm operation can be improved, which is suitable for applications with high real-time performance requirements.

Low-power applications: OpenMV Cam is an embedded camera module commonly used in battery-operated devices. By reducing the clock frequency of the controller, power consumption and heat generation can be reduced, battery life can be extended, and it is suitable for applications with higher power consumption requirements.

Teaching and learning: The use of the pyb.freq function involves the underlying configuration and performance tuning of the controller, which has certain challenges and learning value for teaching and learning. Teachers can help students understand and master the principles and methods of clock frequency setting through examples and practices.

Things to note:

Frequency range and stability: When setting the frequency with the pyb.freq function, you need to pay attention to the legality and stability of the selected frequency. Selecting a frequency outside the controller's specifications or operating range may result in unpredictable errors or system instability.

Performance and power balance: When adjusting clock frequency, there is a trade-off between performance and power consumption. Higher frequencies can improve performance but increase power consumption and heat generation, and lower frequencies can reduce power consumption but may reduce performance. Therefore, there are trade-offs when setting the frequency based on application requirements and device characteristics.

Compatibility: The availability and functionality of the pyb.freq function may vary between different hardware versions and firmware versions. When using the pyb.freq function, you need to confirm whether the OpenMV Cam hardware and firmware version used support this function, and consult relevant documents and information for accurate usage and precautions.

In summary, the pyb.freq function of MicroPython's OpenMV Cam is used to set the clock frequency of the controller, which has the characteristics of controlling performance and power consumption. It is suitable for performance optimization, low-power applications, and teaching and learning scenarios. When using it, you need to pay attention to factors such as frequency range and stability, performance and power consumption balance, and compatibility, and set the clock frequency reasonably according to specific needs and application scenarios.

Case 1: Use pyb.freq() to implement image frequency filtering

Analysis: In this case, we will use the pyb.freq() function to implement frequency filtering of the image. 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.freq() function after each capture to implement frequency filtering. 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()
    result = img.frequency_filter(1)  # 应用1Hz频率滤波
    if result:
        img.save("image_{}.jpg".format(time.time()))
    time.sleep(1000)  # 延时1秒

Interpretation of key points: In this case, we use the frequency_filter() function of OpenMV Cam to implement frequency filtering. This function accepts a parameter representing the frequency value to be applied. For example, when the parameter is 1, it means applying 1Hz frequency filtering. If the frequency filtering is successful, the function will return True, otherwise it will return False.

Case 2: Use pyb.freq() to implement image low-pass filtering

Analysis: In this case, we will use the pyb.freq() function to implement low-pass filtering of the image. 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 the image and call the pyb.freq() function after each capture to implement low-pass filtering. 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()
    result = img.frequency_filter(80)  # 应用80Hz频率滤波
    if result:
        img.save("image_{}.jpg".format(time.time()))
    time.sleep(1000)  # 延时1秒

Interpretation of key points: In this case, we use the frequency_filter() function of OpenMV Cam to implement low-pass filtering. This function accepts a parameter representing the frequency value to be applied. For example, when the parameter is 80, it means applying 80Hz frequency filtering. If the frequency filtering is successful, the function will return True, otherwise it will return False.

Case 3: Using pyb.freq() to implement image high-pass filtering

Analysis: In this case, we will use the pyb.freq() function to implement high-pass filtering of the image. 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 the image and call the pyb.freq() function after each capture to implement high-pass filtering. 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()
    result = img.frequency_filter(1)  # 应用1Hz频率滤波
    if result:
        img.save("image_{}.jpg".format(time.time()))
    time.sleep(1000)  # 延时1秒

Interpretation of key points: In this case, we use the frequency_filter() function of OpenMV Cam to implement high-pass filtering. This function accepts a parameter representing the frequency value to be applied. For example, when the parameter is 1, it means applying 1Hz frequency filtering. If the frequency filtering is successful, the function will return True, otherwise it will return False.

Case 4: Set camera frame rate

import sensor, image, pyb  
  
sensor.reset() # 初始化摄像头  
sensor.set_pixformat(sensor.RGB565) # 设置像素格式  
sensor.set_framesize(sensor.QVGA) # 设置帧大小  
sensor.set_fps(30) # 设置摄像头帧率为30fps  
pyb.freq(160000000) # 设置主频为160MHz  
sensor.skip_frames(time = 2000) # 等待摄像头稳定  
  
while(True):  
    img = sensor.snapshot() # 拍摄照片  
    print(img) # 打印照片

Interpretation of key points:
First initialize the camera and set the pixel format and frame size. Use the set_fps() function to set the camera frame rate to 30fps. Use the pyb.freq() function to set the main frequency to 160MHz to increase the processing speed of the camera. In an infinite loop, use the snapshot() function to take photos in real time and print the photos. By setting the camera frame rate and main frequency, you can adjust the camera's shooting speed and image processing capabilities.

Case 5: Adjust camera contrast and brightness

import sensor, image, pyb  
  
sensor.reset() # 初始化摄像头  
sensor.set_pixformat(sensor.RGB565) # 设置像素格式  
sensor.set_framesize(sensor.QVGA) # 设置帧大小  
sensor.set_contrast(2) # 设置对比度为2  
sensor.set_brightness(1) # 设置亮度为1  
pyb.freq(160000000) # 设置主频为160MHz  
sensor.skip_frames(time = 2000) # 等待摄像头稳定  
  
while(True):  
    img = sensor.snapshot() # 拍摄照片  
    print(img) # 打印照片

Interpretation of key points:
First initialize the camera and set the pixel format and frame size. Use the set_contrast() function and set_brightness() function to set contrast and brightness respectively. Use the pyb.freq() function to set the main frequency to 160MHz to increase the processing speed of the camera. In an infinite loop, use the snapshot() function to take photos in real time and print the photos. By adjusting the contrast and brightness of the camera, you can improve the clarity and visual effects of the photos you take.

Case 6: Camera real-time video stream processing

import sensor, image, pyb, machine  
  
sensor.reset() # 初始化摄像头  
sensor.set_pixformat(sensor.RGB565) # 设置像素格式  
sensor.set_framesize(sensor.QVGA) # 设置帧大小  
pyb.freq(160000000) # 设置主频为160MHz  
sensor.skip_frames(time = 2000) # 等待摄像头稳定  
lcd = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=100000) # 初始化LCD屏幕  
lcd.init() # 初始化LCD屏幕  
lcd.direction(lcd.YX_LRUD) # 设置LCD屏幕方向为从左到右,从上到下  
lcd.clear() # 清空LCD屏幕  
lcd.display(image.Image()) # 在LCD屏幕上显示一张空白图片,以准备接收实时视频流  
stream = sensor.snapshot() # 开始摄像头实时视频流  
while(True):  
    lcd.display(stream) # 在LCD屏幕上显示实时视频流

Interpretation of key points:
First initialize the camera and set the pixel format and frame size. Use the pyb.freq() function to set the main frequency to 160MHz to increase the processing speed of the camera. Initialize the LCD screen, set its orientation and clear the screen. Use the snapshot() function to start the camera's real-time video stream. In an infinite loop, display the live video stream on the LCD screen. Through real-time video stream processing, real-time monitoring and display of cameras can be achieved.

Case 7: Set the system clock frequency:

import pyb

pyb.freq(200000000)  # 设置系统时钟频率为200MHz
要点解读:

该程序使用pyb.freq()函数设置系统时钟频率。
pyb.freq(200000000)将系统时钟频率设置为200MHz。

Case 8: Measuring code execution time:

import pyb

start_time = pyb.millis()  # 记录开始时间

# 执行需要测量时间的代码

end_time = pyb.millis()  # 记录结束时间
execution_time = end_time - start_time  # 计算代码执行时间
print("Execution Time:", execution_time, "ms")

Interpretation of key points:
This program uses the pyb.millis() function to measure the execution time of the code.
start_time = pyb.millis() records the start time, which is the time before the code is executed.
After the code that needs to be measured is executed, use end_time = pyb.millis() to record the end time, which is the time after the code is executed.
By calculating execution_time = end_time - start_time, the execution time of the code is obtained.
Use the print() function to output the code execution time.

Case 9: Use a timer to generate periodic pulse signals:

import pyb

timer = pyb.Timer(1)  # 创建定时器对象
timer.init(freq=1000)  # 设置定时器频率为1kHz

ch = timer.channel(1, pyb.Timer.PWM, pin=pyb.Pin("P7"))  # 创建通道对象
ch.pulse_width_percent(50)  # 设置脉冲宽度占空比为50%

timer.counter()  # 获取定时器计数器值

Interpretation of key points:
This program uses the pyb.Timer and pyb.Pin modules to generate periodic pulse signals.
timer = pyb.Timer(1) creates a timer object and sets its number to 1.
Use timer.init(freq=1000) to set the timer frequency to 1kHz.
ch = timer.channel(1, pyb.Timer.PWM, pin=pyb.Pin("P7")) creates a channel object, specifies the channel number as 1, uses PWM mode, and outputs the signal to pin "P7" .
Use ch.pulse_width_percent(50) to set the pulse width duty cycle to 50%.
Use timer.counter() to obtain the counter value of the timer, which can be used for further operations or monitoring the timer status.
These sample codes show how to use the pyb.freq module in MicroPython and OpenMV Cam to set the system clock frequency, measure code execution time, and generate periodic pulse signals. You can modify and extend these sample codes according to your own needs and specific application scenarios.

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/133579582