将昨日的驱动改成了一个 Arduino 的库,可以更方便的使用
库为两个文件: dh21.h 和 dh21.cpp
在 E:\arduino-0022\libraries\ 下建立 DH21 目录,把这两个文件置于其中即可使用(由此可见 Arduino 的库创建和使用都很方便),重启 Arduino 开发环境后,可在 Sketch –> Import Library 下看到 DH21
使用示例如下:
#include <dh21.h> /* the data line of DH21 is pluged in digital pin #12 */ DH21 dh21(12); void setup() { Serial.begin(9600); } void loop() { if(dh21.get_data() == -1) Serial.println("Read DH21 error"); else { Serial.print("Temperature: "); Serial.print(dh21.temperature()); Serial.print("C "); Serial.print("Humidity: "); Serial.print(dh21.humidity()); Serial.println("%"); } /* read after 5 seconds */ delay(5000); }
运行界面:
dh21.h:
/* * dh21.h - Library for DH21/AM2301 digital temperature sensor * Created by Jack Tan <jiankemeng@gmail.com> * Released into the public domain. */ #ifndef _DH21_H_ #define _DH21_H_ #include "WProgram.h" class DH21 { public: DH21(int pin); float temperature(); float humidity(); byte get_data(); byte data_check(); private: byte read_8bits(); int pin; byte RH_H; byte RH_L; byte T_H; byte T_L; byte crc; }; #endif
dh21.cpp
/* * dh21.cpp - Library for DH21/AM2301 digital temperature sensor * Created by Jack Tan <jiankemeng@gmail.com> * Released into the public domain. */ #include "WProgram.h" #include "dh21.h" DH21::DH21(int p) { pin = p; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); } byte DH21::get_data() { byte flag; pinMode(pin, OUTPUT); /* Bus Low, delay 1 - 5ms */ digitalWrite(pin, LOW); delay(4); /* Bus High, delay 40us */ digitalWrite(pin, HIGH); delayMicroseconds(40); pinMode(pin, INPUT); if(digitalRead(pin) == 0) { flag = 2; /* waitting the ACK signal (Low, 80us) */ while((digitalRead(pin) == 0) && flag++); flag = 2; /* waitting the DATA Start signal (High, 80us) */ while((digitalRead(pin) == 1) && flag++); RH_H = read_8bits(); RH_L = read_8bits(); T_H = read_8bits(); T_L = read_8bits(); crc = read_8bits(); pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); return 0; } else return -1; } byte DH21::read_8bits() { byte i, flag, data = 0; byte temp; for(i=0; i<8; i++) { flag = 2; while((digitalRead(pin) == 0) && flag++); delayMicroseconds(30); temp = 0; if(digitalRead(pin) == 1) temp = 1; flag = 2; while((digitalRead(pin) == 1) && flag++); if(flag == 1) break; data <<= 1; data |= temp; } return data; } byte DH21::data_check() { byte tmp = (T_H + T_L + RH_H + RH_L); if(tmp != crc) { RH_H = 0; RH_L = 0; T_H = 0; T_L = 0; return -1; } else return 0; } float DH21::temperature() { int T = (T_H << 8 ) | T_L; float tt; if(T >= 0) tt = T/10 + (T%10) * 0.1; else { T = T & 0x7fff; tt = -(T/10 + (T%10) * 0.1); } return tt; } float DH21::humidity() { int RH = (RH_H << 8 ) | RH_L; float hum; hum = RH/10 + (RH%10) * 0.1; return hum; }