Hardware Reference
In-Depth Information
Parts:
100 Resistor
200K Potentiometer
680 F Electrolytic Capacitor
Figure 7-1. PID example circuit setup
Listing 7-1. Basic PID Arduino Sketch
float Kp = .5 , Ki = .5, Kd = .5 ; // PID gain values
float Pout , Iout , Dout , Output; // PID final ouput variables
float now , lasttime = 0 , timechange; // important time
float Input , lastinput , Setpoint = 127.0; // input-based variables
float error , errorsum = 0, Derror; // output of the PID components
int settime = 1000; // this = 1 second, so Ki and Kd do not need modification
void setup (){
Serial.begin(9600); // serial setup for verification
} // end void setup (){
void loop (){
now = millis() ; // get current milliseconds
timechange = (now - lasttime); // calculate difference
if (timechange >= settime) { // run PID when the time is at the set time
Input = (analogRead(0)/4.0); // read Input and normalize to output range
error = Setpoint - Input; // calculate error
errorsum = errorsum + error; // add curent error to running total of error
Derror = (Input - lastinput); // calculate slope of the input
Pout = Kp * error; // calculate PID gains
Iout = Ki * errorsum ;
Dout = Kd * Derror ;
if (Iout > 255) // check for integral windup and correct
Iout = 255;
Search WWH ::




Custom Search