树莓派和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>
效果:
多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。