Hello,
i have a question regarding the use of the PID Library. My goal is to control a ball on a beam and therefore i am measuring its position with an ultrasonic signal and taking the resulting distance value as an input for my PID. The Output should adjust the angle of a servo. I made a first attemp to get used to implementing a PID controller, but it does not seem to work as it should. I am using the following code:
#include <NewPing.h>
#include <Servo.h>
#include <PID_v1.h>
double Setpoint, Input, Output;
Servo myServo;
PID myPID(&Input, &Output, &Setpoint,1,0,0, DIRECT);
int distVal;
int angle;
int actualDist;
int TRIG_PIN = 10;
int ECHO_PIN = 11;
int MAX_DIST = 20;
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DIST);
void setup() {
Serial.begin(9600);
myServo.attach(9);
//turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop() {
//measure distance
Serial.print("Ping: ");
distVal = sonar.ping_cm();
Serial.print(distVal);
Serial.print("cm, ");
//control servo
Input = distVal;
Setpoint = 11;
myPID.Compute();
Serial.print(", PID Output: ");
Serial.print(Output);
angle = map(Output, 0, MAX_DIST, 0, 179);
Serial.print(", angle: ");
Serial.println(angle);
myServo.write(angle);
delay(50);
}
My Setpoint ist defined as 11cm and therefore i expect that some PID Output will be calculated if the current measured distance stored in the variable distVal differs from the setpoint. It works for measured values below the setpoint but if they are above it, which results in a negative error value, the PID does not seem to react as the Output value remains to be zero.
Here you can see some lines of monitored values which might help to understand what i try to explain:
Ping: 5cm, , PID Output: 6.00, angle: 53
Ping: 6cm, , PID Output: 5.00, angle: 44
Ping: 6cm, , PID Output: 5.00, angle: 44
Ping: 7cm, , PID Output: 4.00, angle: 35
Ping: 7cm, , PID Output: 4.00, angle: 35
Ping: 8cm, , PID Output: 3.00, angle: 26
Ping: 8cm, , PID Output: 3.00, angle: 26
Ping: 9cm, , PID Output: 2.00, angle: 17
Ping: 9cm, , PID Output: 2.00, angle: 17
Ping: 10cm, , PID Output: 1.00, angle: 8
Ping: 11cm, , PID Output: 1.00, angle: 8
Ping: 11cm, , PID Output: 0.00, angle: 0
Ping: 12cm, , PID Output: 0.00, angle: 0
Ping: 13cm, , PID Output: 0.00, angle: 0
Ping: 14cm, , PID Output: 0.00, angle: 0
Ping: 15cm, , PID Output: 0.00, angle: 0
Ping: 16cm, , PID Output: 0.00, angle: 0
The way i choosed the PID Parameters, the Output basically represents the Error. I have done this for the sake of troubleshooting. Please dont pay attention on the angle value since i have to tune everything to get a correct behavior of the system.
Thanks to everyone who will take a look in my code and help me to fix this issue. At the moment i just could not find my mistake.