如何从两个字节组装一个浮点数? [英] How to assemble a float from two bytes?

查看:555
本文介绍了如何从两个字节组装一个浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个项目,需要读取 DHT11湿度和温度传感器. MCU和串行设备之间的通信非常低级,但是我设法以长度为4的字节数组(第五个字节为校验和)接收测量值(湿度和温度):

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):

我从DHT11传感器收到的值:

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

我现在想将byte[0]byte[1]转换为浮点数,并且将温度转换为相同的值(字节[2]和字节[3]).在C/C ++的Arduino Mega 2560上实现此目的的有效方法是什么?

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++ ?

示例:

byte[0] = 20 and byte[1] = 12 => 20.12 [float]

推荐答案

不幸的是,链接数据表中提供的两个示例的小数部分均为零.但是,从描述中可以看出,可以将高位字节的数据加到低位字节的数据除以256(数据的小数部分中的状态数):

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);

这篇关于如何从两个字节组装一个浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆