[Diao Ye Learns Programming] MicroPython Manual WiPy Wireless LAN (WiFi)

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 Wireless LAN (WiFi) is a feature for implementing wireless network connections.

main feature:

Wireless connectivity: The WiPy WiFi module has wireless connectivity and can communicate with other devices through the Wireless LAN (WiFi) protocol. It supports multiple WiFi standards and frequency bands to achieve wireless data transmission and reception.
Flexibility and scalability: The WiPy WiFi module is programmed using MicroPython language and is flexible and scalable. It can implement various WiFi functions by writing code, such as connecting to a specific network, sending and receiving data, etc.
Low power consumption design: The WiPy WiFi module adopts a low power consumption design and can run in low power consumption mode to extend the battery life of the device. This makes it suitable for the wireless connectivity needs of portable and low-power devices.

Application scenarios:

Internet of Things applications: WiPy WiFi modules are widely used in the field of Internet of Things (IoT) to achieve wireless communication and data transmission between devices. It can connect to wireless routers or other WiFi devices, exchange data with the cloud platform, and realize applications such as smart homes, smart cities, and industrial automation.
Remote control and monitoring: WiPy WiFi modules can be used to remotely control and monitor systems. For example, connect a WiPy device to a WiFi network to wirelessly control and monitor home security systems, smart devices, or industrial equipment.
Data acquisition and transmission: WiPy WiFi modules can be used for data acquisition and transmission applications. It can be connected to sensors or other data collection devices and transmit the collected data to a central server or cloud platform through a WiFi network to achieve real-time monitoring and analysis of data.

Precautions:

Security: When using the WiPy WiFi module, you need to pay attention to network security. Make sure to use a secure WiFi network with appropriate encryption and authentication mechanisms in place to prevent unauthorized access and data leakage.
Power management: The wireless connection of the WiPy WiFi module consumes a certain amount of power. During design and use, attention needs to be paid to reasonable power management to avoid excessive consumption of power and extend the battery life of the device.
Signal Strength and Coverage: The WiPy WiFi module’s wireless connection is limited by signal strength and coverage. When arranging equipment and planning the network, you need to consider the coverage of the WiFi signal and take corresponding measures to enhance signal strength and stability.

To sum up, MicroPython's WiPy WiFi module has wireless connection capabilities and is suitable for scenarios such as IoT applications, remote control and monitoring, and data collection and transmission. When using the WiPy WiFi module, you need to pay attention to aspects such as network security, power management, and signal strength and coverage to ensure the stability and reliability of the wireless connection.

Insert image description here
Case 1: Using MicroPython to connect to a WiFi network

from machine import WiFi
import time

wifi = WiFi()

while True:
    # 扫描附近的WiFi网络
    networks = wifi.scan()
    if len(networks) > 0:
        print("Connecting to network: {0}".format(networks[0]))
        # 连接到指定的WiFi网络
        wifi.connect(networks[0], password="your_password")
        while not wifi.isconnected():
            pass
        print("Connected to network: {0}".format(networks[0]))
    else:
        print("No nearby WiFi networks found.")
    time.sleep(5)  # 每5秒扫描一次

Case 2: Using MicroPython to disconnect from WiFi network

from machine import WiFi
import time

wifi = WiFi()

while True:
    # 断开当前连接的WiFi网络
    wifi.disconnect()
    print("Disconnected from network.")
    time.sleep(5)  # 每5秒断开一次连接

Case 3: Use MicroPython to set WiFi network connection timeout

from machine import WiFi
import time

wifi = WiFi()

# 设置连接超时时间为10秒
wifi.config(sta_timeout=10)

while True:
    # 等待WiFi连接成功或超时
    connected = wifi.wait_for_connection(timeout=10)
    if connected:
        print("Connected to network.")
    else:
        print("Connection timed out.")
    time.sleep(5)  # 每5秒检查一次连接状态

Case 4: Connect to WiFi network

from network import WLAN  
  
# 设置WiFi模式为STA模式  
wlan = WLAN(WLAN.STA)  
  
# 扫描可用的WiFi网络  
networks = wlan.scan()  
print("可用的WiFi网络:", networks)  
  
# 连接到名为"MyWiFi"的WiFi网络(密码为"mypassword")  
wlan.connect("MyWiFi", "mypassword")  
  
# 等待连接成功  
while not wlan.isconnected():  
    pass  
  
print("WiFi连接成功!")

Case 5: Sending data to the server over the network

from network import WLAN  
import socket  
  
# 初始化WLAN模块  
wlan = WLAN(WLAN.STA)  
  
# 连接到WiFi网络  
wlan.connect("MyWiFi", "mypassword")  
  
# 等待连接成功  
while not wlan.isconnected():  
    pass  
  
# 创建TCP套接字并绑定到本地IP地址和端口号  
server_address = ('localhost', 12345)  
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
sock.bind(server_address)  
  
# 监听连接请求  
sock.listen(1)  
print("等待连接...")  
  
# 接受客户端连接请求并发送数据到服务器  
while True:  
    client, addr = sock.accept()  
    print("连接来自:", addr)  
    data = "Hello, client!"  
    client.send(data.encode())  
    client.close()

Case 6: Using HTTP library to access resources on the Internet

import usocket  
import ubinascii  
import ure  # 正则表达式库  
import ujson  # JSON库  
from network import WLAN  
  
# 初始化WLAN模块并连接到WiFi网络  
wlan = WLAN(WLAN.STA)  
wlan.connect("MyWiFi", "mypassword")  
while not wlan.isconnected():  
    pass  
  
# 创建TCP套接字并连接到目标服务器  
server_address = ('www.example.com', 80)  
sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)  
sock.connect(server_address)  
  
# 发送HTTP请求并接收响应数据  
request = b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n'  
sock.send(request)  
response = sock.recv(1024)  
print("响应数据:", response)  
sock.close()

Case 7: A case of using the Blynk library to control LED lights on WiPy. Blynk is a platform for IoT projects that allows remote control of hardware on WiPy through a mobile app. code show as below:

# 导入 Blynk 库
from blynk import Blynk

# 创建一个 Blynk 实例,使用自己的授权码
b = Blynk('YourAuthToken')

# 定义一个回调函数,当虚拟引脚 V0 收到数据时触发
@b.VIRTUAL_WRITE(0)
def my_write_handler(value):
    # value 是一个字符串列表,例如 ['1']
    # 将字符串转换为整数
    value = int(value[0])
    # 如果值为 1,则点亮 WiPy 上的蓝色 LED
    if value == 1:
        pycom.rgbled(0x0000ff)
    # 如果值为 0,则关闭 LED
    elif value == 0:
        pycom.rgbled(0x000000)

# 启动 Blynk
b.run()

Case 8: A case 2 using the socket library to create a simple Web server. The web server can receive the client's HTTP request and return an HTML page showing WiPy's IP address and WiFi strength. code show as below:

# 导入 socket 库和 network 库
import socket
import network

# 创建一个 WLAN 对象,设置为 STA 模式
wlan = network.WLAN(mode=network.WLAN.STA)

# 连接到指定的 WiFi 网络,使用自己的 SSID 和密码
wlan.connect('your-ssid', auth=(network.WLAN.WPA2, 'your-password'))

# 等待连接成功
while not wlan.isconnected():
    pass

# 获取 WiPy 的 IP 地址和 WiFi 强度
ip = wlan.ifconfig()[0]
rssi = wlan.joined_ap_info()[3]

# 创建一个 socket 对象,设置为 TCP 模式和 IPv4 协议
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定 socket 到 WiPy 的 IP 地址和 80 端口
s.bind((ip, 80))

# 开始监听端口,最多允许 5 个连接
s.listen(5)

# 定义一个 HTML 页面的内容,使用 format 方法插入 IP 地址和 WiFi 强度
html = """<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WiPy Web Server</title>
</head>
<body>
    <h1>Hello from WiPy!</h1>
    <p>My IP address is: {}</p>
    <p>My WiFi strength is: {} dBm</p>
</body>
</html>
""".format(ip, rssi)

# 循环接受客户端的连接请求
while True:
    # 接受一个连接请求,返回一个客户端 socket 和地址
    client, addr = s.accept()
    # 打印客户端地址
    print('Got a connection from {}'.format(addr))
    # 接收客户端发送的数据,最多 1024 字节
    request = client.recv(1024)
    # 打印客户端发送的数据
    print('Request: {}'.format(request))
    # 向客户端发送 HTTP 响应头和 HTML 页面内容
    client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
    client.send(html)
    # 关闭客户端 socket
    client.close()

Case 9: Case 3 using the urequests library to send temperature data to the ThingSpeak platform. ThingSpeak is a platform for IoT data analysis and visualization, to which data can be sent or retrieved via HTTP requests. code show as below:

# 导入 urequests 库和 machine 库
import urequests
import machine

# 创建一个 ADC 对象,连接到 G3 引脚(WiPy 上的温度传感器)
adc = machine.ADC()
apin = adc.channel(pin='G3')

# 创建一个定时器对象
tim = machine.Timer.Alarm()

# 定义一个发送数据的函数,作为定时器的回调函数
def send_data(tim):
    # 读取温度传感器的电压值,转换为摄氏度
    volts = apin.voltage()
    celsius = (volts - 500) / 10
    # 打印温度值
    print('Temperature: {} C'.format(celsius))
    # 使用自己的 ThingSpeak API 密钥和温度值构造一个 URL
    url = 'https://api.thingspeak.com/update?api_key=YourAPIKey&field1={}'.format(celsius)
    # 向 URL 发送一个 GET 请求,获取响应对象
    response = urequests.get(url)
    # 打印响应状态码和内容
    print('Status: {}'.format(response.status_code))
    print('Content: {}'.format(response.text))
    # 关闭响应对象
    response.close()

# 启动定时器,每隔 10 秒钟调用一次发送数据的函数
tim.callback(send_data, ms=10000)

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