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

2024-06-09 14:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是Python中Raspberry Pi的代码

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


Tags: 数据importstringgpioincludepiraspberryradio
1条回答
网友
1楼 · 发布于 2024-06-09 14:35:28

您应该接收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 

相关问题 更多 >