Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assemble a float from two bytes?

Tags:

c++

c

arduino

I am currently working on a project where I need to read out a DHT11 humidity and temperature sensor. The communication between the MCU and the serial device is quite low-level, but I managed to receive the measured values (humidity+temperature) as a byte array of length 4 (the 5th byte is the checksum):

Values that I receive from the DHT11 sensor:

- byte[0] = humidity integer part
- byte[1] = humidity decimal part
- byte[2] = temperature integer part
- byte[3] = temperature decimal part
- byte[4] = checksum of the first four bytes

I now would like to convert byte[0] and byte[1] to a float and the same for the temperature (byte[2] and byte[3]). What is an efficient way to accomplish this on an Arduino Mega 2560 in C/C++ ?

Example:

byte[0] = 20 and byte[1] = 12 => 20.12 [float]
like image 417
salocinx Avatar asked May 20 '17 09:05

salocinx


1 Answers

Unfortunately, both examples provided in the linked data sheet send zero for the decimal part. However, it appears from the description that the data from the upper byte can be added to the data from the lower byte divided by 256 (the number of states in the decimal portion of data):

const float scale = 256.0;
float humidity = byte[0] + (byte[1] / scale);
float temperature = byte[2] + (byte[3] / scale);
like image 69
Sergey Kalinichenko Avatar answered Sep 21 '22 18:09

Sergey Kalinichenko