当前位置: 代码迷 >> 综合 >> 【ESP32】MicroPython Web服务控制IO输出
  详细解决方案

【ESP32】MicroPython Web服务控制IO输出

热度:3   发布时间:2024-01-17 12:07:51.0

一、准备工作

步骤1:将esp32连接到电脑,测试连接成功。

步骤2:创建boot.pymain.py

boot文件将在开机时运行一次,包括导入库、网络凭据、实例化PIN、连接网络等其他配置。

main文件运行网络服务接收客户端请求等。

二、boot

此处需要配置wifi账号(ssid)和密码(password)。

# Complete project details at https://RandomNerdTutorials.comtry:import usocket as socket
except:import socketfrom machine import Pin
import networkimport esp
esp.osdebug(None)import gc
gc.collect()ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'station = network.WLAN(network.STA_IF)station.active(True)
station.connect(ssid, password)while station.isconnected() == False:passprint('Connection successful')
print(station.ifconfig())led = Pin(2, Pin.OUT)

三、main

# Complete project details at https://RandomNerdTutorials.comdef web_page():if led.value() == 1:gpio_state="ON"else:gpio_state="OFF"html = """<html><head> <title>ESP Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,"> <style>html{
    font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}h1{
    color: #0F3376; padding: 2vh;}p{
    font-size: 1.5rem;}.button{
    display: inline-block; background-color: #e7bd3b; border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}.button2{
    background-color: #4286f4;}</style></head><body> <h1>ESP Web Server</h1> <p>GPIO state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">ON</button></a></p><p><a href="/?led=off"><button class="button button2">OFF</button></a></p></body></html>"""return htmls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)while True:conn, addr = s.accept()print('Got a connection from %s' % str(addr))request = conn.recv(1024)request = str(request)print('Content = %s' % request)led_on = request.find('/?led=on')led_off = request.find('/?led=off')if led_on == 6:print('LED ON')led.value(1)if led_off == 6:print('LED OFF')led.value(0)response = web_page()conn.send('HTTP/1.1 200 OK\n')conn.send('Content-Type: text/html\n')conn.send('Connection: close\n\n')conn.sendall(response)conn.close()

四、测试

上传boot和main到esp32板子后,点击版上的EN/RST按键。

几秒钟后可看见:
在这里插入图片描述
打开浏览器,输入刚刚的ip地址:
在这里插入图片描述
通过按钮来控制io的输出。