点此进入CSDN

点此添加QQ好友 加载失败时会显示




树莓派和esp8266之间使用tcp协议通信

 

树莓派代码:

复制代码
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);
}
复制代码

 

posted @   高颜值的殺生丸  阅读(137)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App

作者信息

昵称:

刘新宇

园龄:4年6个月


粉丝:1209


QQ:522414928

点击右上角即可分享
微信分享提示