Attach Interrupt not always working

Hey All,

I am using the P2P sample code provided on your site and I’m having trouble getting the interupt function to work consistently. 80% of the time it works but sometimes it seems to ignore the pin input that triggers it. I have modified the code so that it is reading pin 2 and looking for a ground signal. I have a relay connected to pin 2 which closes its contact to ground when activated.

Here is the modified Sodaq_OneP2P code(the lora_p2p_lib file is unmodified from the website version) :

#include <Keyboard.h>

#include <Arduino.h>
#include "LORA_P2P_lib.h"

#define CONSOLE_STREAM SerialUSB
#define LORA_STREAM Serial1

bool LED_Flag = 1;
volatile bool send_Flag = 0;

void setup()
{
  pinMode(LED_GREEN, OUTPUT);
  digitalWrite(LED_GREEN, HIGH);
  pinMode(LED_BLUE, OUTPUT);
  digitalWrite(LED_BLUE, HIGH);
  pinMode(BUTTON, INPUT);
  digitalWrite(2,HIGH);
  LORA_STREAM.begin(57600);
  CONSOLE_STREAM.begin(57600);
  delay(3000);

  CONSOLE_STREAM.println("Started!");

  LoraP2P_Setup();

  CONSOLE_STREAM.println("LORA SETUP DONE!");

  attachInterrupt(2, BTN_ISR, FALLING);


}

void BTN_ISR() {

  send_Flag = 1;
  CONSOLE_STREAM.println("Interrupt!");
}


void loop()
{
  CONSOLE_STREAM.print("Input Pin state is: ");
CONSOLE_STREAM.println(digitalRead(2));
  if (send_Flag == 1) {

    send_Flag = 0;
    CONSOLE_STREAM.println("Sending Message...");
    LORA_Write("10");
   delay(1000);
  }
  else {

    char msg[100] = "";
    CONSOLE_STREAM.println("Listening for Message...");
    int errorCode = LORA_Read(msg); // We have a message if returncode = 1

    if (errorCode == 1 && msg[0] == '1' && msg[1] == '0') { // Switch LED if message = 10


      int count = 0;
      while (count < 2) {
        digitalWrite(LED_GREEN, LOW); // Turn on pin 2 if there is a message
        delay(1000);
        digitalWrite(LED_GREEN, HIGH);
        delay(30);
        digitalWrite(LED_BLUE, LOW);
        delay(1000);
        digitalWrite(LED_BLUE, HIGH);
        CONSOLE_STREAM.println(count);
        count++;

      }

    }
    else {

      CONSOLE_STREAM.println("Error: ");
      CONSOLE_STREAM.println(errorCode);
    }

  }
}

I am new to interrupts so I assume I’m missing something. Any ideas? any help is much appreciated.

A few recommendations with interrupts.

In general keep the ISR functions as simple as possible, where possible just set a flag. I would recommend removing the debug output from the ISR and place it in the interrupt dependent conditional in loop().

The delay(n) method is interrupt driven (it waits until an interrupt driven counter reaches a specified target value), this can possibly interfere with other interrupt driven code. Try delayMicroseconds(n*1000) instead.