赞
踩
在这个项目中,我们将使用ESP32微控制器读取温湿度传感器的数据,并将这些数据通过HTTP请求传输到基于Flask框架的服务器。Flask是一个轻量级的Python Web框架,非常适合快速开发和部署Web应用。通过这个项目,我们不仅可以了解ESP32的基本使用,还能体验Flask框架的便捷和强大功能。
硬件:
软件:
将DHT11或DHT22传感器连接到ESP32开发板:
首先,我们需要在Arduino IDE中编写ESP32的代码,以读取传感器数据并通过HTTP请求将数据发送到Flask服务器。
- #include <WiFi.h>
- #include <HTTPClient.h>
- #include <DHT.h>
-
- #define DHTPIN 4
- #define DHTTYPE DHT22
-
- const char* ssid = "your_SSID";
- const char* password = "your_PASSWORD";
- const char* serverName = "http://your_server_ip:5000/temperature";
-
- DHT dht(DHTPIN, DHTTYPE);
-
- 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");
- dht.begin();
- }
-
- void loop() {
- if (WiFi.status() == WL_CONNECTED) {
- HTTPClient http;
-
- float temperature = dht.readTemperature();
- float humidity = dht.readHumidity();
-
- if (isnan(temperature) || isnan(humidity)) {
- Serial.println("Failed to read from DHT sensor!");
- return;
- }
-
- String serverPath = serverName + "?temperature=" + String(temperature) + "&humidity=" + String(humidity);
-
- http.begin(serverPath.c_str());
- int httpResponseCode = http.GET();
-
- if (httpResponseCode > 0) {
- String response = http.getString();
- Serial.println(httpResponseCode);
- Serial.println(response);
- } else {
- Serial.print("Error on sending GET: ");
- Serial.println(httpResponseCode);
- }
-
- http.end();
- } else {
- Serial.println("WiFi Disconnected");
- }
-
- delay(60000); // Send data every 60 seconds
- }
接下来,我们编写Flask服务器的代码,以接收来自ESP32的数据并进行处理。
- from flask import Flask, request, jsonify
-
- app = Flask(__name__)
-
- @app.route('/temperature', methods=['GET'])
- def get_temperature():
- temperature = request.args.get('temperature')
- humidity = request.args.get('humidity')
- if temperature and humidity:
- print(f"Received temperature: {temperature}°C, humidity: {humidity}%")
- return jsonify({"status": "success", "temperature": temperature, "humidity": humidity})
- else:
- return jsonify({"status": "error", "message": "Missing temperature or humidity"}), 400
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=5000)
- p
确保已安装Flask库,可以通过以下命令安装:
pip install flask
然后,在终端中运行Flask服务器:
python app.py
通过这个项目,我们成功地使用ESP32读取温湿度传感器的数据,并将这些数据传输到基于Flask框架的服务器。Flask作为一个轻量级的Web框架,提供了简单、灵活和强大的功能,适合快速开发和部署物联网应用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。