// Create 2014/09/25 // UpDate 2014/09/26 // IC2-AM2321 // This example code is in the public domain. #include #define I2C_addr 0x5C byte I2cbuff[ 8 ]; void setup() { Serial.begin(9600); Serial.println("AM2321 Test Ver 0.4 Start"); Wire.begin(); } void loop() { unsigned short dat_sdh; unsigned short dat_sdt; while ( 1 ) { dat_sdh = getsdh(); dat_sdt = getsdt(); Serial.print( dat_sdt / 10 ); Serial.print( "." ); Serial.print( dat_sdt % 10); Serial.print( "C " ); Serial.print( dat_sdh / 10 ); Serial.print( "." ); Serial.print( dat_sdh % 10 ); Serial.println( "%" ); delay( 10000 ); } } //getsdt 気温を取得 //リターン:気温 30℃の場合は300 //先にgetsdh()で湿度を取得する事。 unsigned short getsdt( void ) { unsigned short hu; byte dat0 = I2cbuff[ 4 ]; byte dat1 = I2cbuff[ 5 ]; if ( dat0 & 0x80 ) { hu = ( ( ( dat0 & 0x7F ) * 256 ) + dat1 ); } else { hu = ( ( dat0 * 256 ) + dat1 ); } return hu; } #define ACK 0x00 #define NACK 0x01 //getsdh 湿度を取得 //リターン:湿度 80%の場合は800 unsigned short getsdh( void ) { unsigned short hu; int cnt; //AM2321を復帰させる Wire.beginTransmission( I2C_addr ); Wire.write( 0x00 ); delayMicroseconds( 800 ); Wire.endTransmission(); //[AM2321]データ読み取り命令 Wire.beginTransmission( I2C_addr ); Wire.write( 0x03 ); // 0x03レジスター・データの読み取り Wire.write( 0x00 ); // 読み取り開始する先頭アドレス Wire.write( 0x04 ); // 読み取るバイト数 Wire.endTransmission(); //AM2321待ち delayMicroseconds( 1500 ); //[AM2321]データの受信 Wire.requestFrom( I2C_addr, 8 ); delayMicroseconds( 30 ); cnt = 0; while ( Wire.available() ) { // 0:機能コード // 1:返送するバイト数 // 2:湿度-H // 3:湿度-L // 4:温度-H // 5:温度-L // 6:CRC-L // 7:CRC-H I2cbuff[ cnt ++ ] = Wire.read(); } hu = ( ( I2cbuff[ 2 ] * 256 ) + I2cbuff[ 3 ] ) ; return hu; }