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

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
MicroPython's OpenMV Cam supports the pyb.Pin function for controlling and managing the state and behavior of pins. Its main features, application scenarios and matters needing attention will be explained in detail below.

main feature:

Pin control: The pyb.Pin function allows you to flexibly control and configure the pins on the OpenMV Cam. You can set the input and output modes, level status, pull-up and pull-down resistors, etc. of the pins to meet different application needs.

Versatility: OpenMV Cam’s pins support multiple functions, such as digital input and output, analog input, PWM output, interrupt triggering, etc. You can choose different pin functions according to specific needs, and configure and manage them through pyb.Pin.

Simplified development: Using the MicroPython programming language, you can control and manage pins by writing concise code. OpenMV Cam provides a friendly programming interface and sample code, making the development and debugging of pin control easier and more convenient.

Application scenarios:

Sensor interface: The pins of OpenMV Cam can be used to connect various sensors, such as temperature sensor, light sensor, acceleration sensor, etc. Through the pyb.Pin function, the input mode and level status of the pin can be configured to realize data interaction and communication with the sensor.

Actuator control: Pins can be used to control actuator devices, such as motors, servos, relays, etc. Through the pyb.Pin function, the output mode and level status of the pin can be configured to control and drive the actuator device.

External device interface: OpenMV Cam’s pins can communicate and connect with other external devices, such as displays, wireless modules, expansion boards, etc. Through the pyb.Pin function, the function and communication protocol of the pin can be configured to realize data exchange and control with external devices.

Things to note:

Pin voltage: When using the pyb.Pin function, you need to pay attention to the voltage compatibility of the pin. OpenMV Cam usually uses 3.3V level, so it is necessary to ensure that the voltage of external devices and pins are compatible to avoid pin damage or data errors.

Pin limitations: Each pin has certain limitations on its functions and features. When using the pyb.Pin function, you need to carefully review the OpenMV Cam documentation and pin specification table to understand the functions, electrical characteristics, and limitations of each pin to ensure that the pins are configured and used correctly.

Current and power consumption: When using pins to drive and control external devices, you need to pay attention to the maximum current output of the pin and the power consumption of the entire system. Excessive current output may cause pin overload, while excessive power consumption may affect the stability and performance of OpenMV Cam.

In summary, the pyb.Pin function of MicroPython's OpenMV Cam provides a flexible pin control and management interface, which can be used for applications such as connecting sensors, controlling actuators, and communicating with external devices. It has key features such as pin control, versatility and simplified development. When using, you need to pay attention to factors such as pin voltage compatibility, pin limitations, and current power consumption. By properly configuring and using the pyb.Pin function, data interaction and control between OpenMV Cam and external devices can be achieved.

Case 1: Controlling the switch of LED lights

import sensor, image, time
from pyb import LED

sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.RGB565) # 设置像素格式为RGB565
sensor.set_framesize(sensor.QVGA) # 设置帧大小为320x240
sensor.skip_frames(time = 2000) # 等待设置生效,延时2秒

led = LED(1) # 初始化LED,连接到引脚1

while True:
    img = sensor.snapshot() # 捕获一帧图像
    if img.is_dark(): # 如果图像较暗
        led.off() # 关闭LED
    else:
        led.on() # 打开LED
    time.sleep_ms(100) # 延时100毫秒

Interpretation: This program first imports the sensor, image, time and pyb.LED modules. Then initialize the camera, set the pixel format to RGB565, the frame size to 320x240, and wait for the settings to take effect, with a delay of 2 seconds. Next initialize the LED and connect it to pin 1. In an infinite loop, images from the camera are continuously captured. If the image is dark, turn off the LED; otherwise, turn on the LED. The final delay is 100 milliseconds.

Case 2: Controlling the buzzer switch

import sensor, image, time
from pyb import BUZZER

sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.RGB565) # 设置像素格式为RGB565
sensor.set_framesize(sensor.QVGA) # 设置帧大小为320x240
sensor.skip_frames(time = 2000) # 等待设置生效,延时2秒

buzzer = BUZZER(18) # 初始化蜂鸣器,连接到引脚18

while True:
    img = sensor.snapshot() # 捕获一帧图像
    if img.is_dark(): # 如果图像较暗
        buzzer.off() # 关闭蜂鸣器
    else:
        buzzer.on() # 打开蜂鸣器
    time.sleep_ms(100) # 延时100毫秒

Interpretation: This procedure is similar to the first case, except that the LED is replaced by a buzzer. First, the sensor, image, time and pyb.BUZZER modules were imported. Then initialize the camera, set the pixel format to RGB565, the frame size to 320x240, and wait for the settings to take effect, with a delay of 2 seconds. Next initialize the buzzer and connect it to pin 18. In an infinite loop, images from the camera are continuously captured. If the image is dark, turn off the buzzer; otherwise, turn on the buzzer. The final delay is 100 milliseconds.

Case 3: Controlling the switch of the keypad

import sensor, image, time
from pyb import KEY

sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.RGB565) # 设置像素格式为RGB565
sensor.set_framesize(sensor.QVGA) # 设置帧大小为320x240
sensor.skip_frames(time = 2000) # 等待设置生效,延时2秒

key = KEY(14, pyb.Pin('E4')) # 初始化按键板,连接到引脚14和E4

while True:
    img = sensor.snapshot() # 捕获一帧图像
    if img.is_dark(): # 如果图像较暗
        key.press() # 按下按键板
    else:
        key.release() # 松开按键板
    time.sleep_ms(100) # 延时100毫秒

Interpretation: This program is similar to the second case, except that the buzzer is replaced by a keypad. First, the sensor, image, time and pyb.KEY modules were imported. Then initialize the camera, set the pixel format to RGB565, the frame size to 320x240, and wait for the settings to take effect, with a delay of 2 seconds. Next initialize the keypad and connect it to pins 14 and E4. In an infinite loop, images from the camera are continuously captured. If the image is dark, press the keypad; otherwise, release the keypad. The final delay is 100 milliseconds.

Case 4: Use pyb.Pin to control LED flashing

import pyb, time  
  
led = pyb.Pin('X1', pyb.Pin.OUT_PP) # 初始化LED引脚为输出模式  
while True:  
    led.toggle() # 翻转LED状态  
    time.sleep(500) # 延时500ms

Interpretation of key points:
First initialize the LED pin to output mode.
In an infinite loop, use the toggle() function to flip the LED state, and use the time.sleep() function to delay 500ms.

Case 5:: Use pyb.Pin to read key status

import pyb, time  
  
button = pyb.Pin('X2', pyb.Pin.IN, pyb.Pin.PULL_UP) # 初始化按键引脚为输入模式,上拉电阻  
while True:  
    if button.value() == 0: # 如果按键被按下  
        print('Button pressed') # 打印消息  
    time.sleep(100) # 延时100ms

Interpretation of key points:
First initialize the button pin to input mode and pull-up resistor.
In an infinite loop, use the value() function to read the key status, and if the key is pressed (the value is 0), print a message. Use the time.sleep() function to delay 100ms.

Case 6: Use pyb.Pin to control the steering gear angle

import pyb, time  
  
servo = pyb.Pin('X3', pyb.Pin.OUT_PP) # 初始化舵机引脚为输出模式  
while True:  
    for angle in range(0, 181, 10): # 从0度到180度,步长为10度  
        servo.pulse_width_us(500 + angle * 10) # 设置舵机脉冲宽度,控制舵机角度  
        time.sleep(20) # 延时20ms,以减少CPU的使用率

Interpretation of key points:
First initialize the servo pins to output mode.
In an infinite loop, use a for loop to go from 0 degrees to 180 degrees in steps of 10 degrees. Use the pulse_width_us() function to set the servo pulse width and control the servo angle. Use the time.sleep() function to delay 20ms to reduce CPU usage.

Case 7: Control the LED light to turn on and off:

import time
import pyb

led = pyb.Pin("LED1", pyb.Pin.OUT)

while True:
    led.toggle()
    time.sleep(1)

Interpretation of key points:
This program uses the pyb.Pin module to control the LED lights on the OpenMV Cam.
Instantiate a Pin object using pyb.Pin("LED1", pyb.Pin.OUT), connect it to the LED1 pin, and set it to output mode.
In an infinite loop, let the program continue to perform the following operations:
use led.toggle() to switch the state of the LED light (on and off).
Use time.sleep(1) to delay for 1 second to control the frequency of LED light status switching.

Case 8: Read button status:

import pyb

button = pyb.Pin("USR", pyb.Pin.IN)

while True:
    if button.value():
        print("Button pressed")
    else:
        print("Button released")

Interpretation of key points:
This program uses the pyb.Pin module to read the button status on the OpenMV Cam.
Use pyb.Pin("USR", pyb.Pin.IN) to instantiate a Pin object, connect it to the USR pin, and set it to input mode.
In an infinite loop, have the program continue to do the following:
Use button.value() to read the button's state. If the button is pressed, button.value() will return True; if the button is released, button.value() will return False.
According to the status of the button, use the print() function to output the corresponding information.

Case 9: PWM control steering gear:

import time
import pyb

servo = pyb.Servo(1)  # 连接到舵机的引脚号

while True:
    servo.angle(0)  # 设置舵机角度为0度
    time.sleep(1)
    servo.angle(90)  # 设置舵机角度为90度
    time.sleep(1)
    servo.angle(-90)  # 设置舵机角度为-90度
    time.sleep(1)

Interpretation of key points:
This program uses the pyb.Pin module to control the servo on the OpenMV Cam.
Use pyb.Servo(1) to instantiate a Servo object and connect it to the pin number of the servo (set according to the actual connection situation).
In an infinite loop, make the program continue to perform the following operations:
Use servo.angle() to set the angle of the servo. In the example, set the servo angles to 0 degrees, 90 degrees and -90 degrees respectively.
Use time.sleep(1) to delay for 1 second to control the rate of change of the servo angle.

These practical application examples show how to use the pyb.Pin module to control the functionality of OpenMV Cam. The first example demonstrates how to control an LED light on and off by setting the LED pin to output mode and using led.toggle() to toggle the state of the LED light. The second example shows how to read the button's state by setting the button pin to input mode and using button.value() to read the button's state. The third example demonstrates how to use PWM to control the servo by instantiating the Servo object and using servo.angle() to set the angle of the servo.

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