Skip to content

Commit 7c6d4ad

Browse files
committed
added crc8 check
1 parent 6ab874f commit 7c6d4ad

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

Core/Src/AHT20.c

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "AHT20.h"
2121
#include <stdio.h>
2222
#include <string.h>
23+
#include <math.h>
2324

2425
/*
2526
* device address for AHT20
@@ -53,6 +54,8 @@ static uint8_t INIT_CMD[3] = {0xbe, 0x08, 0x00};
5354
*/
5455
static uint8_t MEASURE_CMD[3] = {0xac, 0x33, 0x00};
5556

57+
static uint8_t calculate_crc(uint8_t *data);
58+
5659
/*
5760
* sends reads status_word for further calibration verification
5861
*
@@ -106,6 +109,8 @@ aht20_status_t aht20_calibrate(I2C_HandleTypeDef *hi2c, uint8_t status_word) {
106109
* 5.4 Sensor reading process, paragraph 2
107110
*/
108111
aht20_status_t aht20_measure(I2C_HandleTypeDef *hi2c, uint8_t *measured_data) {
112+
uint8_t received_crc = 0;
113+
109114
if (HAL_OK != HAL_I2C_Master_Transmit(hi2c, DEVICE_ADDRESS, MEASURE_CMD, 3, HAL_MAX_DELAY)) {
110115
return AHT20_STATUS_NOT_TRANSMITTED;
111116
}
@@ -114,15 +119,56 @@ aht20_status_t aht20_measure(I2C_HandleTypeDef *hi2c, uint8_t *measured_data) {
114119
uint8_t measuring_status = 0;
115120
HAL_I2C_Master_Receive(hi2c, DEVICE_ADDRESS, &measuring_status, 1, HAL_MAX_DELAY);
116121

117-
if(measuring_status & (1 << 7)) {
122+
uint8_t all_data[7];
123+
if (measuring_status & (1 << 7)) {
118124
return AHT20_STATUS_NOT_MEASURED;
119-
}else{
120-
HAL_I2C_Master_Receive(hi2c, DEVICE_ADDRESS, measured_data, 6, HAL_MAX_DELAY);
125+
} else {
126+
HAL_I2C_Master_Receive(hi2c, DEVICE_ADDRESS, all_data, 7, HAL_MAX_DELAY);
127+
}
128+
129+
// Copy 6 data bytes to measured_data
130+
for (uint8_t i = 0; i < 6; i++) {
131+
measured_data[i] = all_data[i];
132+
}
133+
received_crc = all_data[6]; // CRC is the 7th byte
134+
135+
uint8_t calculated_crc = calculate_crc(measured_data);
136+
if (calculated_crc == received_crc) {
137+
uint8_t ack = 0x06;
138+
if (HAL_OK != HAL_I2C_Master_Transmit(hi2c, DEVICE_ADDRESS, &ack, 1, HAL_MAX_DELAY)) {
139+
return AHT20_STATUS_NOT_TRANSMITTED;
140+
}
141+
} else {
142+
uint8_t nack = 0x15;
143+
if (HAL_OK != HAL_I2C_Master_Transmit(hi2c, DEVICE_ADDRESS, &nack, 1, HAL_MAX_DELAY)) {
144+
return AHT20_STATUS_NOT_TRANSMITTED;
145+
}
121146
}
122147

123148
return AHT20_STATUS_OK;
124149
}
125150

151+
/*
152+
* calculates crc8 for given data
153+
*/
154+
static uint8_t calculate_crc(uint8_t *data) {
155+
uint8_t crc = 0xFF;
156+
uint8_t i = 0, j = 0;
157+
158+
for (; i < 6; ++i) {
159+
crc ^= data[i];
160+
for (j = 0; j < 8; ++j) {
161+
if (crc & 0x80) {
162+
crc = (crc << 1) ^ 0x31;
163+
} else {
164+
crc <<= 1;
165+
}
166+
}
167+
}
168+
169+
return crc;
170+
}
171+
126172
/*
127173
* calculates measured_data and writes the calculation in provided variables
128174
*

0 commit comments

Comments
 (0)