Advertisement
TolentinoCotesta

Time Proportional Control

Nov 14th, 2018
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.28 KB | None | 0 0
  1. // PID Library
  2. #include <AutoPID.h>
  3.  
  4. // Output Relay
  5. #define RelayPin 7
  6.  
  7. // ************************************************
  8. // PID Variables and constants
  9. // ************************************************
  10.  
  11. //Define Variables we'll be connecting to
  12. double Setpoint;
  13. double Input;
  14. double Output;
  15.  
  16. // pid tuning parameters
  17. double Kp = 2;
  18. double Ki = 0.005;
  19. double Kd = 0.8;
  20.  
  21. #define WindowSize  5000
  22.  
  23. //Specify the links and initial tuning parameters
  24. AutoPID myPID(&Input, &Setpoint, &Output, 0, WindowSize, Kp, Ki, Kd);
  25.  
  26. // 10 second Time Proportional Output window
  27. unsigned long windowStartTime, lastLogTime;
  28. unsigned int minStartTime = 100;
  29. volatile long onTime = 0;
  30.  
  31.  
  32. // ********************** Setup **************************
  33. void setup(){
  34.    Serial.begin(115200);
  35.    pinMode(RelayPin, OUTPUT);               // Output mode to drive relay
  36.    digitalWrite(RelayPin, LOW);             // make sure it is off to start
  37.  
  38.    // Initialize the PID and related variables  
  39.    myPID.setGains(Kp,Ki,Kd);
  40.    myPID.setTimeStep(250);
  41.      
  42.    windowStartTime = millis();
  43.  
  44.    // Run Timer2 interrupt every 15 ms
  45.    TCCR2A = 0;
  46.    TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;  
  47.    TIMSK2 |= 1<<TOIE2;                      // Timer2 Overflow Interrupt Enable
  48.  
  49.    Setpoint = 225;  
  50. }
  51.  
  52. // ************************** Timer Interrupt Handler *************************
  53. // ********************* Called every 15ms to drive the output ****************
  54. SIGNAL(TIMER2_OVF_vect){
  55.  // Time to shift the Relay Window
  56.   if(millis() - windowStartTime > WindowSize)
  57.      windowStartTime += WindowSize;
  58.  
  59.   if((onTime > minStartTime) && (onTime > (millis() - windowStartTime)))
  60.      digitalWrite(RelayPin, HIGH);  
  61.   else  
  62.      digitalWrite(RelayPin, LOW);
  63. }
  64.  
  65. // ********************** Main Control Loop **************************
  66. void loop(){
  67.   Input = analogRead(A0);
  68.   myPID.run();  
  69.  
  70.   onTime = Output;                              
  71.   // Time Proportional relay state is updated regularly via timer interrupt.
  72.    
  73.   if (millis() - lastLogTime > 1000)  {
  74.     lastLogTime = millis();
  75.     Serial.print(F("Input: ")); Serial.println(Input);  
  76.     float pct = map(Output, 0, WindowSize, 0, 1000);
  77.     Serial.print(F("C : "));   Serial.print(pct/10);   Serial.println("%");    
  78.   }  
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement