2013 Arduino PID Lab 0
2013 Arduino PID Lab 0
/*
Length of pendulum = 40 cm
Mass of pendulum rod = 11 grams,
Mass of weight = 6 grams
*/
#include <PID_v1.h>
int enc1 = 2; //Linear encoder pin 1
int enc2 = 4; //Linear encoder pin 2
int in1 = 3; //PWM output to L298n
int in2 = 11; //PWM outout to L298n
int en = 12; //Pin to enable/disable H bridge
int count; //Counter for linear encoder (Resolution: 300ppi)
int abit; //Variable for reading angle sensor
double a_in, a_out, a_setp, p_in, p_out, p_setp, output, pwmin; //PID parameters
PID posPID(&p_in, &p_out, &p_setp,0.001,0,0.0008, DIRECT); // PID loop for
controlling the setpoint of pendulum
PID angPID(&a_in, &a_out, &a_setp,4.6,430,0, DIRECT); // PID loop for controlling
the motor
void setup()
{
//TCCR2B = TCCR2B & 0b11111000 | 0x04;
pinMode(enc1, INPUT);
pinMode(enc2, INPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(en, OUTPUT);
attachInterrupt (0, encoder, RISING); //Reading linear encoder for tracking cart
position
digitalWrite(en, HIGH); //Enable/Disable H-bridge
Serial.begin(9600);
posPID.SetMode(AUTOMATIC);
posPID.SetSampleTime(10);
posPID.SetOutputLimits(-3,3);
angPID.SetMode(AUTOMATIC);
angPID.SetSampleTime(1);
angPID.SetOutputLimits(-195,195);
}
void loop()
{
if(count < 1000 && count > -1000) //To prevent the cart from hitting the ends
{
p_setp = 0;
p_in = count;
posPID.Compute();
a_setp = 545.4 + p_out;
a_in = analogRead(abit);
angPID.Compute();
output = a_out;
if(output<0)
{
pwmin = (-1*output) + 60;
analogWrite(in2, 0);
analogWrite(in1, pwmin);
}
if(output>0)
{
pwmin = (output+60);
analogWrite(in1,0);
analogWrite(in2, pwmin);
}
Serial.println(a_in);
}
else
{
digitalWrite(en,LOW);
analogWrite(in1, 0);
analogWrite(in2, 0);
}
}
void encoder ()
{
if (digitalRead(enc1) == digitalRead(enc2))
{
count++;
}
else
{
count--;
}
}