1
0
mirror of https://github.com/rfivet/stm32bringup.git synced 2025-05-18 13:18:32 -04:00

Fix DHT11 temperature calculation for temperature below 0°C.

This commit is contained in:
Renaud 2025-02-04 13:20:11 +08:00
parent efd5cd28c7
commit 6f4e46a36f
4 changed files with 17 additions and 20 deletions

14
dht11.c
View File

@ -1,5 +1,5 @@
/* dht11.c -- DHT11 humidity and temperature sensor reading */
/* Copyright (c) 2020-2021 Renaud Fivet */
/* Copyright (c) 2020-2025 Renaud Fivet */
#include "dht11.h" /* implements DHT11 API */
@ -25,7 +25,7 @@
unsigned char dht11_humid ; /* 5 .. 95 %RH */
signed char dht11_tempc ; /* -20 .. 60 C */
unsigned char dht11_tempf ; /* .0 .. .9 C */
int dht11_deciC ; /* -200 .. 600 */
void dht11_init( void) {
/* At startup A13 is ALT DIO with Pull Up enabled */
@ -79,14 +79,12 @@ dht11_retv_t dht11_read( void) {
dht11_tempc = values[ 2] ;
dht11_tempf = values[ 3] ;
if( dht11_tempf & 0x80) {
dht11_tempc *= -1 ;
dht11_tempf = 10 - ( dht11_tempf & 0x7F) ;
if( dht11_tempf == 10) {
dht11_tempc -= 1 ;
dht11_tempf = 0 ;
}
dht11_tempc = -( dht11_tempc + 1) ;
dht11_tempf ^= 0x80 ;
}
dht11_deciC = dht11_tempc * 10 + dht11_tempf ;
return DHT11_SUCCESS ;
}

View File

@ -1,5 +1,5 @@
/* dht11.h -- DHT11 API */
/* Copyright (c) 2020 Renaud Fivet */
/* dht11.h -- DHT11 API */
/* Copyright (c) 2020-2025 Renaud Fivet */
typedef enum {
DHT11_SUCCESS,
@ -12,6 +12,7 @@ typedef enum {
extern unsigned char dht11_humid ; /* 5 .. 95 %RH */
extern signed char dht11_tempc ; /* -20 .. 60 C */
extern unsigned char dht11_tempf ; /* .0 .. .9 C */
extern int dht11_deciC ; /* -200 .. 600 */
void dht11_init( void) ;

View File

@ -1,5 +1,5 @@
/* dht11main.c -- sample DHT11 sensor */
/* Copyright (c) 2020-2023 Renaud Fivet */
/* Copyright (c) 2020-2025 Renaud Fivet */
#include <stdio.h>
#include "system.h"
@ -17,8 +17,8 @@ int main( void) {
if( 2 == (last % 5)) /* every 5 seconds starting 2s after boot */
switch( dht11_read()) {
case DHT11_SUCCESS:
printf( "%u%%RH, %d.%uC\n", dht11_humid, dht11_tempc,
dht11_tempf) ;
printf( "%u%%RH, %d.%uC, %d\n", dht11_humid, dht11_tempc,
dht11_tempf, dht11_deciC) ;
break ;
case DHT11_FAIL_TOUT:
puts( "Timeout") ;

View File

@ -196,13 +196,11 @@ And retest after the following modification.
dht11_tempc = values[ 2] ;
dht11_tempf = values[ 3] ;
if( dht11_tempf & 0x80) {
dht11_tempc *= -1 ;
dht11_tempf = 10 - ( dht11_tempf & 0x7F) ;
if( dht11_tempf == 10) {
dht11_tempc -= 1 ;
dht11_tempf = 0 ;
}
dht11_tempc = -( dht11_tempc + 1) ;
dht11_tempf ^= 0x80 ;
}
dht11_deciC = dht11_tempc * 10 + dht11_tempf ;
</pre>
<h2>Stability</h2>
@ -239,6 +237,6 @@ or how bad the measurements are.
<a href="33_ds18b20.html">Next</a>, I will use another digital thermometer as a
reference.
<hr>© 2020-2024 Renaud Fivet
<hr>© 2020-2025 Renaud Fivet
</body>
</html>