树莓派代码:
from flask import Flask, render_template import socket import threading app = Flask(__name__) adc_value = 0 # 接收tcp数据 def receive_tcp_data(): global adc_value # 从ESP8266接收ADC数据 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('0.0.0.0', 5000)) sock.listen(1) while True: conn, addr = sock.accept() data = conn.recv(1024) adc_value = 70 - int(data.decode()) # print(conn,addr,adc_value) conn.close() @app.route('/') def index(): global adc_value # 在Web页面上显示ADC数据 return render_template('index2.html', adc_data=adc_value) # Web服务线程 def start_web_server(): app.run(host='0.0.0.0', port=8888) if __name__ == '__main__': # 启动接收tcp数据的线程 udp_thread = threading.Thread(target=receive_tcp_data) udp_thread.daemon = True udp_thread.start() # 启动接收tcp数据的线程 flask_thread = threading.Thread(target=start_web_server) flask_thread.daemon = True flask_thread.start() while True: pass
index2.html
<!DOCTYPE html> <html> <head> <title>ADC Data Display</title> </head> <body> <h1>ADC Data: {{ adc_data }}</h1> </body> </html>
esp8266 使用arduino
#include <ESP8266WiFi.h> #include <WiFiClient.h> const char* ssid = "litianmenzhenbu"; const char* password = "LT12345678"; const char* serverIP = "192.168.0.110"; // 树莓派的IP地址 const int serverPort = 5000; // 树莓派上Flask服务的端口号 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"); // 连接到树莓派上的Flask服务 WiFiClient client; if (client.connect(serverIP, serverPort)) { Serial.println("Connected to server"); } } void loop() { // 模拟读取ADC值,此处可替换为实际读取ADC的代码 int adcValue = analogRead(A0); // 发送ADC值到树莓派上的Flask服务 WiFiClient client; if (client.connect(serverIP, serverPort)) { String data = String(adcValue); client.print(data); client.flush(); client.stop(); } delay(100); }
标签:树莓,esp8266,tcp,client,ADC,data,adc From: https://www.cnblogs.com/LiuXinyu12378/p/17470533.html