esp32-wroom-32的联网光敏代码
时间: 2023-10-15 07:08:29 浏览: 96
以下是基于ESP32-WROOM-32的联网光敏代码示例(使用Arduino IDE):
```c++
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi信息
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// MQTT服务器信息
const char* mqtt_server = "your_MQTT_SERVER";
const int mqtt_port = 1883;
const char* mqtt_user = "your_MQTT_USER";
const char* mqtt_password = "your_MQTT_PASSWORD";
const char* mqtt_topic = "your_MQTT_TOPIC";
// 光敏电阻引脚
const int light_sensor_pin = 34;
// WiFi客户端
WiFiClient wifi_client;
// MQTT客户端
PubSubClient mqtt_client(wifi_client);
void setup_wifi() {
delay(10);
// 连接WiFi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect_mqtt() {
// Loop until we're reconnected
while (!mqtt_client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt_client.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
mqtt_client.publish(mqtt_topic, "hello world");
// ... and resubscribe
mqtt_client.subscribe(mqtt_topic);
} else {
Serial.print("failed, rc=");
Serial.print(mqtt_client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
mqtt_client.setServer(mqtt_server, mqtt_port);
mqtt_client.setCallback(callback);
}
void loop() {
if (!mqtt_client.connected()) {
reconnect_mqtt();
}
mqtt_client.loop();
// 读取光敏电阻值
int light_sensor_value = analogRead(light_sensor_pin);
// 发布光敏电阻值到MQTT服务器
String message = String(light_sensor_value);
mqtt_client.publish(mqtt_topic, message.c_str());
delay(10000);
}
```
注意,此示例仅用于演示目的,应根据实际情况进行修改。请确保正确配置WiFi和MQTT服务器信息,并根据需要更改光敏电阻引脚和发布间隔时间。
阅读全文