|
|
from fpioa_manager import fm
|
|
|
from Maix import GPIO
|
|
|
from board import board_info
|
|
|
import time, network, socket
|
|
|
from machine import UART
|
|
|
|
|
|
|
|
|
|
|
|
WIFI_SSID = "junzekeji" # 替换为你的WiFi
|
|
|
WIFI_PASSWD = "234567890l" # 替换为你的WiFi密码
|
|
|
PC_IP = "192.168.89.6" # 替换为你的电脑IP
|
|
|
PC_PORT = 12345 # 替换为你的监听端口
|
|
|
|
|
|
def wifi_enable(en):
|
|
|
if wifi_en:
|
|
|
wifi_en.value(en)
|
|
|
|
|
|
|
|
|
|
|
|
# 定义UDP发送函数
|
|
|
def udp_send(ip, port, message):
|
|
|
"""向指定IP和端口发送UDP消息"""
|
|
|
try:
|
|
|
ADDR = (ip, port)
|
|
|
sock = socket.socket()
|
|
|
sock.connect(ADDR)
|
|
|
#sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
#sock.settimeout(1)
|
|
|
print(message, ip, port)
|
|
|
sock.send(message)
|
|
|
sock.close()
|
|
|
return True
|
|
|
except Exception as e:
|
|
|
print("UDP发送错误:", e)
|
|
|
return False
|
|
|
|
|
|
# 测试单次发送
|
|
|
def udp_client(server_ip, server_port):
|
|
|
message = "Hello from K210!"
|
|
|
if udp_send(server_ip, server_port, message):
|
|
|
print("已向 {}:{} 发送消息: {}".format(server_ip, server_port, message))
|
|
|
else:
|
|
|
print("向 {}:{} 发送消息失败".format(server_ip, server_port))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
# (1) GPIO 注册,用于 WiFi 使能
|
|
|
fm.register(8, fm.fpioa.GPIOHS0, force=True)
|
|
|
wifi_en = GPIO(GPIO.GPIOHS0, GPIO.OUT)
|
|
|
wifi_enable(0)
|
|
|
time.sleep_ms(200)
|
|
|
wifi_enable(1)
|
|
|
time.sleep(2)
|
|
|
|
|
|
# (2) 初始化 UART (115200)
|
|
|
fm.register(board_info.WIFI_RX, fm.fpioa.UART2_TX, force=True)
|
|
|
fm.register(board_info.WIFI_TX, fm.fpioa.UART2_RX, force=True)
|
|
|
uart = UART(UART.UART2, 115200, timeout=1000, read_buf_len=4096)
|
|
|
_ = uart.read() # 清空缓存
|
|
|
|
|
|
# (3) 初始化 ESP8285
|
|
|
try:
|
|
|
nic = network.ESP8285(uart)
|
|
|
except Exception as e:
|
|
|
print("ESP8285初始化失败:", e)
|
|
|
time.sleep(1)
|
|
|
|
|
|
# (4) 连接 WiFi
|
|
|
print("尝试连接 WiFi:", WIFI_SSID)
|
|
|
try:
|
|
|
nic.connect(WIFI_SSID, WIFI_PASSWD)
|
|
|
attempts = 0
|
|
|
while not nic.isconnected() and attempts < 20:
|
|
|
attempts += 1
|
|
|
print("等待连接... 第 {}/20 次".format(attempts))
|
|
|
time.sleep(1)
|
|
|
|
|
|
if nic.isconnected():
|
|
|
print("WiFi连接成功!")
|
|
|
print("IP信息:", nic.ifconfig())
|
|
|
#time.sleep(1)
|
|
|
else:
|
|
|
print("WiFi连接失败,请检查SSID或密码。")
|
|
|
time.sleep(1)
|
|
|
except Exception as e:
|
|
|
print("连接WiFi异常:", e)
|
|
|
|
|
|
# 测试单次发送
|
|
|
udp_client(PC_IP, PC_PORT)
|
|
|
|