使用arduino

时间:2019-05-03 11:04:10

标签: arduino-uno lorawan

我正在将两个Arduino UNO板与lora发送器和lora接收器接口,并通过发送“ Hello World”来测试互连,该“ Hello World”很容易被翻译成接收器串行监视器。

但是,当我将传感器连接到Arduino UNO并将其与lora-device接口时,它将传感器值作为int数据类型进行传输。因此,我尝试将int转换为string并将值存储在unit_8数据类型中,但是无法将unit_8数据类型转换为string

我的客户代码是:

#include <SPI.h>
#include <RH_RF95.h>
const int watermeterPin = 2;
volatile int  pulse_frequency;
unsigned int  literperhour;
unsigned long currentTime, loopTime;
byte sensorInterrupt = 0;
RH_RF95 rf95; 
void setup() 
{
  Serial.begin(9600);
  delay(500);
   pinMode(watermeterPin, INPUT); 
   attachInterrupt(sensorInterrupt, getFlow, FALLING);
   currentTime = millis();
   loopTime = currentTime;
  while (!Serial) ; 
  if (!rf95.init())
    Serial.println("init failed");
}
void loop()
{
  Serial.println("Sending to rf95_server");
  currentTime = millis();
   if(currentTime >= (loopTime + 1000))
   {
      loopTime = currentTime;
      literperhour = (pulse_frequency * 60 / 7.5);
      pulse_frequency = 0;
       Serial.print(literperhour, DEC);
   Serial.println(" Liter/hour");  
   }
   String str= String(literperhour);
  uint8_t data[] = str;
  rf95.send(data, sizeof(data));
  rf95.waitPacketSent();
  uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);
  if (rf95.waitAvailableTimeout(3000))
  {   
    if (rf95.recv(buf, &len))
   {
      Serial.print("got reply: ");
      Serial.println((char*)buf);   
   }
    else
    {
      Serial.println("recv failed");
    }
  }
  else
  {
    Serial.println("No reply, is rf95_server running?");
  }
  delay(400);
}
void getFlow ()
{ 
   pulse_frequency++;
} 

我的服务器代码是:

#include <SPI.h>
#include <RH_RF95.h>
RH_RF95 rf95;
int led = 10;
void setup() 
{
  pinMode(led, OUTPUT);     
  Serial.begin(9600);
  while (!Serial) ;
  if (!rf95.init())
    Serial.println("init failed");  
}
void loop()
{
  if (rf95.available())
  {  
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
       digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

String不能转换为uint8_t[]。因为:

  

错误:数组初始化程序必须是初始化程序列表或字符串文字

因此,不要这样做:

String str= String(literperhour);
uint8_t data[] = str; // <-- illegal assignment. String is not implicitly convertible to uint8_t
rf95.send(data, sizeof(data));

最好是这样做

String str= String(literperhour);
uint8_t data[] = str;
rf95.send(str.c_str(), str.length());

c_str()函数返回const unsigned char*(或类似类型),而length()返回String内部的字符数。