LCD stop working after use of sei() and cli()

Hello,

I'm trying to merge code of two workings programs:

  • the first count using a sensor
  • the second prints on a LCD screen

So I tried to display the sensor count on the LCD.
On the setup() function I can print out on the LCD the string "INIT".
On the loop() function, I can print only ONCE on the LCD because after the sei() and cli() call everything stops working.

Can you please explain me how to make it work?

Thanks!

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int NbTopsFan;
int calc;
int hallsensor = 2;

LiquidCrystal_I2C lcd(0x27,16,2);

void rpm()
{
  NbTopsFan++;
}

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);

  // Works fine: the LCS print INIT each time
  lcd.print("INIT");
 
  pinMode(hallsensor,INPUT);
  Serial.begin(9600);
  attachInterrupt(0, rpm, RISING);
}

void loop()
{
  // The LCS print TEST1 each time
  lcd.setCursor(0,1);
  lcd.print("TEST1");
  
  NbTopsFan = 0;
  sei();
  delay(1000);
  cli();
  calc=(NbTopsFan * 2.2);
 
  Serial.println(calc,DEC);

  // DOES NOT print Test2
  lcd.setCursor(0,1);
  lcd.print("TEST2");
}

Welcome,

I don't know for your problem, but variables used inside interrupt handlers must be declared as volatile

volatile int NbTopsFan;

Will printing to Serial or the I2C LCD work with interrupts disabled?

Usually the interrupts are disabled only long enough to access the variable in the interrupt.

cli();  // globally disable interrupts
calc=(NbTopsFan * 2.2);  // access variable changed in interrupt
sei();  // enable interrupts

Better yet, make a copy of the interrupt variable and use that in the program.

cli();  // globally disable interrupts
tempvar =  NbTopsFan; // copy variable changed in interrupt
sei();  // enable interrupts
calc=(tempvar * 2.2);

Karma for code tags in first post.

Good job with the code tags on the first post.

Your issue is covered here
https://forum.arduino.cc/index.php?topic=421005.0

There are examples of a fix with both "Blink without Delay" non blocking code, and also with the keeping the delay period in place, but with better placement of the interrupt/no interrupt commands.