Hi everyone,
I'm an ME student and am having difficulties implement the PID controller (Using PID_V1, from Brett B.).
The project is this:
Using the Serial Monitor, imput a desired RPM velocity. This is our setpoint for the PID. The encoder has already been coded to read RPM. The PID will read the encoder as the input, and output to the motor.
Currently, I am using a potentiometer to change our desired Setpoint on the fly. Implementing the serial should not be problem later.
This is what our code looks like:
#include <PID_v1.h>
#define encoder0PinA 2
#define encoder0PinB 4
int pwmh = 11;
int dir = 10;
int potpin = A0;
volatile long encoder0Pos=0;
long newposition;
long oldposition = 0;
long posdelta;
long timedelta;
unsigned long newtime;
unsigned long oldtime = 0;
volatile long vel;
int Kp=1;
int Ki=10;
int Kd=1;
int rpm;
int Automatic;
int Direct;
double Setpoint, Input, Output;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, Direct);
const int sampleRate = 1;
const long serialPing = 500;
void setup()
{
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH);
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH);
attachInterrupt(0, doEncoder, RISING);
pinMode(pwmh, OUTPUT);
pinMode(dir, OUTPUT);
pinMode(potpin, INPUT);
Serial.begin (9600);
Serial.println("start");
myPID.SetMode(Automatic);
myPID.SetSampleTime(sampleRate);
}
void loop()
{
Setpoint = map(analogRead(potpin), 0, 1023, 0, 255);
Serial.println(Setpoint);
newposition = encoder0Pos;
newtime = millis();
posdelta=abs(newposition-oldposition);
timedelta=newtime-oldtime;
oldposition = newposition;
oldtime = newtime;
vel = ((posdelta*60000) / timedelta)/24;
Serial.print ("RPM = ");
Serial.println (vel);
Input = vel;
myPID.Compute();
myPID.SetTunings(Kp, Ki, Kd);
analogWrite(pwmh, Output);
delay(1000);
}
void doEncoder()
{
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
encoder0Pos++;
} else {
encoder0Pos--;
}
}
I am by no means a good programmer/coder. This code is the result of inspiration from a bunch of different examples.
ANY help would be greatly appreciated. I've attached a picture. I'm currently using a Polulu motor driver to control the motor.