I've been working on getting multiple PID controls working with my hardware. Now that I have the basics up and running, is there a more efficient way to code this? I'll be running 4 and possibly up to 6 PID's using roughly the same settings.
On side note: PID1 is rock steady,PID2 seems a bit jumpy, is there anything in the code that would cause that?
#include <PID_v1.h>
int actual1;
int demand1;
int actual2;
int demand2;
double Pk = 10; //speed it gets there
double Ik = 0;
double Dk = 0;
double Setpoint1, Input1, Output1;
double Setpoint2, Input2, Output2;
PID PID1(&Input1, &Output1, &Setpoint1, Pk, Ik, Dk, DIRECT);
PID PID2(&Input2, &Output2, &Setpoint2, Pk, Ik, Dk, DIRECT);
void setup() {
pinMode (A0, INPUT);
pinMode (A1, INPUT);
pinMode (A2, INPUT);
pinMode (A3, INPUT);
pinMode (5, OUTPUT);
pinMode (6, OUTPUT);
pinMode (7, OUTPUT);
pinMode (8, OUTPUT);
Serial.begin(115200);
PID1.SetMode(AUTOMATIC);
PID1.SetOutputLimits(-255,255);
PID1.SetSampleTime(10);
PID2.SetMode(AUTOMATIC);
PID2.SetOutputLimits(-255,255);
PID2.SetSampleTime(10);
}
void loop() {
// ** start PID 1 **
actual1 = analogRead(A0);
demand1 = analogRead(A1);
actual1 = map(actual1,0,1023,341,682);
actual1 = map(actual1,341,682,-255,255);
demand1 = map(demand1,0,1023,-255,255);
Input1 = actual1;
Setpoint1 = demand1;
PID1.Compute();
if (Output1 < 0) {
Output1 = abs(Output1);
analogWrite(5,Output1);
analogWrite(6,0);
}
else if (Output1 >= 0) {
Output1 = abs(Output1);
analogWrite(6,Output1);
analogWrite(5,0);
}
else {
analogWrite(5,0);
analogWrite(6,0);
}
// ** start PID 2 **
actual2 = analogRead(A2);
demand2 = analogRead(A3);
actual2 = map(actual2,0,1023,341,682);
actual2 = map(actual2,341,682,-255,255);
demand2 = map(demand2,0,1023,-255,255);
Input2 = actual2;
Setpoint2 = demand2;
PID2.Compute();
if (Output2 < 0) {
Output2 = abs(Output2);
analogWrite(7,Output2);
analogWrite(8,0);
}
else if (Output2 >= 0) {
Output2 = abs(Output2);
analogWrite(8,Output2);
analogWrite(7,0);
}
else {
analogWrite(7,0);
analogWrite(7,0);
}
delay(10);
}