【问题标题】:How to assemble a float from two bytes?如何从两个字节组装一个浮点数?
【发布时间】:2017-05-20 09:38:20
【问题描述】:

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

我从 DHT11 传感器收到的值:

- 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 上完成此任务的有效方法是什么?

例子:

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

【问题讨论】:

    标签: c++ c arduino


    【解决方案1】:

    不幸的是,链接数据表中提供的两个示例都为小数部分发送了零。但是,从描述中可以看出,可以将高字节的数据与低字节的数据相加除以256(数据小数部分的状态数):

    const float scale = 256.0;
    float humidity = byte[0] + (byte[1] / scale);
    float temperature = byte[2] + (byte[3] / scale);
    

    【讨论】:

    • 在 DHT11 的情况下,“十进制”部分很可能始终为 0。有些图书馆根本不费心去阅读它;有些甚至使用 0 值(湿度和温度)来区分 DHT11 和 DHT22。
    • 感谢您的快速回复。工作正常,虽然正如安德烈所提到的,小数部分确实总是为零。但我肯定会在我项目的另一部分使用它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2018-02-10
    • 2011-06-16
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多