Interrupt problem for newby

Using a NANO classic. This is just a portion of the project but simplifies it and how it doesn't work. At least as I want.)
For this test my pin 2 is connected to ground through a 2K resistor (but I have tried 10K).
A switch is connected from 5V to pin 2. Pin 2 is going from 0 to 5V when pressed. (it's actually pretty clean on the O'scope.
Tried 2 different NANO's

It starts and runs fine usually. UNTIL you press the switch. It then locks up the NANO. Sometimes throwing garbage on the LCD or blacking it out completely.
It will also do the same thing intermittently even if you never press the switch. (Sometimes not for several minutes.)
If you remove the attachInterrupt statement, it never fails while in the void loop.

I assume I have something coded wrong. I have tried a few other methhods of doing this with the same results.

Thanks....

#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
// Set the LCD address to 0x27 for a 20 chars and 4 line display
LiquidCrystal_I2C lcd(0x27, 20, 4);
const byte interruptPin = 2;
volatile byte state = LOW;
int pulseCounter = 0;
#define INTERRUPT_INPUT 2

void setup() {
#define INTERRUPT_INPUT 2
  pinMode(interruptPin, INPUT);
  lcd.begin();
  // Turn on the blacklight and print a message.
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(7, 0);
  lcd.print("READY");
  attachInterrupt(digitalPinToInterrupt(interruptPin),counter, RISING);
}

void loop() {
lcd.clear();
lcd.print("Wait for INTERRUPT..");
delay(500);
lcd.clear();
}

void counter()
{
  pulseCounter = pulseCounter + 1;
  lcd.print(" GOT INTERRUPT..");
  lcd.print(pulseCounter);
  delay(500);
}

Don't ever do any of the above in an interrupt code. Just do the count.

Neither print nor delay() work in an ISR because they use interrupts. Interrupts are disabled whilst in an ISR. Variables such as pulseCounter which are used in an ISR and also in other code should be declared as volatile

Can you see any possible problems ?

Geesh! Thanks guys... Well, I said I was a newby.... The thing that messed my thoughts up was the fact that the hardware crashed. I had those statements in there just to test. Moved the delay and print statements out and it works great.

1 Like

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