Interrupt not working. LCD is not displaying

Hello. I’m making a device that counts rotations with an IR sensor. I connected it’s output to the pin 2, or the interrupt pin and it works with an example code. The problem is that my code isn’t working. This is my code

 #include <Wire.h> 
#include <LiquidCrystal_I2C.h>
const byte interruptPin = 2;
int n = 0;
volatile int i = 0;
int resetPin = 4;
int stopPin = 5;
boolean stopPinOn = false;
LiquidCrystal_I2C lcd(0x27,16,2);


void setup() {
  lcd.init();                  
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("rotation counter");
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(interruptPin), cycle, FALLING);
  pinMode(resetPin, INPUT_PULLUP);
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(power, OUTPUT);
  delay(1000);
  lcd.clear();
}

void loop() {
  
  lcd.setCursor(3,0);
  lcd.print("Rotations:");
if(digitalRead(resetPin) == 0){
  i = 0;
}

if(digitalRead(stopPin) == 0){

  stopPinOn = true;
  
}
else {
  stopPinOn = false;
  }
}

void cycle(){
i = i + 1;
if(stopPinOn == true){
  n = i - 1;
}
else{
  n = i;
}
  lcd.setCursor(1, 1);
  lcd.print(n); 
}

The sensor outputs 0 when an object is detected and in theory, every time something is detected, the printed value should change, but it doesn’t do anything. there isn’t a character displayed on the second line.
Any suggestions or hints would be nice :slight_smile:

Never attempt to do serial I/O in an interrupt routine.

The interrupt routine should set a global flag (declared “volatile”) and the main loop should print n (also declared “volatile”) when the flag is set, then reset it.

So then it should look something like this right?

volatile int n = 0;

void loop() {
  
  lcd.setCursor(3,0);
  lcd.print("Rotations:");
if(digitalRead(resetPin) == 0){
  i = 0;
}

if(digitalRead(stopPin) == 0){

  stopPinOn = true;
  
}
else {
  stopPinOn = false;
  }
  lcd.setCursor(1, 1);
  lcd.print(n); 
}

void cycle(){
i = i + 1;
if(stopPinOn == true){
  n = i - 1;
}
else{
  n = i;
}
}

Always post all the code.

Please explain what you are trying to do. The program seems much more complicated than it needs to be, to count rotations.

There is no reason to print the number if it hasn’t changed.

Okay, everything works now. Thank you very much!