SX1278 LoRa Receiver mismatched data being received

I am creating a LoRa based Water Level Alarm System. Now I have a problem when the data is being sent to my Receiver, the RX Serial looks like this:

9:26:57.353 -> Received Distance: Ǯ cm
19:27:01.669 -> Received Distance: \���xe�]�۸L�
19:27:01.714 -> 5����~	b:1���A����^;3}΀Wa >
19:27:01.750 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:01.983 -> 5����~	b:1���A����^;3}΀Wa >
19:27:02.017 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:02.250 -> 5����~	b:1���A����^;3}΀Wa >
19:27:02.283 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:02.516 -> 5����~	b:1���A����^;3}΀Wa >
19:27:02.549 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:02.782 -> 5����~	b:1���A����^;3}΀Wa >
19:27:02.815 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:03.048 -> 5����~	b:1���A����^;3}΀Wa >
19:27:03.081 -> ��Ӡeȕ�)��A���%u��M��Yv%�dc<x�|��t��`����܆����l�� VPպ�ʠ�2˾��y�ʵX�����.k�K��5p�_�e��1+'n�����Tۮ��l-|�	���e8��9�gQ[y���{��v�Ӏzx��������23llo�dR&�
0��$�0��k�EV�/��Ǯ\���xe�]�۸L�
19:27:03.280 -> 5 cm
//Transmitter Code
#include <SPI.h>
#include <LoRa.h>
#include <NewPing.h>

// LoRa Pins
#define LORA_SCK 13
#define LORA_MISO 12
#define LORA_MOSI 11
#define LORA_SS 10
#define LORA_RST 9
#define LORA_DIO0 2

// Ultrasonic Pins
#define TRIGGER_PIN 5
#define ECHO_PIN 6
#define MAX_DISTANCE 40 // Maximum distance to measure (in cm)

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

  LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa initialization failed!");
    while (1);
  }
  Serial.println("LoRa initialized.");
}

void loop() {
  // Get distance from ultrasonic sensor
  unsigned long distance = sonar.ping_cm();

  // If valid distance is measured, send it via LoRa
  if (distance > 0) {
    LoRa.beginPacket();
    LoRa.print(distance);  // Convert the integer to string automatically
    LoRa.endPacket();
    Serial.print("Sent Distance: ");
    Serial.println(distance);
  } else {
    Serial.println("Distance measurement failed.");
  }

  delay(5000);
}
//Receiver Code
#include <SPI.h>
#include <LoRa.h>

// LoRa Pins
#define LORA_SCK 13
#define LORA_MISO 12
#define LORA_MOSI 11
#define LORA_SS 10
#define LORA_RST 9
#define LORA_DIO0 2

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

  LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa initialization failed!");
    while (1);
  }
  Serial.println("LoRa initialized.");
}

void loop() {
  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    String receivedData = "";
    while (LoRa.available()) {
      receivedData += (char)LoRa.read(); // Read the incoming data as a string
    }

    receivedData.trim();  // Remove any whitespace/newlines

    if (receivedData.length() > 0) {
      // Print the received distance
      Serial.print("Received Distance: ");
      Serial.print(receivedData);
      Serial.println(" cm");
    }
  }
}

Is there a way to fix this? I have tried sending 'Hello' earlier, just two LoRa communicating, and It worked without delay. But when I added my Ultrasonic, it became like random characters(?)

what host microcontrollers are you using?
what LoRa module are you using?
how have you connected the modules?
does the transmitter report the distance OK?

I am using both Arduino Uno(CH340)
RA-02 SX1278 LoRa modules
Yes, they are connected, and I check the wires and made sure they are connected properly
Transmitter is sending the distance flawlessly based on the Serial Monitor:

19:43:07.506 -> Sent Distance: 24
19:43:12.509 -> Sent Distance: 26
19:43:17.520 -> Sent Distance: 25
19:43:22.527 -> Sent Distance: 25
19:43:27.522 -> Sent Distance: 23

EDIT:

RX Serial received the data but there are random characters:
19:48:31.282 -> Received Distance: clR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX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;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%$c<ppt`(lVT2yX&[s=p_e0)%nT[l-|=gQ[>y[QzxclR&0$0klEV/9e]L5T~b:!A0V;3}W y[)AE%uIYv%

still same code, but I added a block to ignore the non-printable characters for RX

you are using the String class on a UNO - it's use not recommended with low power micros as it can fragment the memory - initially try a simple read and print, e.g.

   while (LoRa.available()) {
      Serial.print((char)LoRa.read());
    }

the UNO uses 5V logic LoRa modules generally use 3.3V logic - you should use level shifters to convert between the levels

Even when the LoRa module is connected to 3.3V pin? I'll try using it when it arrive.

Also tried using characters, it received 21cm but after that it became another bunch of random characters non-stop printing

Connecting the LoRa device to the 3.3V power pin on the UNO does not stop the UNO using 5V logic level signals to the 3.3V logic level LoRa device.

Also in a lot of cases the UNO 3.3V supply pin cannot provide enough current to run a LoRa module as a transmitter.

Thanks for the clarification. I'll use level shifters when it arrive.

Is it possible that the data I received was cause by the power? This is my first time using LoRa

even if the LoRa module is powered from 3.3V the logic level outputs from the UNO are 5V
could there be other LoRa modules or devices transmitting locally at 433MHz possible corrupting the LoRa signals?

Possible.

If the LoRa device power supply is not adequate, the transmissions can be corrupted.

Dont use the setup until you have logic level conversion in place, the 5V signals from the UNO can damage the LoRa module.

Thanks, will try it. I'll update once the component is here

if I run your post 1 code on a couple of Adafruit 32U4 LoRa modules (modified pin and frequency settings) both transmitter and receiver work OK
transmitter serial monitor (distance set to 45)

15:01:01.163 -> Received Distance: 45 cm
15:01:06.184 -> Received Distance: 45 cm
15:01:11.195 -> Received Distance: 45 cm
15:01:16.225 -> Received Distance: 45 cm
15:01:21.242 -> Received Distance: 45 cm

receiver

Received Distance: 45 cm
Received Distance: 45 cm
Received Distance: 45 cm
Received Distance: 45 cm

so code looks basically OK
you could be having problems with logic levels, power supplies, interference, etc etc

EDIT: replaced one of the Feather 32U4 LoRa modules with a UNO with a Dragino LoRa shield running transmitter code - serial monitor

5:16:32.854 -> Sent Distance: 45
15:16:37.899 -> Sent Distance: 45
15:16:42.913 -> Sent Distance: 45
15:16:47.954 -> Sent Distance: 45
15:16:52.971 -> Sent Distance: 45

Feather 32U4 LoRa receiver receives OK

15:24:10.224 -> Received Distance: 45 cm
15:24:15.244 -> Received Distance: 45 cm
15:24:20.293 -> Received Distance: 45 cm
1 Like

I tried something else while the level shifter is not here, instead of sending values, I sent the Equivalent using the TX:

  if (distance > 0 && distance < 11) {
    message = "L3";
  } else if (distance >= 11 && distance < 21) {
    message = "L2";
  } else if (distance >= 21 && distance <= 40) {
    message = "L1";
  }

Now, the Receiver received it, and did what it needed to do, play track depending on which level is sent and sent an Acknowledgement to continue detecting and sending data, but when the Transmitter is sending new Level, Receiver is not receiving the said Level:

//TX Code
#include <SPI.h>
#include <LoRa.h>
#include <NewPing.h>

// LoRa Pins
#define LORA_SCK 13
#define LORA_MISO 12
#define LORA_MOSI 11
#define LORA_SS 10
#define LORA_RST 9
#define LORA_DIO0 2

// Ultrasonic Pins
#define TRIGGER_PIN 5
#define ECHO_PIN 6
#define MAX_DISTANCE 40 // Maximum distance to measure

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

bool waitForACK(int timeout) {
  unsigned long startTime = millis();
  while (millis() - startTime < timeout) {
    int packetSize = LoRa.parsePacket();
    if (packetSize) {
      String received = "";
      while (LoRa.available()) {
        received += (char)LoRa.read();
      }
      if (received == "ACK") {
        Serial.println("Acknowledgement received!");
        return true;
      }
    }
  }
  Serial.println("Acknowledgement not received.");
  return false;
}

void setup() {
  Serial.begin(9600);
  LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);

  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa initialization failed!");
    while (1);
  }
  Serial.println("LoRa initialized.");
}

void loop() {
  // Get distance from ultrasonic sensor
  unsigned int distance = sonar.ping_cm();

  const char *message = nullptr; // Pointer for message selection

  // Categorize distance and assign message
  if (distance > 0 && distance < 11) {
    message = "L3";
  } else if (distance >= 11 && distance < 21) {
    message = "L2";
  } else if (distance >= 21 && distance <= 40) {
    message = "L1";
  }

  // Send LoRa message if a valid category was assigned
  if (message) {
    int attempts = 0;
    bool ackReceived = false;

    while (attempts < 3 && !ackReceived) { // Retry up to 3 times
      LoRa.beginPacket();
      LoRa.print(message);
      LoRa.endPacket();

      Serial.print("Sent Message: ");
      Serial.println(message);

      ackReceived = waitForACK(25000); // Wait 25 seconds for acknowledgment
      attempts++;
    }

    if (!ackReceived) {
      Serial.println("Failed to receive acknowledgment after 3 attempts.");
    }
  } else {
    Serial.println("Distance out of range.");
  }

  delay(10000); // Wait before next detection cycle
}
//RX Code
#include <SPI.h>
#include <LoRa.h>
#include <SoftwareSerial.h>

// LoRa Pins
#define LORA_SCK 13
#define LORA_MISO 12
#define LORA_MOSI 11
#define LORA_SS 10
#define LORA_RST 9
#define LORA_DIO0 2

// MP3-TF-16P Module Pins
#define MP3_RX 4  // Connect to TX of MP3 module
#define MP3_TX 3  // Connect to RX of MP3 module

SoftwareSerial mp3Serial(MP3_RX, MP3_TX);
bool isPlaying = false; // Flag to prevent receiving new data while playing

// Flags for level detection
bool level1Detected = false;
bool level2Detected = false;
bool level3Detected = false;

void sendMP3Command(byte command, byte param1, byte param2) {
  byte packet[] = {0x7E, 0xFF, 0x06, command, 0x00, param1, param2, 0xEF};
  for (byte i = 0; i < 8; i++) {
    mp3Serial.write(packet[i]);
  }
  delay(200); // Allow time for the MP3 module to process
}

void clearSerialBuffer() {
  while (mp3Serial.available()) {
    mp3Serial.read();
  }
}

bool isMP3Playing() {
  sendMP3Command(0x42, 0x00, 0x00); // Query playing status
  delay(50); // Wait for a response
  
  while (mp3Serial.available()) {
    byte response = mp3Serial.read();
    if (response == 0x01) {
      return true; // Still playing
    }
  }
  return false; // Finished playing
}

void sendACK() {
  LoRa.beginPacket();
  LoRa.print("ACK");
  LoRa.endPacket();
  Serial.println("ACK sent.");
}

void playTrack(uint8_t trackNumber) {
  isPlaying = true;

  clearSerialBuffer();
  sendMP3Command(0x16, 0x00, 0x00);  // Stop any currently playing track
  delay(200);  

  sendMP3Command(0x03, 0x00, trackNumber);  // Play track
  
  // Wait until the track finishes playing
  while (isMP3Playing()) {
    delay(100); // Check every 100ms to avoid blocking other tasks
  }

  isPlaying = false;
  sendACK(); // Send ACK only after track fully plays
}

void resetLevelFlags(const String &message) {
  if (message == "L1") {
    level1Detected = true;
    level2Detected = false;
    level3Detected = false;
  } else if (message == "L2") {
    level1Detected = false;
    level2Detected = true;
    level3Detected = false;
  } else if (message == "L3") {
    level1Detected = false;
    level2Detected = false;
    level3Detected = true;
  }
}

void setup() {
    Serial.begin(9600);
    mp3Serial.begin(9600);  
    LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);

    if (!LoRa.begin(433E6)) {
      Serial.println("LoRa initialization failed!");
      while (1);
    }
    Serial.println("LoRa initialized.");

    delay(1500); 
    sendMP3Command(0x06, 0x00, 0x0A); // Set volume to 10 for testing purposes
    delay(500);
}

void loop() {
  if (isPlaying) return; 

  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    Serial.print("Received Message: ");
    
    String message = "";  

    while (LoRa.available()) {
      char c = (char)LoRa.read();
      message += c;
      Serial.print(c);
    }

    Serial.println();

    // Process message and play track only if the level was not already detected
    if (message == "L1" && !level1Detected) {
      Serial.println("Playing Track 1");
      playTrack(1);
      resetLevelFlags(message);  // Reset flags after detecting a level
      sendACK();  // Send ACK
      delay(1000); // 
      
    } else if (message == "L2" && !level2Detected) {
      Serial.println("Playing Track 2");
      playTrack(2);  // Track 2 = 23 seconds
      resetLevelFlags(message);
      sendACK();  // Send ACK
      delay(1000); 

    } else if (message == "L3" && !level3Detected) {
      Serial.println("Playing Track 3");
      playTrack(3);
      resetLevelFlags(message);
      sendACK();  // Send ACK
      delay(1000); 
      
    }
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.