Thanks! Mr.John, One more question I'm setting the setpoint of the PID value to the counts that are taken up by the encoder like 9 so I think when the PID sees the value counted isn;t 9 then it will strive to achieve that position by rotation forward or reverse to get hold to that position but mine isn;t working like that??
The following is the completed code:
#include <PID_v1.h>
#define encoder0PinA 2
#define encoder0PinB 3
volatile unsigned int encoder0Pos = 0;
// Motor control 1 is connected to the Digital PIN 5
const int MotorControlPin1 = 5;
// Motor control 2 is connected to the Digital PIN 6
const int MotorControlPin2 = 6;
//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, DIRECT);
void setup() {
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
Setpoint = 4;
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
attachInterrupt(1, doEncoderB, CHANGE);
myPID.SetMode(AUTOMATIC);
Serial.begin (19200);
}
void loop(){
Input = encoder0Pos;
myPID.Compute();
if (Output > 0)
{
// Output is positive so set MotorControlPin2 (Direction) to HIGH
digitalWrite(MotorControlPin2, HIGH);
// When Direction is HIGH, a LOW on MotorControlPin1 (PWM Speed) causes the motor to run
analogWrite(MotorControlPin1, 255 - constrain((int)Output, 0, 255));
}
else
{
// Output is negative so set MotorControlPin2 (Direction) to LOW
digitalWrite(MotorControlPin2, LOW);
// When Direction is LOW, a HIGH on MotorControlPin1 (PWM Speed) causes the motor to run
analogWrite(MotorControlPin1, constrain((int)-Output, 0, 255));
}
}
void doEncoderA(){
// look for a low-to-high on channel A
if (digitalRead(encoder0PinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // must be a high-to-low edge on channel A
{
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
Serial.println (encoder0Pos, DEC);
// use for debugging - remember to comment out
}
void doEncoderB(){
// look for a low-to-high on channel B
if (digitalRead(encoder0PinB) == HIGH) {
// check channel A to see which way encoder is turning
if (digitalRead(encoder0PinA) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
// Look for a high-to-low on channel B
else {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinA) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
}