#include <PID_v1.h>
#include <Servo.h>
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1,P_ON_M, DIRECT); //P_ON_M specifies that Proportional on Measurement be used//P_ON_E (Proportional on Error) is the default behavior
Servo servo_1; // servo controller (multiple can exist)
int servo_pin = 3; // PWM pin for servo control
int pos = 0; // servo starting position
void setup()
{
Serial.begin(9600);//start serial monitor to display current values on a serial monitor
servo_1.attach(servo_pin); // start servo control
servo_1.write(pos); // move servo to grasp object
Serial.println("Positioned to grasp");
//initialize the variables we're linked to
Input = analogRead(A0);
Setpoint = 0.68;
//turn the PID on
myPID.SetMode(AUTOMATIC);
}
void loop()
{
unsigned int x = 0;
Setpoint = 0.68;
float AcsValue = 0.0, Samples = 0.0, AvgAcs = 0.0, AcsValueF=0.0;
Input = analogRead(A0);
myPID.Compute();
//analogWrite(3,Output);
AcsValue = analogRead(A0);
Samples = Samples + AcsValue; //Add samples together
delay (3); // let ADC settle before next sample 3ms
AvgAcs=Samples/150.0;//Taking Average of Samples
AcsValueF = -
(.259 - (AvgAcs * (5.0 / 1024.0)) )/0.8;
Serial.println(AcsValueF);
delay(50);
if(Setpoint > Input)
{
//String in_char = 0;
//servo_1.write(in_char.toInt());
//servo_1.write(0);
analogWrite(3,OUTPUT);
analogWrite(3,HIGH);
}
else if(Setpoint < Input)
{
//String in_char = "90";
//servo_1.write(in_char.toInt());
// servo_1.write(90);
analogWrite(3,OUTPUT);
analogWrite(3,LOW);
}
}
1 Like