Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PID Library
- #include <AutoPID.h>
- // Output Relay
- #define RelayPin 7
- // ************************************************
- // PID Variables and constants
- // ************************************************
- //Define Variables we'll be connecting to
- double Setpoint;
- double Input;
- double Output;
- // pid tuning parameters
- double Kp = 2;
- double Ki = 0.005;
- double Kd = 0.8;
- #define WindowSize 5000
- //Specify the links and initial tuning parameters
- AutoPID myPID(&Input, &Setpoint, &Output, 0, WindowSize, Kp, Ki, Kd);
- // 10 second Time Proportional Output window
- unsigned long windowStartTime, lastLogTime;
- unsigned int minStartTime = 100;
- volatile long onTime = 0;
- // ********************** Setup **************************
- void setup(){
- Serial.begin(115200);
- pinMode(RelayPin, OUTPUT); // Output mode to drive relay
- digitalWrite(RelayPin, LOW); // make sure it is off to start
- // Initialize the PID and related variables
- myPID.setGains(Kp,Ki,Kd);
- myPID.setTimeStep(250);
- windowStartTime = millis();
- // Run Timer2 interrupt every 15 ms
- TCCR2A = 0;
- TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;
- TIMSK2 |= 1<<TOIE2; // Timer2 Overflow Interrupt Enable
- Setpoint = 225;
- }
- // ************************** Timer Interrupt Handler *************************
- // ********************* Called every 15ms to drive the output ****************
- SIGNAL(TIMER2_OVF_vect){
- // Time to shift the Relay Window
- if(millis() - windowStartTime > WindowSize)
- windowStartTime += WindowSize;
- if((onTime > minStartTime) && (onTime > (millis() - windowStartTime)))
- digitalWrite(RelayPin, HIGH);
- else
- digitalWrite(RelayPin, LOW);
- }
- // ********************** Main Control Loop **************************
- void loop(){
- Input = analogRead(A0);
- myPID.run();
- onTime = Output;
- // Time Proportional relay state is updated regularly via timer interrupt.
- if (millis() - lastLogTime > 1000) {
- lastLogTime = millis();
- Serial.print(F("Input: ")); Serial.println(Input);
- float pct = map(Output, 0, WindowSize, 0, 1000);
- Serial.print(F("C : ")); Serial.print(pct/10); Serial.println("%");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement