Dimmer a light while doing something else

Hello everybody

I'm trying to make an AC dimmer using a tric and with the same arduino write on the LCD every 1 second and read a temp every 1 second

LET'S SAY FOR NOW I JUST WANT A CONSTANT DIMMING, SO THE LIGHT STAYS AT A STEADY LUX

The dimmer works great but when I add something else like reading a temperature or writing on the LCD the light flickers (right in the time I do something else)

I've avoided delays and used a timer interrupts but it looks not enough.

I would like to repeat that everything works great, the only think is that the light flickers, every 1 sec when I do something else.

Can someone help me to understand how to better use timers in order to always prioritize the triac timing ?

thanks a lot

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

LiquidCrystal_I2C lcd(0x3F,20,4);             // set the LCD address to 0x3F for a 16 chars and 2 line display


const byte Interrupt_PIN = 2;                 //Zero-crossing circuit pin

//Temp measurement
float Temp = 0;                               //Variabile temperatura
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 3
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

//Triac settings
volatile bool triacOn;                        //Triac state support variable
const byte Triac_PIN = 12;                    //Triac pin
int Tric_ON_Logic_State = HIGH;               //Logic state that drives the Triac to turn the load ON
const byte Triac_Pulse_Micros = 50;           //Time to keep the triac enable signal ON

//Loop times settings
const int PID_Loop_Period = 1000;             //Loop time of the PID routine
const int Serial_Loop_Period = 1000;          //Loop time of the Serial debug routine
const int Temp_Reading_Loop_Period = 3000;    //Loop time of the Temp_Reading routine
const int LCD_Loop_Period = 1000;             //Loop time of the LCD routine

//Timers variables setting 
unsigned long Current_Millis = 0;             //Loop timer support variable
unsigned long PID_Loop_Time;                  //Support variable for PID loop timer
unsigned long LCD_Loop_Time;                  //Support variable for LCD loop timer
unsigned long Temp_Reading_Loop_Time;         //Support variable for Temp_Reading loop timer 
unsigned long Serial_Loop_Time;               //Support variable for Serial loop timer
volatile int Triac_ON_Delay = 9000;           //THIS VALUE CONTROL THE LOAD POWER. Delay to turn on the TRIAC after a zero crossing. The greater it is the lower it is the power (9000 means low power)



//----------------------------------------------------------------------------------------------------------------------------------- Setup

void setup() {
  pinMode(Triac_PIN, OUTPUT);                                                         //Set the Triac PIN as an output pin
  attachInterrupt(digitalPinToInterrupt(Interrupt_PIN), zeroCrossing, FALLING);       //Set up an interrupt on pin 2, when happens execute zeroCrossing routine, Falling trigger
  Timer1.initialize();                                                                //Initialize the Timer 1 interrupt
  Timer1.attachInterrupt(triacPulse);                                                 //Set up the Timer 1 interrupt, when happens execute triacPulse routine
  Serial.begin(9600);                                                                 //Setup the Serial port for dbg purposes 
  lcd.init();                                                                         //LCD init
  lcd.backlight();                                                                    //Turn the LCD backlight ON
  lcd.clear();                                                                        //Clear the LCD screen 
  sensor.begin();                                                                     //Dallas temp sensor begin
  
  lcd.setCursor(0,0);                                                                 //Write first line
  lcd.print("Dimmer");                                                                //Write first line
  
  delay (1000);                                                                       //Wait a sec before start                                                        
}


//----------------------------------------------------------------------------------------------------------------------------------- Zero crossing interrupt routine


void zeroCrossing() {
      triacOn = false;                                                // Triac tuns off self at zero crossing
      Timer1.setPeriod(Triac_ON_Delay);                               // To call triacPulse() after off period
}


//----------------------------------------------------------------------------------------------------------------------------------- Triac activation interrupt routine

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(Triac_PIN, Tric_ON_Logic_State);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(Triac_PIN, !Tric_ON_Logic_State);
    triacOn = true;
    Timer1.setPeriod(Triac_Pulse_Micros);
  }
}


//----------------------------------------------------------------------------------------------------------------------------------- PID routine

void LCD(){

        if (Current_Millis > LCD_Loop_Time) {                         //If the millis timer reached LCD_Loop_Time...

        lcd.setCursor(0,1);                                           //Set LCD cursor on line 2
        lcd.print(Temp);                                              //Write temp on line 2
        LCD_Loop_Time = Current_Millis + LCD_Loop_Period;             //Set the next LCD write = Current millis time + LCD_Loop_Period        
      }
  }

//----------------------------------------------------------------------------------------------------------------------------------- PID routine

void PID(){

        if (Current_Millis > PID_Loop_Time) {                         //If the millis timer reached PID_Loop_Time...

        Triac_ON_Delay = 9000;
        PID_Loop_Time = Current_Millis + PID_Loop_Period;             //Set the next PID calculation = Current millis time + PID_Loop_Period
      }
  }
  
//----------------------------------------------------------------------------------------------------------------------------------- Serial debug loop

void Serial_Debug_Loop(){

      if (Current_Millis > Serial_Loop_Time) {                        //If the millis timer reached Serial_Loop_Time...
  
      Serial.print(Triac_ON_Delay);                                   //Write on the serial port
      Serial.print(" "); 
      Serial.println(Temp, 1);                                        //Write on the serial port
      Serial_Loop_Time = Current_Millis + Serial_Loop_Period;         //Set the next serial write = Current millis time + Serial_Loop_Period
  }
}

//----------------------------------------------------------------------------------------------------------------------------------- Temps Reading

void Temp_Reading(){

    if (Current_Millis > Temp_Reading_Loop_Time) {                            //If the millis timer reached Temp_Reading_Loop_Time...

    sensor.setResolution(9);
    sensor.requestTemperatures();
    Temp = sensor.getTempCByIndex(0);

    Temp_Reading_Loop_Time = Current_Millis + Temp_Reading_Loop_Period;       //Set the next Temp_Reading = Current millis time + Temp_Reading_Loop_Period
                                                             
  }
}


//----------------------------------------------------------------------------------------------------------------------------------- Main Loop

void loop(){

      Current_Millis = millis();                                       //Get the current time
      Serial_Debug_Loop();                                             //Execute the Serial_Debug_Loop
      Temp_Reading();                                                  //Read the temperatures
      PID();                                                           //Execute the PID routine
      LCD();                                                           //Execute the LCD routine
}

These aren't your issue, but if you get within LCD_Loop_Period of millis()= ULONG_MAX it will trigger every time.

not sure I understand DaveX

The display works just fine updating every 1 sec since

const int LCD_Loop_Period = 1000;             //Loop time of the LCD routine

This looks like a lot for an interrupt. I might consider setting up the timer1 PWM with a frequency slower than your zero-crossing frequency, and then updating the low-level TCNT1 register (and maybe output) in your zero crossing interrupt to synchronize the right PWM phase with the zeros.

In 47.7 days from bootup when millis is 999 smaller than ULONG_MAX, this:

        LCD_Loop_Time = Current_Millis + LCD_Loop_Period;             //Set the next LCD write = Current millis time + LCD_Loop_Period        

will set LCD_Loop_Time=0, and for the next 1000ms before millis() rolls over to zero, the if (Current_Millis > LCD_Loop_Time) conditional will trigger every time.

It would be especially bad if you were updating with:

LCD_Loop_Time += LCD_Loop_Period;

thanks or your reply

Yeah I knew the issue was around the interrupt somehow.
I hope I can fix this without playing with low level registers since they are out of my knowledge.

I've tried to read something in order to understand them but it looks quite difficult to me

Would you have any advices of a not so difficult way to avoid this hanging or some good way on how to learn the LL registers?

thanks again

PS. this will stay active for max 12-16 hours so I won't expect any variable to go in overflow

I'd draw out the waveforms of the AC, the zero crossing signal, and the desired TriacPin.

I'd also try setting up a Timer1 PWM pin to have the same frequency, and then look up "TCNT1" in the Arduino's datasheets or elsewhere.

It seems what you are looking for is something like timers - Turn off Timer1 / Timer1 One-shot - Arduino Stack Exchange


Oh -- if you try the same pattern with micros() instead of millis() the problem happens at 71 minutes.

thanks @DaveX

I've tried to learn something about ISR. It is now way better but still not OK. I suspect there is some "interrupt" in the I2C-LCD library and in the Dallas Temp library that goes in conflict with my ISR interrupt.
By the way it is way better. What do you think about my new code. I used timer 1 to turn the TRIAC ON and the timer 2 to stop the signal to the triac

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

LiquidCrystal_I2C lcd(0x3F,20,4);             // set the LCD address to 0x3F for a 16 chars and 2 line display


const byte Interrupt_PIN = 2;                 //Zero-crossing circuit pin

//Temp measurement
float Temp = 0;                               //Variabile temperatura
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 3
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

//Triac settings
const byte Triac_PIN = 12;                    //Triac pin
int Tric_ON_Logic_State = LOW;                //Logic state that drives the Triac to turn the load ON

//Loop times settings
const int PID_Loop_Period = 1000;             //Loop time of the PID routine
const int Serial_Loop_Period = 1000;          //Loop time of the Serial debug routine
const int Temp_Reading_Loop_Period = 3000;    //Loop time of the Temp_Reading routine
const int LCD_Loop_Period = 1000;             //Loop time of the LCD routine

//Timers variables setting 
unsigned long Current_Millis = 0;             //Loop timer support variable
unsigned long PID_Loop_Time;                  //Support variable for PID loop timer
unsigned long LCD_Loop_Time;                  //Support variable for LCD loop timer
unsigned long Temp_Reading_Loop_Time;         //Support variable for Temp_Reading loop timer 
unsigned long Serial_Loop_Time;               //Support variable for Serial loop timer


//----------------------------------------------------------------------------------------------------------------------------------- Setup

void setup() {

  //timer 1

  cli();                                      //stop interrupts for till we make the settings
  
  TCCR1A = 0;                                 // Reset entire TCCR1A to 0 
  TCCR1B = 0;                                 // Reset entire TCCR1B to 0
  TCCR1B |= B00000100;                        //Set CS12 to 1 so we get prescalar 256 = 1 Clock every 16 uS
  TIMSK1 |= B00000010;                        //Set OCIE1A to 1 so we enable compare match A
  OCR1A = 562;                                //Register A to 562 = Triac turn on after around 9000 uS after the zeroCrossing = low lamp intensity  
  


  //timer 2
  TCCR2A = 0;                                 // Reset entire TCCR1A to 0 
  TCCR2B = 0;                                 // Reset entire TCCR1B to 0
  TCCR2B |= B00000100;                        //Set CS12 to 1 so we get prescalar 256 = 1 Clock every 16 uS
  TIMSK2 |= B00000100;                        //Set OCIE1B to 1 so we enable compare match B
  OCR2B = 6;                                  //Register B to 6 = Triac signal is turned OFF after 96uS , the triac will turn OFF itself at the zero crossing 
   
  sei();                                      //Enable back the interrupts




  pinMode(Triac_PIN, OUTPUT);                                                         //Set the Triac PIN as an output pin
  attachInterrupt(digitalPinToInterrupt(Interrupt_PIN), zeroCrossing, FALLING);       //Set up an interrupt on pin 2, when happens execute zeroCrossing routine, Falling trigger
  Serial.begin(9600);                                                                 //Setup the Serial port for dbg purposes 
  
  lcd.init();                                                                         //LCD init
  lcd.backlight();                                                                    //Turn the LCD backlight ON
  lcd.clear();                                                                        //Clear the LCD screen 
  sensor.begin();                                                                     //Dallas temp sensor begin
 
  lcd.setCursor(0,0);                                                                 //Write first line
  lcd.print("Dimmer");                                                                //Write first line
  
  delay (1000);                                                                       //Wait a sec before start                                                        
}


//----------------------------------------------------------------------------------------------------------------------------------- Zero crossing interrupt routine


void zeroCrossing() {
   TCNT1  = 0;                                                        //Reset the timer every zero crossing

   }




//----------------------------------------------------------------------------------------------------------------------------------- PID routine

void LCD(){

        if (Current_Millis > LCD_Loop_Time) {                         //If the millis timer reached LCD_Loop_Time...

        lcd.setCursor(0,1);                                           //Set LCD cursor on line 2
        lcd.print(Current_Millis);                                    //Write temp on line 2

        lcd.setCursor(0,2);                                           //Set LCD cursor on line 2
        lcd.print(Temp);                                              //Write temp on line 2
        
        LCD_Loop_Time = Current_Millis + LCD_Loop_Period;             //Set the next LCD write = Current millis time + LCD_Loop_Period        
      }
  }

//----------------------------------------------------------------------------------------------------------------------------------- PID routine

void PID(){

        if (Current_Millis > PID_Loop_Time) {                         //If the millis timer reached PID_Loop_Time...

        //write the PID logic, not used for now  


        PID_Loop_Time = Current_Millis + PID_Loop_Period;             //Set the next PID calculation = Current millis time + PID_Loop_Period
      }
  }
  
//----------------------------------------------------------------------------------------------------------------------------------- Serial debug loop

void Serial_Debug_Loop(){

      if (Current_Millis > Serial_Loop_Time) {                        //If the millis timer reached Serial_Loop_Time...
  
      // write the serial debug messages

     
      Serial_Loop_Time = Current_Millis + Serial_Loop_Period;         //Set the next serial write = Current millis time + Serial_Loop_Period
  }
}

//----------------------------------------------------------------------------------------------------------------------------------- Temps Reading

void Temp_Reading(){

    if (Current_Millis > Temp_Reading_Loop_Time) {                            //If the millis timer reached Temp_Reading_Loop_Time...

    sensor.setResolution(9);                                                  //Set the temp sensor resolution to ) bit
    sensor.requestTemperatures();                                             //Request temperature
    Temp = sensor.getTempCByIndex(0);                                         //Write temp on variable Temp

    Temp_Reading_Loop_Time = Current_Millis + Temp_Reading_Loop_Period;       //Set the next Temp_Reading = Current millis time + Temp_Reading_Loop_Period
                                                             
  }
}


//----------------------------------------------------------------------------------------------------------------------------------- Main Loop

void loop(){

      Current_Millis = millis();                                       //Get the current time
      //Serial_Debug_Loop();                                             //Execute the Serial_Debug_Loop
      Temp_Reading();                                                  //Read the temperatures
      //PID();                                                           //Execute the PID routine
      LCD();                                                           //Execute the LCD routine

}


//----------------------------------------------------------------------------------------------------------------------------------- Triac activation interrupt routine



ISR(TIMER1_COMPA_vect){

  digitalWrite(Triac_PIN,Tric_ON_Logic_State);            //Turn the Triac ON
  TCNT2  = 0;                                             //Reset the timer 2

}


//----------------------------------------------------------------------------------------------------------------------------------- Triac singal OFF interrupt routine

   

ISR(TIMER2_COMPB_vect){                                  //If timer 2 is matching register B
  

  digitalWrite(Triac_PIN,!Tric_ON_Logic_State);          //Turn the Triac COMMAND OFF, the triac will turn off itself at the zero crossing


}

it seems I am not the only one

it looks like this temp sensor does not work properly with the interrupts