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

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

问题描述

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

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天全站免登陆