2011-12-14 04:20:47 -08:00
|
|
|
/********************************************************
|
|
|
|
* PID RelayOutput Example
|
|
|
|
* Same as basic example, except that this time, the output
|
|
|
|
* is going to a digital pin which (we presume) is controlling
|
|
|
|
* a relay. the pid is designed to Output an analog value,
|
|
|
|
* but the relay can only be On/Off.
|
|
|
|
*
|
|
|
|
* to connect them together we use "time proportioning
|
|
|
|
* control" it's essentially a really slow version of PWM.
|
2015-05-09 11:20:53 -07:00
|
|
|
* first we decide on a window size (5000mS say.) we then
|
2011-12-14 04:20:47 -08:00
|
|
|
* set the pid to adjust its output between 0 and that window
|
|
|
|
* size. lastly, we add some logic that translates the PID
|
2015-05-09 11:20:53 -07:00
|
|
|
* output into "Relay On Time" with the remainder of the
|
2011-12-14 04:20:47 -08:00
|
|
|
* window being "Relay Off Time"
|
|
|
|
********************************************************/
|
|
|
|
|
|
|
|
#include <PID_v1.h>
|
2015-05-09 11:20:53 -07:00
|
|
|
|
|
|
|
#define PIN_INPUT 0
|
|
|
|
#define RELAY_PIN 6
|
2011-12-14 04:20:47 -08:00
|
|
|
|
|
|
|
//Define Variables we'll be connecting to
|
|
|
|
double Setpoint, Input, Output;
|
|
|
|
|
|
|
|
//Specify the links and initial tuning parameters
|
2015-05-09 11:20:53 -07:00
|
|
|
double Kp=2, Ki=5, Kd=1;
|
|
|
|
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
|
2011-12-14 04:20:47 -08:00
|
|
|
|
|
|
|
int WindowSize = 5000;
|
|
|
|
unsigned long windowStartTime;
|
2015-05-09 11:20:53 -07:00
|
|
|
|
2011-12-14 04:20:47 -08:00
|
|
|
void setup()
|
|
|
|
{
|
|
|
|
windowStartTime = millis();
|
2015-05-09 11:20:53 -07:00
|
|
|
|
2011-12-14 04:20:47 -08:00
|
|
|
//initialize the variables we're linked to
|
|
|
|
Setpoint = 100;
|
|
|
|
|
|
|
|
//tell the PID to range between 0 and the full window size
|
|
|
|
myPID.SetOutputLimits(0, WindowSize);
|
|
|
|
|
|
|
|
//turn the PID on
|
|
|
|
myPID.SetMode(AUTOMATIC);
|
|
|
|
}
|
|
|
|
|
|
|
|
void loop()
|
|
|
|
{
|
2015-05-09 11:20:53 -07:00
|
|
|
Input = analogRead(PIN_INPUT);
|
2011-12-14 04:20:47 -08:00
|
|
|
myPID.Compute();
|
|
|
|
|
|
|
|
/************************************************
|
|
|
|
* turn the output pin on/off based on pid output
|
|
|
|
************************************************/
|
2015-05-09 11:20:53 -07:00
|
|
|
if (millis() - windowStartTime > WindowSize)
|
2011-12-14 04:20:47 -08:00
|
|
|
{ //time to shift the Relay Window
|
|
|
|
windowStartTime += WindowSize;
|
|
|
|
}
|
2015-05-09 11:20:53 -07:00
|
|
|
if (Output < millis() - windowStartTime) digitalWrite(RELAY_PIN, HIGH);
|
|
|
|
else digitalWrite(RELAY_PIN, LOW);
|
2011-12-14 04:20:47 -08:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|