HumidityDevice.h
2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#ifndef __HUMIDITY_DEVICE_H__
#define __HUMIDITY_DEVICE_H__
#include "mbed.h"
class HumidityDevice {
public:
const static char configReg_Address = 0x02;
const static char device_address = 0x80;
int length;
HumidityDevice(Serial *serial, I2C *i2c, bool shouldReadTemperature) : serial(serial), i2c(i2c),
shouldReadTemperature(shouldReadTemperature) {
if(shouldReadTemperature){
length = 4;
triggerMes_Address = 0x00;
} else {
length = 2;
triggerMes_Address = 0x01;
}
powRes = pow((double)2, (double)16);
}
/*
* Permet de lire le capteur d'humidité et d'obtenir ses valeurs.
*/
void read(char data[]) {
char cmd[1]={triggerMes_Address};
i2c->write(address_found, cmd, 1);
wait(0.2);
i2c->read(address_found, data, length);
if(shouldReadTemperature){
temp = (float((data[0] << 8)| data[1]) / powRes) * 165 - 40;
hum = (float((data[2] << 8)| data[3]) / powRes) * 100;
} else {
hum = (float((data[0] << 8)| data[1]) / powRes) * 100;
}
}
/*
* Permet de trouver le capteur d'humidité et son adresse. Assigne une adresse trouvée à
* la variable 'adress_found'.
*/
bool find() {
int count = 0;
bool res = false;
serial->printf("Searching for I2C devices...\n");
if (!i2c->write(device_address, NULL, 0)) //0 est renvoyé = capteur trouvé
{
serial->printf(" - I2C device found at address 0x%02X\n", device_address);
address_found = device_address;
res = true;
count++;
}
serial->printf("%d devices found\n\n", count);
return res;
}
/*
* Permet de configurer le capteur d'humidité.
*/
void setup() {
serial->printf("setting up device...\n");
char cmd[3] = {configReg_Address, 0x00, 0x00};
if(shouldReadTemperature){
cmd[1] = 0x10;
}
i2c->write(address_found, cmd, 3);
serial->printf("finished set up\n");
}
float getTemperature(){
return temp;
}
float getHumidity() {
return hum;
}
bool hasReadTemperature() {
return shouldReadTemperature;
}
private:
unsigned char address_found;
char triggerMes_Address;
Serial *serial;
I2C *i2c;
bool shouldReadTemperature;
float hum, temp;
float powRes;
};
#endif /* #ifndef __HUMIDITY_DEVICE_H__*/