3-2温度传感器( 二 )


void gettemperature(){int runs=0;do {temp_f = dht.readTemperature(false);humidity = dht.readHumidity();if(runs > 0){Serial.println("##Failed to read f rom DHT sensor! ###");}//Serial.println(String(temp_f).C_str());//Serial.println(String (humidity).C_str());runs++;}while(isnan(temp_f) && isnan(humidity));}
setup 函数部分把 继电器 和 LED 的引脚设置为 ,绿色LED在电源启动时默认为开启状态,如下所示:
void setup() {pinMode(RELAY_PIN, OUTPUT);pinMode(GREEN_LED, OUTPUT);pinMode(RED_LED, OUTPUT);digitalWrite(RELAY_PIN, LOW);digitalWrite(GREEN_LED, HIGH);digitalWrite(RED_LED, LOW);Serial.begin(115200);setup_wifi();client.setServer(mqtt_server, mqtt_port);client.setCallback(callback);if(SPIFFS.begin()){Serial.println(F("File system was mounted."));//检查我们是否具有除默认温度之外的所需温度File f = SPIFFS.open("/config_temp.txt" ,"r");if (!f){//现在阅读文件内容String s=f.readStringUntil('n');Serial.println(s);desired_temp = s.toFloat();//现在关闭文件f.close();} else {Serial.println(F("Failed to open my_file.txt"));}}}
使用提供的凭据连接到Wi-Fi网络,如下所示:
void setup_wifi() {delay(10);//我们首先连接到WiFi网络Serial.println();Serial.print(F("Connecting to "));Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED){WiFi.begin(ssid, password);Serial.print(".");delay(5000);}Serial.println(F("WiFi connected"));Serial.println(F("IP address :"));Serial.println(WiFi.localIP());}
以下是在订阅主题 /set 上收到新的MQTT消息时触发的 回调函数:
void callback(char* topic, byte* payload, unsigned int length){Serial.print(F("Message arrived ["));Serial.print(topic);Serial.print(F("] "));for(inti=0;i

3-2温度传感器

文章插图
to the MQTTin case some keep aliveare lost, as shown in thecode:
如果某些保持活动帧丢失,请重新连接到MQTT服务器,如以下代码所示:
void reconnect(){//循环直到我们重新连接while(!client.connected()){Serial.print(F("Attempting MQTT connection...") ) ;if(client.connect("ESP8266Client", mqtt_user, mqtt_passwd)){Serial.println(F("connected"));client.subscribe("thermostat/set");} else {Serial.print(F("failed, rc="));Serial.print(client.state( ));Serial.println(F("try again in 5 seconds"));//等待5秒再重试delay(5000);}}}
loop 函数是我们用于触发 继电器 和 LED ON或 OFF 的逻辑的地方 。每两秒钟读取一次温度并用我们想要的温度进行检查,如下所示:
void loop(){gettemperature();if(!client.connected()) {reconnect();}client.loop();long now = millis();if (now lastMsg > 2000) {lastMsg = now;if((float)desired_temp offset_temp >= (float)temp_f){//Serial.println(F("Start heating..."));digitalWrite (RELAY_ PIN, HIGH);digitalWrite (GREEN_ LED, LOW);digitalWrite(RED_ LED, HIGH);}else if((float)desired_temp + offset_temp <= (float)temp_f){//Serial. println(F("Stop heating..."));digitalWrite (RELAY_PIN, LOW);digitalWrite (GREEN_LED, HIGH);digitalWrite (RED_LED ,LOW);}client.publish ("thermostat/get", String(temp_f).c_str());}}
要设置温度,您可以使用MQTT代理的本地控制台,就像我们在第2章中所做的那样,Вu?ld?ng 和Соnf?gur?ngYоurОwnМQТТ?еrvеr: