我正在使用NRF24L01进行无线通信。我的发射机代码是:
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
//int msg[1];
RF24 radio(2,9); // CSN, CE
const uint64_t pipe = 0xE8E8F0F0E1LL;
void setup(){
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(pipe);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
Serial.println("################## Set up complete ######################");
}
void loop(){
const char data[] = "hello world!";
radio.write(&data, sizeof(data));
Serial.println("message sent");
delay(1000);
}
我的接收方代码是:
#include "nRF24L01.h"
#include "RF24.h"
#include "SPI.h"
RF24 radio(8,7); // (CSN, CE)
const uint64_t pipe = 0xE8E8F0F0E1LL;
void setup(){
Serial.begin(9600);
radio.begin(); // Start the NRF24L01
radio.openReadingPipe(1,pipe); // Get NRF24L01 ready to receive
Serial.print("pipe open ... ");
radio.setPALevel(RF24_PA_MIN);
radio.startListening(); // Listen to see if information received
Serial.println("Listening: ready to recieve ...");
}
void loop(){
Serial.print("checking for radio signal ... ");
if (radio.available()){
Serial.print("| radio available | ");
char data[32] = ""; // delcare data
radio.read(&data, sizeof(data)); // read data from transmitter
Serial.println(data); // print data to serial
}
else {
Serial.println(" Nothing"); // print if nothing read
}
delay(500);
}
当发送器发送其数据时,接收器应该打印:
"checking for radio signal | radio available | "hello world!"
或者当发送方没有发送数据时,接收方会打印:
checking for radio signal | nothing
但是,接收方正在打印:
b'checking for radio signal ... Nothing\r\n'
b'checking for radio signal ... Nothing\r\n'
b'checking for radio signal ... | radio available | \xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x04\x18\x03?\x01fpipe open ... \r\n'
b'checking for radio signal ... | radio available | \xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x04\x18\x03?\x01fpipe open ... \r\n'
b'checking for radio signal ... Nothing\r\n'
b'checking for radio signal ... Nothing\r\n'
有人知道为什么我没有看到“ hello world”,而是得到了奇怪的字符串吗?
注意:即使关闭发射器,我也会得到相同的输出。
答案 0 :(得分:0)
在接收代码中,还存在逻辑错误。当您直接打印“已发送的消息”而没有任何条件时,无论消息是发送还是丢失,每次都会执行该消息。相反,您应该使用
if(radio.write(&data, sizeof(data))){
Serial.println("Message Sent");
}else{
Serial.println("Message not sent");
}
因为radio.write如果数据到达接收器,则返回TRUE。否则返回FALSE,表示数据已丢失。 这样做,您将意识到该消息不是仅被发送。 在RF24无线电(CE,CSN)中,CSN之前还提到了CE。