Try   HackMD

Arduino:DHT11 溫溼度感測器資料擷取

簡單筆記一下,板子是 Arduino UNO,感測器是 DHT11 Sensor,板子跟感測器的接線方式參考這篇文章

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Ref:http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino

紅線接 5V;黑線接地 GND;藍線接 7。

下載 Arduino IDE

Arduino IDE 官方載點:https://www.arduino.cc/en/software/
Python 官方載點:https://www.python.org/downloads/

編譯 Python 的 IDE 有很多種,這邊是使用 VSCode(官方載點

衍生閱讀:如何用 Visual Studio Code 在 WSL 中進行 Python 開發

導入 DHTLib

編譯以下程式碼前需要先下載這個 DHTLib Library 然後導入 IDE。

草稿碼 > 匯入程式庫 > 加入 ZIP 程式庫

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

開啟序列埠監控

#include <dht.h>

dht DHT;

#define DHT11_PIN 7

void setup(){
  Serial.begin(9600);
}

void loop(){
  int chk = DHT.read11(DHT11_PIN);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  delay(1000);
}

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

複製貼上以上程式碼進入 Arduino IDE 後,點擊畫面左上角的打勾圖示可以驗證,接著按旁邊的箭頭就可以上傳,要檢視序列埠監控視窗的話,按畫面最右上角的放大鏡圖示,進入序列埠監控視窗,就可以看到當前 Arduino 板接的感測器溫溼度資料了。9600 是 Baud(波特),右下角可以看到當前板子插在電腦哪個 Port 上(在這邊我的是接在 COM5)。

使用 Python 擷取資料

安裝 pyserial:指令 pip install pyserial

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這邊是用 VSCode 跑 python,簡單地擷取資料只要像以上短短幾行,如果後續要匯出成為 Excel 的 .csv 表格可以參考下方程式碼(需要先安裝 pip install pandas)。COM5 的埠部分要看板子是接在電腦哪裡,不一定是 COM5,有可能是 COM5

擷取資料成為 list

import serial
import time
import pandas as pd

arduino = serial.Serial("COM5", "9600") # 不同的電腦有可能不是接在 COM5 port
dataset_1 = []
dataset_2 = []
timeset = []
counter = 0 # 計時器

while(counter < 30 ): # 本程式僅擷取前三十秒資料
    counter = counter + 1
    data_1 = arduino.readline().decode("utf-8") # 記錄溫度
    data_2 = arduino.readline().decode("utf-8") # 記錄濕度
    nowtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    dataset_1.append(data_1)
    dataset_2.append(data_2)
    timeset.append(nowtime)
     
df = pd.DataFrame({'time':timeset,'hum':dataset_2, 'temp': dataset_1})
df.to_csv('./mydata.csv',index=False,encoding="utf-8")

匯出成為 Excel .csv 檔案

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


: : 20211028 : : 與松 withhhsong : :

tags: withhhsong tutorials python LectureNote arduino DHT11