-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtu21d_lib.c
More file actions
90 lines (71 loc) · 1.92 KB
/
htu21d_lib.c
File metadata and controls
90 lines (71 loc) · 1.92 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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include "htu21d_lib.h"
/* *************************** */
/* HTU21D Sensor configuration */
/* *************************** */
/* Registers (No Hold master) */
#define HTU21D_REG_TEMP_NH 0xF3
#define HTU21D_REG_HUMID_NH 0xF5
#define HTU21D_REG_SOFT_RST 0xFE
/* Max measuring times - see page 3, 5 and 12 of the datasheet */
#define HTU21D_TEMP_MAX_TIME_MS 50
#define HTU21D_HUMID_MAX_TIME_MS 16
#define HTU21D_SOFT_RST_MAX_TIME_MS 15
/* ********* */
/* Functions */
/* ********* */
/* HTU21D: device initialization (for RPi I2C bus) */
int HTU21D_initPi(int *i2caddr)
{
int addr, fd;
addr = HTU21D_I2C_ADDR;
if (i2caddr != NULL)
if (*i2caddr > 0)
addr = *i2caddr;
fd = wiringPiI2CSetup(addr);
if (fd < 0)
return -1;
if (i2caddr != NULL)
*i2caddr = addr;
return fd;
}
/* Soft reset */
void HTU21D_softReset(int fd)
{
wiringPiI2CWrite(fd, HTU21D_REG_SOFT_RST);
delay(HTU21D_SOFT_RST_MAX_TIME_MS);
}
/* Get temperature */
double HTU21D_getTemperature(int fd)
{
unsigned int temp;
double tSensorTemp;
unsigned char buf[4];
wiringPiI2CWrite(fd, HTU21D_REG_TEMP_NH);
delay(HTU21D_TEMP_MAX_TIME_MS);
read(fd, buf, 3);
temp = (buf [0] << 8 | buf [1]) & 0xFFFC;
/* Convert sensor reading into temperature.
See page 14 of the datasheet */
tSensorTemp = temp / 65536.0;
return -46.85 + (175.72 * tSensorTemp);
}
/* Get humidity */
double HTU21D_getHumidity(int fd)
{
unsigned int humid;
double tSensorHumid;
unsigned char buf[4];
wiringPiI2CWrite(fd, HTU21D_REG_HUMID_NH);
delay(HTU21D_HUMID_MAX_TIME_MS);
read(fd, buf, 3);
humid = (buf [0] << 8 | buf [1]) & 0xFFFC;
/* Convert sensor reading into humidity.
See page 15 of the datasheet */
tSensorHumid = humid / 65536.0;
return -6.0 + (125.0 * tSensorHumid);
}