树莓派和esp8266在局域网下使用UDP通信,esp8266采集adc数据传递给树莓派,树莓派在web上显示结果
树莓派和esp8266需要在同一局域网下
esp8266使用arduino开发:
接入一个电容土壤湿度传感器,采集湿度需要使用adc
#include <ESP8266WiFi.h> #include <WiFiUdp.h> const char* ssid = "litianmenzhenbu"; const char* password = "LT12345678"; const char* serverIp = "192.168.0.110"; const int serverPort = 5005; const int adcPin = A0; WiFiUDP udp; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); udp.begin(udp.localPort()); } void loop() { int adcValue = analogRead(adcPin); Serial.print("adcValue:"); Serial.println(adcValue); udp.beginPacket(serverIp, serverPort); udp.write((byte*)&adcValue, sizeof(adcValue)); udp.endPacket(); delay(1000); }
树莓派使用python开发:
from flask import Flask, render_template import socket import threading app = Flask(__name__) # 设置树莓派的IP地址和端口 raspberry_pi_ip = '192.168.0.110' raspberry_pi_port = 5005 adc_value = 0 # 接收UDP数据 def receive_udp_data(): global adc_value udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_socket.bind((raspberry_pi_ip, raspberry_pi_port)) while True: data, _ = udp_socket.recvfrom(1024) adc_value = 70 - int.from_bytes(data, byteorder='little') # 在这里处理ADC数据,例如将其存储到数据库或进行其他操作 # 启动接收UDP数据的线程 udp_thread = threading.Thread(target=receive_udp_data) udp_thread.daemon = True udp_thread.start() # 网页主页 @app.route('/') def index(): # 在这里获取ADC数据,例如从数据库中读取最新的ADC值 return render_template('index1.html', adc_value=adc_value) if __name__ == '__main__': app.run(host='0.0.0.0', port=8888)
index.html
<!DOCTYPE html> <html> <head> <title>ADC Data</title> </head> <body> <h1>ADC Data: {{ adc_value }}</h1> </body> </html>
效果:
多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App