51单片机通过esp01s将传感器数据发送到手机代码
时间: 2023-10-02 10:06:21 浏览: 93
由于你没有给出具体的传感器和手机接收方式,以下是一个基于DHT11温湿度传感器和通过WiFi连接的手机APP接收的示例代码:
```c
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <DHT.h>
#define DHTPIN 2 // DHT11传感器连接的引脚
#define DHTTYPE DHT11 // DHT11传感器类型
#define WIFI_SSID "你的WiFi名称"
#define WIFI_PASSWORD "你的WiFi密码"
#define SERVER_IP "你的手机IP地址"
#define SERVER_PORT 8888
DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial serial(4, 5); // ESP01S连接的引脚
void setup() {
Serial.begin(9600);
serial.begin(9600);
dht.begin();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\tTemperature: ");
Serial.print(temperature);
Serial.println(" °C");
String data = String(humidity) + "," + String(temperature);
serial.println(data);
delay(3000); // 每3秒发送一次数据
}
// 将数据发送到手机APP
void sendData(String data) {
WiFiClient client;
if (client.connect(SERVER_IP, SERVER_PORT)) {
client.println(data);
client.flush();
client.stop();
}
}
```
这个代码通过ESP8266连接WiFi,读取DHT11传感器的温湿度数据,并将数据通过ESP01S模块发送到手机APP。你需要替换代码中的WIFI_SSID、WIFI_PASSWORD、SERVER_IP和SERVER_PORT为你的WiFi名称、密码和手机APP接收的IP地址和端口号。另外,你需要在手机APP上实现对应的接收代码。
阅读全文