iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
自我挑戰組

Maker making IoT !!系列 第 23

[Day22] Esp32用STA mode + AHT10 - (程式碼講解)

1.前言

這邊主要是為解說前幾篇關於AHT10的程式碼,此次主要講的部分是loop中的程式碼,因為透過上次講解已經知道ESPAsyncWebServer不是透過loop分析數值的了,所以這邊會講解loop的部分。

2.程式碼

void loop(){  
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the AHT values
    previousMillis = currentMillis;
    // Read temperature as Celsius (the default)
    float newT = myAHT10.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    //float newT = AHT.readTemperature(true);
    // if temperature read failed, don't change t value
    if (isnan(newT)) {
      Serial.println("Failed to read from AHT sensor!");
    }
    else {
      t = newT;
      Serial.println(t);
    }
    // Read Humidity
    float newH = myAHT10.readHumidity();
    // if humidity read failed, don't change h value 
    if (isnan(newH)) {
      Serial.println("Failed to read from AHT sensor!");
    }
    else {
      h = newH;
      Serial.println(h);
    }
  }
}

第137行,AHT10會讀取溫度(單位預設為攝氏)
第149行,AHT10會讀取濕度
第141行,判斷newT的值是否為空值(nan)
第151行,判斷newH的值是否為空值(nan)

其實這邊程式碼大多都重複,因為就先讀取數值,在判斷是否空值(nan),如果是顯示錯誤訊息,如果不是就輸出數值,最需要注意的是讀取數值的資料型態,一定需要是浮點數(因為讀取的溫溼度值都有小數點)。

歡迎交流

好了,鐵人賽30天說長不長說短不短,如果從開頭看到這裡,那就代表你已經入門這塊領域了(師父引進門修行在個人),因為大多數簡單的程式碼都比我現在貼得可能都還少行,那複雜更困難的都會破百破千甚至更多,那今天講解稍微少點,因為下一篇會更加精彩,所以就留給明天的精彩表演拉(我是不是超級大划水阿)。


上一篇
[Day21] Esp32用STA mode + AHT10
下一篇
[Day23] Esp32 + LINE
系列文
Maker making IoT !!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言