SX1278 LoRa with Arduino cannot send or receive more than 1 byte

1.3k views Asked by At

I am making a project with LoRa which needs to control 4 servos but through LoRa communication so I sent it like for the first servo it should send values from 0-180 and for the next servo I sent 181 - 361 and goes on for 4 servos! But unfortunately it cannot send values fore that 255 which I guess is 1 byte and if I try to send more that 255 for example 256 it receives as 0 and 257 as 1 and goes on. Is there a commend or way to increase it by a initializing command? Because I know that Lora can send unto 63 bytes.I will attach the code below(Simplified with a simple code):

Sender code(TX)(Arduino UNO):

    #include <SPI.h>
    #include <LoRa.h>
    
    int val = 256;
    void setup() {
      Serial.begin(9600);
      while (!Serial);
    
      Serial.println("LoRa Sender");
    
      if (!LoRa.begin(433E6)) {
        Serial.println("Starting LoRa failed!");
        while (1);
      }
    }
    
    void loop() {
      Serial.print("Sending packet: ");
    
      // send packet
      LoRa.beginPacket();
      LoRa.print(val);
      LoRa.endPacket();
    
      delay(500);
    }

Receiver Code(RX)(Arduino Mega):

   #include <SPI.h>
   #include <LoRa.h>
   
   #define LORA_SS 53
   #define LORA_RST 9
   #define LORA_DIO0 8
   String val;
   
   void setup() {
     pinMode(LORA_SS, OUTPUT);
     digitalWrite(LORA_SS, HIGH);
   
     LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
     Serial.begin(9600);
     
     while (!Serial);
   
     Serial.println("LoRa Receiver");
   
     if (!LoRa.begin(433E6)) {
       Serial.println("Starting LoRa failed!");
       while (1);
     }
   }
   
   void loop() {
     // try to parse packet
     int packetSize = LoRa.parsePacket();
     if (packetSize) {
       // received a packet
       Serial.print("Received packet '");
   
       // read packet
       while (LoRa.available()) {
         val = LoRa.read();
        
       }
      
       Serial.print(val.toInt());
       // print RSSI of packet
       Serial.print("' with RSSI ");
       Serial.println(LoRa.packetRssi());
     }
   }

Output of the Receiver :

Received packet '0' with RSSI -5
1

There are 1 answers

4
hcheung On

Your val in the int val = LoRa.read(); has a scope only within the while loop. So when you access it outside of the scope, you get 0.

Move the declaration of the val outside of the while loop.

int val;
while (LoRa.available()) {
   val = LoRa.read();
}
Serial.print(val.toInt());