主体代码为GPT生成,做了部分修改,调试通过,仅供测试参考。
main.py
import network
import socket
import machine
import time
import gc
import ujson
import uasyncio as asyncio
# 初始化以太网并启用 DHCP
lan = network.LAN()
lan.active(True)
lan.ifconfig('dhcp')
# 等待网络连接
while not lan.isconnected():
pass
print("以太网已连接,网络配置:", lan.ifconfig())
# 初始化 ADC
adc0 = machine.ADC(0) # 使用 ADC 通道 0,调整为具体引脚
adc1 = machine.ADC(1)
adc2 = machine.ADC(2)
# 获取ADC值并返回JSON数据
def handle_adc_request():
while True:
value0 = adc0.read_u16() # 读取ADC值,范围0-4095
value1 = adc1.read_u16()
value2 = adc2.read_u16()
data = ujson.dumps({
"adc1_value": value0,
"adc2_value": value1,
"adc3_value": value2
})
# 监听客户端请求
yield data
def serve_html():
with open('index.html', 'r') as f:
return f.read()
# 创建Web服务器并返回数据
async def web_server():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('Listening on', addr)
adc_generator = handle_adc_request()
while True:
cl, addr = s.accept()
print('Client connected from', addr)
request = cl.recv(1024)
print("Request:", request)
if b'GET /data' in request:
# 返回ADC的JSON数据s
try:
# 获取下一个ADC值
data = next(adc_generator)
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: application/json\r\n')
cl.send('Connection: close\r\n\r\n')
cl.send(data)
except StopAsyncIteration:
cl.send('HTTP/1.1 500 Internal Server Error\r\n')
cl.send('Connection: close\r\n\r\n')
cl.close()
elif b'GET /' in request:
# 返回HTML文件内容
html_content = serve_html()
cl.send('HTTP/1.1 200 OK\r\n')
cl.send('Content-Type: text/html\r\n')
cl.send('Connection: close\r\n\r\n')
cl.send(html_content)
cl.close()
else:
cl.send('HTTP/1.1 404 Not Found\r\n')
cl.send('Connection: close\r\n\r\n')
cl.close()
# 主程序
async def main():
await web_server() # 启动Web服务器
#free_memory = gc.mem_free()
#allocated_memory = gc.mem_alloc()
#print("Free memory:", free_memory, "bytes")
#print("Allocated memory:", allocated_memory, "bytes")
# 启动事件循环
asyncio.run(main())
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ADC Readings</title>
<script>
// 每秒请求一次ADC数据并更新页面
function fetchData() {
fetch('/data')
.then(response => response.json())
.then(data => {
// 更新页面显示的ADC值
document.getElementById('adc1_value').textContent = data.adc1_value;
document.getElementById('adc2_value').textContent = data.adc2_value;
document.getElementById('adc3_value').textContent = data.adc3_value;
})
.catch(error => console.error('Error fetching ADC data:', error));
}
// 页面加载时开始每秒请求一次数据
window.onload = function() {
setInterval(fetchData, 1000); // 每1秒请求一次数据
}
</script>
</head>
<body>
<h1>ADC Readings</h1>
<div>
<p>ADC1 Value: <span id="adc1_value">Loading...</span></p>
<p>ADC2 Value: <span id="adc2_value">Loading...</span></p>
<p>ADC3 Value: <span id="adc3_value">Loading...</span></p>
</div>
</body>
</html>
显示内容如下,每秒自动更新。