1+ #include "hdc2021debr.h"
2+ #include <stdbool.h>
3+ #include <stdio.h>
4+
5+ static int hdc2021_write_reg (hdc2021debr_t * hdc2021 , uint8_t reg , uint8_t data )
6+ {
7+ uint8_t buffer [2 ] = {reg , data };
8+ return hdc2021 -> write_reg (buffer , hdc2021 -> dev_address , sizeof (buffer ));
9+ }
10+
11+ static int hdc2021_read_reg (hdc2021debr_t * hdc2021 , uint8_t reg , uint8_t * data ,
12+ uint8_t length )
13+ {
14+ return hdc2021 -> read_reg (data , reg , hdc2021 -> dev_address , length );
15+ }
16+
17+ int hdc2021_init (hdc2021debr_t * hdc2021 , Write_ptr write_reg , Read_ptr read_reg ,
18+ uint8_t dev_address )
19+ {
20+ hdc2021 -> write_reg = write_reg ;
21+ hdc2021 -> read_reg = read_reg ;
22+ hdc2021 -> dev_address = dev_address << 1u ;
23+
24+ return 0 ;
25+ }
26+
27+ int hdc2021_toggle_heater (hdc2021debr_t * hdc2021 , bool enable )
28+ {
29+ uint8_t device_config ;
30+
31+ if (hdc2021_read_reg (hdc2021 , REG_DEVICE_CONFIG , & device_config ,
32+ sizeof (device_config )))
33+ {
34+ return 1 ;
35+ };
36+
37+ // the 3rd bit toggles the heater
38+ if (enable ) {
39+ device_config |= (1 << 3 );
40+ } else {
41+ device_config &= ~(1 << 3 );
42+ };
43+
44+ if (hdc2021_write_reg (hdc2021 , REG_DEVICE_CONFIG , device_config ))
45+ {
46+ return 1 ;
47+ };
48+
49+ return 0 ;
50+
51+ }
52+ /**
53+ * @brief triggers oneshot measurement
54+ *
55+ * @param hdc2021 - hdc2021debr driver
56+ * @return int - Status code
57+ */
58+ int hdc2021_trigger_oneshot (hdc2021debr_t * hdc2021 )
59+ {
60+ uint8_t config ;
61+
62+ if (hdc2021_read_reg (hdc2021 , REG_MEASURE_CONFIG , & config , 1 )) {
63+ return 1 ;
64+ }
65+
66+ config |= 0x01 ;
67+
68+ if (hdc2021_write_reg (hdc2021 , REG_MEASURE_CONFIG , config )) {
69+ return 1 ;
70+ }
71+
72+ return 0 ;
73+ }
74+
75+ int hdc2021_get_temp_humid (hdc2021debr_t * hdc2021 )
76+ {
77+ uint8_t buffer [4 ];
78+
79+ if (hdc2021_trigger_oneshot (hdc2021 )) {
80+ return 1 ;
81+ }
82+
83+
84+ if (hdc2021_read_reg (hdc2021 , REG_TEMP_LOW , buffer , 4 ))
85+ {
86+ return 1 ;
87+ };
88+
89+ uint16_t temp_bytes = (buffer [1 ] << 8 ) | buffer [0 ];
90+ uint16_t humid_bytes = (buffer [3 ] << 8 ) | buffer [2 ];
91+
92+ float tempVal = (((float )temp_bytes /65536.0f ) * 165.0f ) - 40.0f ;
93+ hdc2021 -> temp = tempVal ;
94+
95+ float humidVal = ((float )humid_bytes /65536.0f ) * 100.0f ;
96+ hdc2021 -> humidity = humidVal ;
97+
98+ return 0 ;
99+ }
0 commit comments