main.ino
[c]
#include "I2C.h"
I2C i2c;
byte buf[8];
float temp;
void setup()
{
//I2C
i2c.setup();
Serial.begin(115200);
while (!Serial) ;
}
void loop()
{
// Manifacture ID
i2c.read_reg(buf, 0x40, 0xfe, 2);
for(int i=0; i<2; i++){
Serial.print(buf[i] ,HEX);
}
Serial.println("");
// temperature
unsigned short _t;
i2c.read_reg(buf, 0x40, 0x00, 2);
_t = buf[0];
temp = 165.0 * ((_t << 8) | buf[1]) / 65536-40;
Serial.println(temp);
// humidity
i2c.read_reg(buf, 0x40, 0x02, 2);
_t = buf[0];
temp = 100.0 * ((_t << 8) | buf[1]) / 65536;
Serial.println(temp);
delay(1000);
}
[/c]
I2C.h
[c]
#ifndef I2C_H
#define I2C_H
#include "Wire.h"
class I2C {
public:
I2C();
int setup();
byte* I2C::read_reg(byte* buf, uint8_t addr,uint8_t reg, int num);
};
#endif
[/c]
I2C.cpp
[c]
#include "Arduino.h"
#include "I2C.h"
I2C::I2C() {
}
int I2C::setup() {
Wire.begin();
}
byte* I2C::read_reg(byte* buf, uint8_t addr,uint8_t reg, int num){
Wire.beginTransmission(addr);
Wire.write(reg);
Wire.endTransmission();
delay(50);
Wire.requestFrom(addr, num);
while (!Wire.available());
for (int i=0; i < num; i++) {
buf[i] = Wire.read();
}
return buf;
}
[/c]