[Diao Ye Learns Programming] MicroPython Manual WiPy Universal Board Control

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 of Python's core syntax.
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
WiPy is a MicroPython-based wireless microcontroller module that provides a complete hardware and software solution designed to simplify the development and deployment of Internet of Things (IoT) devices.

1. Microcontroller module: WiPy is a microcomputer module that integrates a processor, memory, wireless communication module and other necessary components. It is designed to provide a compact, low-power hardware platform capable of running high-level programming languages ​​​​such as MicroPython and having the ability to connect to the Internet and other devices.
2. MicroPython: MicroPython is a streamlined version of the Python programming language, specially developed for embedded systems and microcontroller design. It provides the core functions and syntax of the Python language, allowing developers to use familiar Python syntax for hardware control and IoT application development. As the operating environment of MicroPython, WiPy can directly interpret and execute MicroPython code.
3. Internet of Things (IoT): The Internet of Things refers to a network that connects various physical devices (such as sensors, actuators, embedded systems, etc.) through the Internet to achieve intelligence and interconnection. As a wireless microcontroller module, WiPy has wireless communication capabilities and can be connected to other devices and cloud platforms in the Internet of Things to achieve remote control and data exchange.
4. Wireless communication module: WiPy has one or more built-in wireless communication modules, common ones including Wi-Fi, Bluetooth, LoRa, etc. These wireless communication modules enable WiPy to communicate with other devices through wireless networks to achieve data transmission, remote control, cloud connection and other functions. Developers can choose appropriate wireless communication modules based on specific needs.
5. Development and deployment: WiPy provides a set of convenient development tools and development environment, allowing developers to quickly develop, debug and test applications. Once developed, WiPy can be deployed directly into actual IoT devices to communicate and interact with other devices. WiPy's compact design and low power consumption make it ideal for deployment in embedded systems and IoT devices.

Insert image description here
MicroPython's WiPy universal board control refers to the process of using the WiPy universal board for hardware control and IoT application development.

main feature:

Powerful hardware control capabilities: WiPy universal board integrates processor, memory and various interfaces (such as GPIO, UART, SPI, I2C, etc.), and has powerful hardware control capabilities. It supports programmatic control of various external devices, sensors and actuators to interact with the external world.

MicroPython Support: The WiPy Universal Board is developed based on MicroPython, a streamlined version of the Python programming language developed specifically for embedded systems and microcontroller designs. When using the WiPy universal board for control, you can directly use MicroPython language for programming, using rich Python libraries and syntax sugar to simplify the development process.

Rich communication interfaces: WiPy universal board provides a variety of communication interfaces, such as Wi-Fi, Bluetooth, LoRa, etc. These interfaces enable the WiPy universal board to communicate wirelessly with other devices to achieve data transmission, remote control and interconnection.

Cross-platform support: WiPy universal board has cross-platform features and can be developed and programmed on different operating systems (such as Windows, Linux, Mac OS, etc.). This allows developers to choose the appropriate development environment based on their preferences and needs, and code, debug and deploy on different platforms.

Application scenarios:

IoT application development: WiPy universal board control is suitable for various IoT application development scenarios, such as smart home, industrial automation, environmental monitoring, agricultural IoT, etc. Through the hardware control capabilities and communication interface of the WiPy universal board, sensors, actuators and the Internet can be easily connected to realize the intelligence and interconnection of IoT devices.

Embedded system development: WiPy universal board can be used as the control core of embedded systems to develop various embedded applications. It can be connected with other hardware modules (such as displays, buttons, sensors, etc.) to realize control and interaction of embedded devices.

Education and Learning: WiPy Universal Board Control is ideal for education and learning purposes. Because it uses MicroPython as the programming language, it is easy to learn and use, and is suitable for beginners to get started. By using the WiPy universal board for control experiments and project development, students can gain in-depth understanding of embedded systems, IoT technology, and Python programming.

Things to note:

Hardware connection: When using the WiPy universal board for control, you need to pay attention to the correct connection of external devices and sensors. Make sure the pins and power connections are set up correctly to avoid problems caused by incorrect hardware connections.

Power management: The power supply of the WiPy universal board needs to be stable and reliable. During the design and use process, attention needs to be paid to the stability and adaptability of the power supply to ensure the normal operation and stability of the equipment.

Exception handling and debugging: During the development process, you may encounter various problems and exceptions. It is necessary to master debugging skills and exception handling methods in order to detect and solve problems in time.

Code optimization and resource management: WiPy universal boards have limited processing power and memory capacity. During the development process, you need to pay attention to code optimization and resource management to avoid taking up too much memory and processor resources to ensure system stability and performance.

In summary, MicroPython's WiPy universal board control has powerful hardware control capabilities, supports MicroPython programming, rich communication interfaces and cross-platform support. It is suitable for IoT application development, embedded system development, and education and learning. During use, you need to pay attention to hardware connection, power management, exception handling and debugging, as well as code optimization and resource management. By fully understanding its characteristics and application scenarios, and paying attention to relevant matters, the development and application of WiPy universal board control can be efficiently carried out.

Insert image description here
When it comes to actual application development using MicroPython’s WiPy universal board, here are several reference code examples covering different application scenarios:

Case 1: Temperature and humidity sensor data collection and upload::

import machine
import time
import dht
import urequests

# 初始化温湿度传感器
sensor = dht.DHT11(machine.Pin(4))

# Wi-Fi网络连接
wifi_ssid = "your_wifi_ssid"
wifi_password = "your_wifi_password"
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)

while not wifi.isconnected():
    pass

# Wi-Fi连接成功,读取温湿度数据并上传
while True:
    try:
        sensor.measure()
        temperature = sensor.temperature()
        humidity = sensor.humidity()

        # 发送HTTP请求上传数据
        url = "http://api.example.com/data"
        headers = {
    
    "Content-Type": "application/json"}
        data = {
    
    "temperature": temperature, "humidity": humidity}
        response = urequests.post(url, json=data, headers=headers)
        print("数据上传成功")

    except Exception as e:
        print("数据采集和上传出现异常:", str(e))

    # 等待一段时间后再次采集和上传
    time.sleep(60)

This sample code demonstrates how to use the WiPy Universal Board to read data from a temperature and humidity sensor and upload the data to a specified API endpoint over a Wi-Fi network.

Case 2: LED flashing control::

import machine
import time

# 设置LED引脚
led_pin = machine.Pin(2, machine.Pin.OUT)

# 控制LED闪烁
while True:
    led_pin.on()
    time.sleep(1)
    led_pin.off()
    time.sleep(1)

This sample code shows how to control the blinking of an LED using the WiPy Universal Board. By controlling the status of the pin, the switching and flashing effects of the LED light are achieved.

Case 3: Buzzer music playback:

import machine
import time

# 设置蜂鸣器引脚
buzzer_pin = machine.Pin(5, machine.Pin.OUT)

# 定义音符频率
NOTE_C4 = 262
NOTE_D4 = 294
NOTE_E4 = 330
NOTE_F4 = 349
NOTE_G4 = 392
NOTE_A4 = 440
NOTE_B4 = 494

# 播放音乐
def play_music(notes, durations):
    for i in range(len(notes)):
        frequency = notes[i]
        duration = durations[i]
        buzzer_pin.on()
        time.sleep_ms(duration)
        buzzer_pin.off()
        time.sleep_ms(50)  # 音符间的间隔时间

# 定义音乐谱
twinkle_twinkle_notes = [NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4,
                         NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4]
twinkle_twinkle_durations = [400, 400, 400, 400, 400, 400, 800,
                             400, 400, 400, 400, 400, 400, 800]

# 播放"Twinkle Twinkle Little Star"
play_music(twinkle_twinkle_notes, twinkle_twinkle_durations)

This sample code shows how to control a buzzer to play music using the WiPy Universal Board. Simple music can be played by controlling the pin's state and setting note frequency and duration.

Case 4: Use MicroPython to control LED lights on and off

from machine import Pin
import time

# 初始化引脚2为输出模式
led = Pin(2, Pin.OUT)

while True:
    led.value(1)  # 点亮LED
    time.sleep(1)  # 延时1秒
    led.value(0)  # 熄灭LED
    time.sleep(1)  # 延时1秒

Case 5: Use MicroPython to read data from temperature and humidity sensors

from machine import I2C, Pin
import time

# 初始化I2C接口和DHT11传感器
i2c = I2C(scl=Pin(5), sda=Pin(4))
sensor = DHT11(i2c)

while True:
    # 读取温度和湿度数据
    temperature, humidity = sensor.read()
    print("Temperature: {0:.1f} C, Humidity: {1:.1f} %".format(temperature, humidity))
    time.sleep(5)  # 每5秒读取一次数据

Case 6: Using MicroPython to control steering gear rotation

from machine import Servo
import time

# 初始化舵机对象
servo = Servo(Pin(12), min_pulse=500, max_pulse=2500)

while True:
    # 设置舵机角度
    servo.write(0)  # 舵机转到0度
    time.sleep(2)  # 延时2秒
    servo.write(90)  # 舵机转到90度
    time.sleep(2)  # 延时2秒
    servo.write(180)  # 舵机转到180度
    time.sleep(2)  # 延时2秒

Case 7: Monitoring temperature and humidity via WiPy and sensors

from machine import Pin  
import network  
import utime  
  
# 设置WiPy的引脚和模式  
pin1 = Pin(5, Pin.IN) # 温湿度传感器信号线  
wlan = network.WLAN(network.STA_模式) # STA模式  
wlan.active(True)  
  
# 打印欢迎信息  
print("欢迎使用WiPy温湿度监测器")  
  
# 循环监测温湿度并上传到云平台  
while True:  
    # 读取温湿度传感器数据  
    temperature = pin1.value() * 4250 / 1024  
    humidity = pin1.value() * 100 / 1024  
    print("温度:%.2f C,湿度:%.2f %%" % (temperature, humidity))  
      
    # 将数据上传到云平台  
    url = "http://example.com/data" # 替换为实际的云平台URL  
    data = "temperature=%.2f&humidity=%.2f" % (temperature, humidity)  
    import http.client  
    conn = http.client.HTTPConnection(url)  
    conn.request("POST", "/", data)  
    res = conn.getresponse()  
    print(res.status, res.reason)  
    conn.close()  
      
    # 等待一段时间后再次读取数据  
    utime.sleep(10)

Case 8: Implementing timer switching through WiPy and LED lights

from machine import Pin  
import utime  
  
# 设置WiPy的引脚和模式  
pin = Pin(2, Pin.OUT) # LED灯控制引脚  
wlan = network.WLAN(network.STA_模式) # STA模式  
wlan.active(True)  
  
# 设定定时开关时间(这里为每天8点开关)  
while True:  
    # 获取当前时间并判断是否到达定时开关时间  
    now = utime.localtime()  
    current_time = utime.strftime("%H:%M:%S", now)  
    if current_time == "08:00:00": # 如果到达定时开关时间,就打开LED灯  
        pin.value(1)  
        print("LED灯已打开")  
        break  
    else: # 如果未到达定时开关时间,就继续等待  
        continue  
    utime.sleep(1) # 等待1秒钟后再次检测时间

Case 9: Controlling LED lights via WiPy and buttons

from machine import Pin  
import utime  
  
# 设置WiPy的引脚和模式  
pin_led = Pin(2, Pin.OUT) # LED灯控制引脚  
pin_button = Pin(5, Pin.IN) # 按钮控制引脚  
wlan = network.WLAN(network.STA_模式) # STA模式  
wlan.active(True)  
  
# 打印欢迎信息  
print("欢迎使用WiPy按钮控制LED灯")  
  
# 循环检测按钮状态并控制LED灯  
while True:  
    # 检测按钮状态  
    button_state = pin_button.value()  
    if button_state == 0: # 如果按钮未按下,就关闭LED灯  
        pin_led.value(0)  
        print("LED灯已关闭")  
    else: # 如果按钮已按下,就打开LED灯  
        pin_led.value(1)  
        print("LED灯已打开")  
    utime.sleep(0.1) # 等待0.1秒钟后再次检测按钮状态

These reference code examples of practical applications cover common use cases for WiPy universal board control, including sensor data collection and upload, LED control, and buzzer music playback. By referring to these sample codes, you can further develop and customize the application to fit your specific needs.

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