樹莓派和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>

 

效果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章