python - 使用 NRF24L01 将 Arduino 浮点值转换为 Python

标签 python c++ arduino raspberry-pi3

我试图通过 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

最佳答案

你应该收到 4 个字节(在大多数架构上,sizeof(float) 总是 4)所以检查你收到的数据:

if (len(receivedMessage) == 4)

四个字节代表一个 float ,所以要转换它:

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

四个字节转换为十六进制字符串并转换为 float 。

编辑(未测试):

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

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

关于python - 使用 NRF24L01 将 Arduino 浮点值转换为 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56210248/

相关文章:

python - 我需要使用 pylast 的 library.add_album 功能的帮助(python last.fm api 包装器)

python - 在列表中查找匹配和不匹配的项目

c++ - 是否有一组标准的编译器选项?

c++ - 如何将寄存器的值存储到指针指向的内存位置?

arduino - 使用 Arduino 解析 HTTP 响应的库

python - 在静态网站中本地检查死链接(使用 wget?)

python - 如何仅在评估模式下运行 TF 对象检测 API model_main.py

c++ - 如何从指向基类的唯一指针获取子类成员?

android - arduino ADK + android LED 闪烁示例编译错误

c++ - 是否可以隐藏 arduino 的库代码?