-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhdc2021debr.c
More file actions
94 lines (73 loc) · 1.92 KB
/
Copy pathhdc2021debr.c
File metadata and controls
94 lines (73 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
90
91
92
93
94
#include "hdc2021debr.h"
#include <stdbool.h>
#include <stdio.h>
static int hdc2021_write_reg(hdc2021debr_t *hdc2021, uint8_t reg, uint8_t data)
{
uint8_t buffer[2] = {reg, data};
return hdc2021->write_reg(buffer, hdc2021->dev_address, sizeof(buffer));
}
static int hdc2021_read_reg(hdc2021debr_t *hdc2021, uint8_t reg, uint8_t *data,
uint8_t length)
{
return hdc2021->read_reg(data, reg, hdc2021->dev_address, length);
}
int hdc2021_init(hdc2021debr_t *hdc2021, Write_ptr_hdc write_reg, Read_ptr_hdc read_reg,
uint8_t dev_address)
{
hdc2021->write_reg = write_reg;
hdc2021->read_reg = read_reg;
hdc2021->dev_address = dev_address << 1u;
return 0;
}
int hdc2021_toggle_heater(hdc2021debr_t *hdc2021, bool enable)
{
uint8_t device_config;
if (hdc2021_read_reg(hdc2021, REG_DEVICE_CONFIG, &device_config,
sizeof(device_config)))
{
return 1;
}
// the 3rd bit toggles the heater
if (enable)
{
device_config |= (1 << 3);
} else
{
device_config &= ~(1 << 3);
}
if (hdc2021_write_reg(hdc2021, REG_DEVICE_CONFIG, device_config))
{
return 1;
}
hdc2021->is_heater_enabled = enable;
return 0;
}
int hdc2021_trigger_oneshot(hdc2021debr_t *hdc2021)
{
uint8_t config;
if (hdc2021_read_reg(hdc2021, REG_MEASURE_CONFIG, &config, 1))
{
return 1;
}
config |= 0x01;
if (hdc2021_write_reg(hdc2021, REG_MEASURE_CONFIG, config))
{
return 1;
}
return 0;
}
int hdc2021_get_temp_humid(hdc2021debr_t *hdc2021)
{
uint8_t buffer[4];
if (hdc2021_read_reg(hdc2021, REG_TEMP_LOW, buffer, 4))
{
return 1;
}
uint16_t temp_bytes = ((uint16_t)(buffer[1]) << 8) | buffer[0];
uint16_t humid_bytes = ((uint16_t)(buffer[3]) << 8) | buffer[2];
float tempVal = (((float)temp_bytes/65536.0f) * 165.0f) - 40.0f;
hdc2021->temp = tempVal;
float humidVal = ((float)humid_bytes/65536.0f) * 100.0f;
hdc2021->humidity = humidVal;
return 0;
}