간단하게 온습도 센서만 부착했다.
#include <WiFi.h> //WIFI shield
#include <PubSubClient.h>
#include<DHT.h> //DHT.h 라이브러리 추가
DHT dht(13, DHT11); //DHT 설정 dht(핀, DHT종류)
char ssid[] = "";
char password[] = "";
const char* mqtt_server = "";
char nickname[] = "";
char mqtt_id[] = "";
char mqtt_pw[] = ";
unsigned long timer = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
for(int i = 0; i<500; i++){
delay(1);
}
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(nickname,mqtt_id,mqtt_pw)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
// Wait 5 seconds before retrying
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
dht.begin();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if(now - timer > 30 * 1000){
timer = now;
float tem = dht.readTemperature(); //온도 값 정수형 변수 tem에 저장
float hum = dht.readHumidity(); //습도 값 정수형 변수 hum에 저장
char cStr[6]; // number of digits + 1 for null terminator
dtostrf(tem,5,2, cStr); // int value, pointer to string, base number
client.publish("iot/temperature", cStr);
dtostrf(hum,5,2, cStr); // int value, pointer to string, base number
client.publish("iot/humidity", cStr);
Serial.println(tem);
Serial.println(tem);
}
}