Arduino AC Phase Control - "dancing" wave form

Hi, I implemented the following code in my circuit and I have the following sine wave on the soldering iron heater: - YouTube , and - YouTube

Why the sine wave is “dancing” on the screen of the oscilloscope ? Are there any solutions for my problem ?
Shouldn’t be slower that “dance” ?

#include <TimerOne.h>
#include <PID_v1.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 5;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = 0; // microseconds cut out from AC pulse

int fadeAmount = 10;

unsigned long updaterate = 1200; 
unsigned long lastupdate;

int temperature = 0;

double Setpoint, Input, Output;

double aggKp = 2.5, aggKi = 0.3, aggKd = 1.5;
double consKp = 1, consKi = 0.05, consKd = 0.25;

PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

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

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
 // Serial.begin(9600);
  myPID.SetOutputLimits(20, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, FALLING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
 //Read temperature
  Input = 0;
  for(int i=0;i<50;i++)
  Input += analogRead(A0);
  Input /= 50;
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 550, 25, 400);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(A1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 400);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    temperature = newSetpoint;
    lastupdate = millis();
  }

  double gap = abs(Setpoint - Input); //distance away from setpoint
    myPID.SetTunings(aggKp, aggKi, aggKd);

  myPID.Compute();
  noInterrupts();
  period = 11000-(43*Output);
  interrupts();
}

is there any noise on your zero crossing input?

i had problems with noise using an optical encoder when a small 12V motor was running. leads were 20". trying to keep them separate from the motor leads helped, but I feel that passing the inputs thru a pins 2&6 of a 555 timer to provide more hysterisis is really needed.

i'm curious about how you're using Timer1. Shouldn't it generate just a short pulse (1 msec)? is there any need to track the triac state? shouldn't Timer1 be used as a one-shot? shouldn't it be stopped() on the first event?

My zero crossing looks like the attached screenshot (yellow trace), and output through optotriac (blue trace).

DS0163.jpg

i'm guessing that the yellow trace is pin 3 on the opto and the blue trace a pulse generated within zeroCrossing() that is not in the posted code.

it would be useful to include the triac output waveform (or triac trigger pulse) with either the yellow or blue traces. you would need to see if there are any shifts after confirming the blue and yellow never shift if you haven't done so already

if there is any suspicion about Timer1, you could capture timestamps (micros()) in zeroCrossing() and triacPulse to see if there are any sudden shifts

The yellow trace is the pin 3 of the opto and the blue trace is the signal to the triac driver.

The yellow trace is the pin 3 of the opto and the blue trace is the signal to the triac driver.

doesn't the trace you posted imply that the triac is being turned at the beginning if the cycle?

Yes.

Hello Mike

@gcjr, more info potentiometer - Arduino PID controller for Triac - Arduino Stack Exchange

i've used PID for timing recovery at work and motor position and see no need for it to control a triac on a soldering iron

doesn't the trace you posted imply that the triac is being turned at the beginning if the cycle?

do you every observe the triac (blue) trace shifting relative to the opto output (yellow) trace like your videos show?

it is PID. it is tuning the parameters. The PID control gets smoother over time as it finetunes its parameters, but I think a simple PID has some problems with the sine relation between the output (time) and the resulting heating power.
blue is temperature, red is PID output for the Triac period

@gcjr, the hardware works good with fade in fade out sketch - YouTube

parameters for what?

PID is often used to control the rate of change of position (i.e. speed) in order to reach with minimal overshoot a desire position. what rate is being controlled? you simply turn the triac on at a specific time

are you suggesting the PID is causing the shifts? if so remove the PID stuff and see if the shifts go away

gcjr:
are you suggesting the PID is causing the shifts? if so remove the PID stuff and see if the shifts go away

It moves like this: - YouTube

i suggest you add code to toggle a pin to zeroCrossing() to confirm that the interrupt is synchronized to to the opto output to confirm the external circuitry

you can't make assumption that things work or don't work

I also found on the internet a PID code which works but with problems.

The events are in the following order:

  1. I start the soldering station from AC 230V
  2. The soldering station heats up to maximum (I measure 18mV on the TC at maximum)
  3. I reduce voluntary the temperature by rotating the pot to the minimum
  4. The temperature (and the voltage on the TC) starts to decrease
  5. When the voltage on the TC is about 16-17mV then the power to the soldering iron starts to increase suddenly. And I cannot do anything to make it stable or to decrease it.
  6. The voltage on the TC continues to rise, and when it reaches 22-23mV, I unplug the soldering station from the wall socket, to protect the heater of the soldering iron.

I tried the following solutions for my problem: I checked individually each part of the schematic and all of them were good.
I found that this event happens, when in the code the PID error is equal (=) to set point. This makes the PID value to be 7400 and in the delayMicroseconds(maximum_firing_delay - PID_value); line of code the result is zero (0), making the entire sine wave to be present on the soldering iron heater. I measured those things in serial monitor.

And this is the code:
//Inputs and outputs
int firing_pin = 5;
int zero_cross = 2;

//Variables
int last_CH1_state = 0;
bool zero_cross_detected = false;
int firing_delay = 7400;

//////////////////////////////////////////////////////
int maximum_firing_delay = 7400;
/*Later in the code you will se that the maximum delay after the zero detection
* is 7400. Why? Well, we know that the 220V AC voltage has a frequency of around 50-60HZ so
* the period is between 20ms and 16ms, depending on the country. We control the firing
* delay each half period so each 10ms or 8 ms. To amke sure we wont pass thsoe 10ms, I've made tests
* and the 7400us or 7.4ms was a good value. Measure your frequency and chande that value later */
//////////////////////////////////////////////////////

unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
int temp_read_Delay = 500;
int real_temperature = 0;
int setpoint = 100;

//PID variables
float PID_error = 0;
float previous_error = 0;
float elapsedTime, Time, timePrev;
int PID_value = 0;
//PID constants
int kp = 20;   int ki= 5;   int kd = 10;
int PID_p = 0;    int PID_i = 0;    int PID_d = 0;


void setup() {
//Define the pins
Serial.begin(9600);
pinMode (firing_pin,OUTPUT);
pinMode (zero_cross,INPUT);  
PCICR |= (1 << PCIE2);    //enable scan                                                
PCMSK2 |= (1 << PCINT18);  //Set pin D2 (zero cross input) trigger an interrupt on state change.
}


void loop() {    
currentMillis = millis();           //Save the value of time before the loop
if(currentMillis - previousMillis >= temp_read_Delay){
previousMillis += temp_read_Delay;              //Increase the previous time for next loop
//get the real temperature in Celsius degrees
// added by Mike
for(int i=0;i<50;i++)
real_temperature += analogRead(A0);  
real_temperature /= 50;
real_temperature = map(real_temperature, 0, 550, 25, 400);
// end added by Mike
setpoint = analogRead(A1);
setpoint = map(setpoint, 0, 1023, 150, 400);
PID_error = setpoint - real_temperature;        //Calculate the pid ERROR

if(PID_error > 30)                              //integral constant will only affect errors below 30ºC            
{PID_i = 0;}

PID_p = kp * PID_error;                         //Calculate the P value
PID_i = PID_i + (ki * PID_error);               //Calculate the I value
timePrev = Time;                    // the previous time is stored before the actual time read
Time = millis();                    // actual time read
elapsedTime = (Time - timePrev) / 1000;  
PID_d = kd*((PID_error - previous_error)/elapsedTime);  //Calculate the D value
PID_value = PID_p + PID_i + PID_d;                      //Calculate total PID value

//We define firing delay range between 0 and 7400. Read above why 7400!!!!!!!
if(PID_value < 0) // initial it was <
{      PID_value = 0;       }
if(PID_value > 7400) // initial it was >
{      PID_value = 7400;    }
previous_error = PID_error; //Remember to store the previous error.
//    Serial.println("PID_error=");
//    Serial.println(PID_error);
//    Serial.println("real_temperature=");
//    Serial.println(real_temperature);
//    Serial.println("setpoint=");
//    Serial.println(setpoint);
//    Serial.println("PID_value=");
//    Serial.println(PID_value);
}

//If the zero cross interruption was detected we create the 100us firing pulse  
if (zero_cross_detected)    
{
  delayMicroseconds(maximum_firing_delay - PID_value); //This delay controls the power
  digitalWrite(firing_pin,HIGH);
  delayMicroseconds(100);
  digitalWrite(firing_pin,LOW);
  zero_cross_detected = false;
}
}

//This is the interruption routine (pind D8(zero cross), D11(increase) and D12(decrease))
//----------------------------------------------

ISR(PCINT2_vect){
///////////////////////////////////////Input from optocoupler
if(PIND & B00000010){            //We make an AND with the state register, We verify if pin D2 is HIGH???
if(last_CH1_state == 0){       //If the last state was 0, then we have a state change...
  zero_cross_detected = true;  //We have detected a state change! We need both falling and rising edges
}
}
else if(last_CH1_state == 1){    //If pin 2 is LOW and the last state was HIGH then we have a state change      
zero_cross_detected = true;    //We haev detected a state change!  We need both falling and rising edges.
last_CH1_state = 0;            //Store the current state into the last state for the next loop
}
}

gcjr:
i suggest you add code to toggle a pin to zeroCrossing() to confirm that the interrupt is synchronized to to the opto output to confirm the external circuitry

you can't make assumption that things work or don't work

again. the hardware works good with a 'fade' sketch

print the values. draw a chart. see if the period is in limits

This is a chart. Please have a look.
Chart temperature - the “sine wave” happens when I rotate the pot to minimum temperature.
The temperature increases when the delayMicroseconds(maximum_firing_delay - PID_value); is equal to 0 Microseconds, and I think that this happens right in the moment when pid_values are 7400 (read from the graph).

you have to look at the values in detail. the 11000 in period = 11000 - (75 * output) was only to show that the output works the other way. it should be 10000 microseconds and maybe the 75 should be changed to get the values between 9800 and 1200.

I was talking about this code:

//Inputs and outputs
int firing_pin = 5;
int zero_cross = 2;

//Variables
int last_CH1_state = 0;
bool zero_cross_detected = false;
int firing_delay = 7400;

//////////////////////////////////////////////////////
int maximum_firing_delay = 7400;
/*Later in the code you will se that the maximum delay after the zero detection
 * is 7400. Why? Well, we know that the 220V AC voltage has a frequency of around 50-60HZ so
 * the period is between 20ms and 16ms, depending on the country. We control the firing
 * delay each half period so each 10ms or 8 ms. To amke sure we wont pass thsoe 10ms, I've made tests
 * and the 7400us or 7.4ms was a good value. Measure your frequency and chande that value later */
//////////////////////////////////////////////////////

unsigned long previousMillis = 0; 
unsigned long currentMillis = 0;
int temp_read_Delay = 500;
int real_temperature = 0;
int setpoint = 100;

//PID variables
float PID_error = 0;
float previous_error = 0;
float elapsedTime, Time, timePrev;
int PID_value = 0;
//PID constants
int kp = 30;   int ki= 10;   int kd = 5;
int PID_p = 0;    int PID_i = 0;    int PID_d = 0;


void setup() {
  //Define the pins
  Serial.begin(9600);
  pinMode (firing_pin,OUTPUT); 
  pinMode (zero_cross,INPUT);   
  PCICR |= (1 << PCIE2);    //enable scan                                                 
  PCMSK2 |= (1 << PCINT18);  //Set pin D2 (zero cross input) trigger an interrupt on state change.
}


void loop() {    
  currentMillis = millis();           //Save the value of time before the loop
  if(currentMillis - previousMillis >= temp_read_Delay){
    previousMillis += temp_read_Delay;              //Increase the previous time for next loop
    //get the real temperature in Celsius degrees
    // added by Mike
    for(int i=0;i<50;i++)
    real_temperature += analogRead(A0);  
    real_temperature /= 50;
    real_temperature = map(real_temperature, 0, 550, 25, 400);
    // end added by Mike
    setpoint = analogRead(A1);
    setpoint = map(setpoint, 0, 1023, 150, 400);
    PID_error = setpoint - real_temperature;        //Calculate the pid ERROR
    
    if(PID_error > 30)                              //integral constant will only affect errors below 30ºC             
    {PID_i = 0;}
    
    PID_p = kp * PID_error;                         //Calculate the P value
    PID_i = PID_i + (ki * PID_error);               //Calculate the I value
    timePrev = Time;                    // the previous time is stored before the actual time read
    Time = millis();                    // actual time read
    elapsedTime = (Time - timePrev) / 1000;   
    PID_d = kd*((PID_error - previous_error)/elapsedTime);  //Calculate the D value
    PID_value = PID_p + PID_i + PID_d;                      //Calculate total PID value

    //We define firing delay range between 0 and 7400. Read above why 7400!!!!!!!
    if(PID_value < 0) // initial it was <
    {      PID_value = 0;       }
    if(PID_value > 7400) // initial it was >
    {      PID_value = 7400;    }
    previous_error = PID_error; //Remember to store the previous error.
  
    Serial.print(PID_error);
    Serial.print(";");
    Serial.print(real_temperature);
    Serial.print(";");
    Serial.print(setpoint);
    Serial.print(";");
    Serial.print(PID_value);
    Serial.println(";");
  }

  //If the zero cross interruption was detected we create the 100us firing pulse  
  if (zero_cross_detected)     
    {
      delayMicroseconds(maximum_firing_delay - PID_value); //This delay controls the power
      digitalWrite(firing_pin,HIGH);
      delayMicroseconds(100);
      digitalWrite(firing_pin,LOW);
      zero_cross_detected = false;
    } 
}

//This is the interruption routine (pind D8(zero cross), D11(increase) and D12(decrease))
//----------------------------------------------

ISR(PCINT2_vect){
  ///////////////////////////////////////Input from optocoupler
  if(PIND & B00000100){            //We make an AND with the state register, We verify if pin D2 is HIGH???
    if(last_CH1_state == 0){       //If the last state was 0, then we have a state change...
      zero_cross_detected = true;  //We have detected a state change! We need both falling and rising edges
    }
  }
  else if(last_CH1_state == 1){    //If pin 2 is LOW and the last state was HIGH then we have a state change      
    zero_cross_detected = true;    //We haev detected a state change!  We need both falling and rising edges.
    last_CH1_state = 0;            //Store the current state into the last state for the next loop
    }
}