Hi guys/gals.
So a little background, I'm working on a project where I am controlling 2 motors and I am wanting to use some encoders i've just installed as feedback signal to sync the speeds of each motors. I'm hoping this will help me in instances where the robot must drive straight.
Anyway what I'm trying to do is attach interrupts to two pins that have one signal from each encoder plugged into it. Each interrupt function should calculate the period of the corresponding waveform. I want to feed the difference of the periods into the arduino's PID algorithm to speed up/slow down the motors to match each others speed.
Obviously though, this approach does not seem to work and after spending all day on it, I'm reaching out to ya'll. Any help would be appreciated
This is just a simple test sketch that uses code from Simon Tushev's blog on a post about measuring frequency with arduinos.
http://tushev.org/articles/arduino/item/51-measuring-frequency-with-arduino
P.S: I've tested my encoders so at least I know they are working. Kinda a newbie still so be gentle...
#include <PID_v1.h>
#define SAMPLES 1024
int E1 = 5; //M1 Speed Control
int E2 = 6; //M2 Speed Control
int M1 = 4; //M1 Direction Control
int M2 = 7; //M1 Direction Control
int pinA = 2;
int pinB = 3;
int i = 0;
long PerA, PerB;
double Setpoint=0, phaseDiff=0, forwardPWM=50;
PID myPID(&phaseDiff, &forwardPWM, &Setpoint,2,5,1, DIRECT);
void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
digitalWrite(E1,LOW);
digitalWrite(E2,LOW);
digitalWrite(2,HIGH); // Turn on pullup resisitors
digitalWrite(3,HIGH);
myPID.SetMode(AUTOMATIC); //Create an instance of PID
attachInterrupt(0, getPeriodA, CHANGE); //Attach an interrupt to encoder 1 signal A
attachInterrupt(1, getPeriodB, CHANGE); //Attach an interrupt to encoder 2 signal A
Serial.begin(115200);
Serial.print("Start...");
}
void stop(void) //Stop
{
digitalWrite(E1,0);
digitalWrite(M1,LOW);
digitalWrite(E2,0);
digitalWrite(M2,LOW);
}
void advance(char a,char b) //Move forward
{
analogWrite (E1,a); //PWM Speed Control
digitalWrite(M1,HIGH);
analogWrite (E2,b);
digitalWrite(M2,HIGH);
}
void loop(void)
{
advance (forwardPWM,forwardPWM);
myPID.Compute();
calcPhaseDiff();
}
void getPeriodA() {
long measA = 0;
for(unsigned int j=0; j<SAMPLES; j++) measA+= 500000/pulseIn(2, CHANGE, 250000); //Grab 1024 samples of the period
PerA = measA / SAMPLES; //Calcualte the average period of A
Serial.println(PerA);
}
void getPeriodB() {
long measB = 0;
for(unsigned int j=0; j<SAMPLES; j++) measB+= 500000/pulseIn(3, CHANGE, 250000);
PerB = measB / SAMPLES;
Serial.println(PerB);
}
void calcPhaseDiff(){
phaseDiff = abs(PerA-PerB);
}