sandeepmistry / arduino-LoRa

An Arduino library for sending and receiving data using LoRa radios.
MIT License
1.6k stars 621 forks source link

Fix duplicate packet reception on Arduino MKR 1310 #664

Open mdias opened 9 months ago

mdias commented 9 months ago

Without this change there is a chance that we receive duplicate packets

morganrallen commented 9 months ago

Have you thoroughly checked the rest of your code to ensure something else isn't causing the duplicate? I've never encountered a situation where the IRQ doesn't clear. You can test this by reading back the IRQ reg and printing out that value but note this also might fix your problem as it might just be the delay of two writes that's fixing and issue somewhere else.

mdias commented 9 months ago

The program I have that showed this happening rather easily was basically broadcasting a counter variable every second and checking for received packets all the time. I have 2 Arduino MKR 1310 running the same program and both of them showed like 10-20% of the packets received being received twice.

I don't have enough knowledge to investigate further why the IRQs are not clearing, but after searching online I came across this issue describing the same problem but on a different board, and this fix was suggested. After trying the same fix on my board I could confirm that there are no longer duplicated received packets.

I understand that this looks like a hack and the problem may come from somewhere else, so I understand if you don't want to merge it as is. But the patch as is should also only affect the MKR 1310 board which is already misbehaving (the duplicates) with the original code.

morganrallen commented 9 months ago

There's an easy experiment you can try. Replace the new writeRegister call with delay(100). Does this also solve the problem?

morganrallen commented 9 months ago

It would also be helpful to understand this issue better if you could share the code around the call to endPacket

mdias commented 9 months ago

Replacing writeRegister with delay(100) results in some packets not being received at all, and some others are still duplicated.

My sample application is doing this when sending a packet:

void SendString(const char* str)
{
  digitalWrite(LED_BUILTIN, HIGH);

  LoRa.beginPacket();
  LoRa.print(str);
  LoRa.endPacket();

  digitalWrite(LED_BUILTIN, LOW);
}
...
static void sendData()
{
  char buf[16] = {0};
  if (secondsTimer()) // trigger only once a second
  {
    sprintf(buf, "%i", counter);
    DbgPrint("sending: "); // print debug info with Serial.print()
    DbgPrintLn(buf);

    ++counter;

    SendString(buf);
  }
}

On the receptor end, I receive data like so:

bool ReceiveString(String& outString)
{
  int packetSize = LoRa.parsePacket();
  if (packetSize <= 0)
  {
    return false;
  }

  while (LoRa.available())
  {  
    outString += (char)LoRa.read();
  }

  return true;
}