【问题标题】:Arduino Float Value to Python using NRF24L01使用 NRF24L01 将 Arduino 浮点值转换为 Python
【发布时间】:2019-05-19 17:19:52
【问题描述】:

我试图通过 NRF24L01 将温度传感器数据发送到 Raspberry Pi 并使用 python 在 Raspberry Pi 中读取它。但是温度传感器数据以字母的形式出现在 Raspberry Pi 中,我发现它是 Ascii 值。我不确定如何显示从 Arduino 到 Raspberry Pi 的实际读数

这是 Arduino 代码:


#include <DallasTemperature.h>
#include <OneWire.h>
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define ONE_WIRE_BUS 2

OneWire oneWire (ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

RF24 radio(9, 10);

void setup(void) {

  Serial.begin(9600);
  sensors.begin();
  radio.begin() ;
  radio.setPALevel(RF24_PA_MAX) ;
  radio.setChannel(0x76) ;
  radio.openWritingPipe(0xF0F0F0F0E1LL) ;
  radio.enableDynamicPayloads() ;
  radio.powerUp() ;
}

void loop(void) {
  sensors.requestTemperatures();
  float temperature = sensors.getTempFByIndex(0);
  radio.write(&temperature, sizeof(float));
  delay(1000);
  Serial.print(sensors.getTempFByIndex(0));
}

这是 Raspberry Pi 在 Python 中的代码

from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()

while True:

    while not radio.available(0):
        time.sleep(1/100)

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating...")
    string = ""

    for n in receivedMessage:
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Our received message decodes to: {}".format(string))

我想用数字而不是字母来获取温度值。而不是这样:

翻译... 我们收到的消息解码为:N

【问题讨论】:

  • receivedMessage的大小是多少,收到后的具体内容是什么(radio.read)?

标签: python c++ arduino raspberry-pi3


【解决方案1】:

您应该收到 4 个字节(在大多数架构上,sizeof(float) 始终为 4)所以请检查您收到的数据:

if (len(receivedMessage) == 4)

四个字节代表一个浮点数,所以要转换它:

temperature = float.fromhex(''.join(format(x, '02x') for x in receivedMessage))

四个字节转换为十六进制字符串,再转换为浮点数。

编辑(未测试):

receivedMessage = []
radio.read(receivedMessage, radio.getDynamicPayloadSize())

if (len(receivedMessage) == 4)
   temperature = float.fromhex(''.join(format(x, '02x') for x in receivedMessage))
   print '%.2f' % temperature 

【讨论】:

  • 你应该关心计算机的字节顺序
  • @pytness 这是两个 ARM Cortex 处理器,所以我怀疑字节序会有所不同。但如果没有实际收到的数据,我无法确认这一点。
  • @Gerhard 感谢您的回复。我对编码有点陌生,你介意展示或告诉我将这些代码行放在哪里来检查数据大小并将其转换为浮点数吗?
猜你喜欢
  • 2018-01-30
  • 1970-01-01
  • 2020-03-21
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
相关资源
最近更新 更多