在两个arduino之间使用NRF24L01发送多个传感器值

时间:2018-12-11 04:04:00

标签: arduino

我一直到处都在寻找答案,但是我很沮丧。我有2个arduino,它们正在使用NRF24L01收发器进行通信。我想发送2个传感器值,一个是浮点数,一个是整数。我尝试过:

1)分别发送。这些值似乎会在打印时产生干扰,从而在每个循环中创建一个额外的0和换行符。

2)将两个值组合成一个字符串。该字符串在另一端不可读。

我正在尝试以以下格式获取数据:

sensor1Val,sensor2Val

这是我的发射机代码示例:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 Transmitter(9, 10);

const byte address[6] = {"00001"};

int sensorVal1 = 0;
float sensorVal2 = 2.5;

void setup() {
Serial.begin(9600);

//TRANSMITTER STUFF//
Transmitter.begin(); 
Transmitter.openWritingPipe(address); 
Transmitter.setPALevel(RF24_PA_MIN); 
Transmitter.setChannel(87); 
Transmitter.setDataRate(RF24_250KBPS); 
Transmitter.stopListening(); 
}



void loop() 
{
Serial.print(sensorVal1);
Serial.print(", ");
Serial.println(sensorVal2);

Transmitter.write(&sensorVal1, sizeof(sensorVal1));
Transmitter.write(&sensorVal2, sizeof(sensorVal2));
delay(1000); //Wait 1s between measurements
sensorVal1++;
sensorVal2++;
} 

这是我的接收方代码的示例:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

RF24 Receiver(9, 10); 


const byte address[6] = {"00001"}; 
at a certain address (integer, 6)

int receive1;
float receive2;

void setup() {
Serial.begin(9600); 
Receiver.begin(); 
Receiver.openReadingPipe(0, address); 
Receiver.setPALevel(RF24_PA_MIN); 
Receiver.setChannel(87);
Receiver.setDataRate(RF24_250KBPS); 
Receiver.startListening(); 

}

void loop() {


 if (Receiver.available()) { 

    Receiver.read(&receive1, sizeof(receive1)); 
    Receiver.read(&receive2, sizeof(receive2));

    Serial.print(receive1);
    Serial.print(", ");
    Serial.println(receive2);

    delay(100);

   }
 }

我是arduino的新手,所以我们将不胜感激!

1 个答案:

答案 0 :(得分:0)

使用结构发送数据。

struct MyStruct {

  int sensorVal1;
  float sensorVal2;

};

发件人代码

MyStruct myStruct;
// initialise the members of the structure with the values you want
Transmitter.write(&myStruct, sizeof(myStruct));

接收方

MyStruct myStruct;
Receiver.read(&myStruct, sizeof(myStruct));