Hi everybody, i have a problem with optical encoder and the motor shield. When the two motors are stopped, the encoders function properly: making them rotate by hand, they count 20 steps per spin but when the motors are on, some interferences make much many steps be counted instead of their real number.
I paste the code but not the whole one because it’s too long. I don’t think there’s something wrong, but there could be something to better.
#define LEFT 0
#define RIGHT 1
//i pin usati per i due motori
int SX = 6;
int M1 = 7;
int DX = 5;
int M2 = 4;
//le due "velocità" dei motori
int velocita_sx = 100;
int velocita_dx = 100;
//array per l'encoder
long coder[2] = {0,0};
void setup(){
attachInterrupt(LEFT, LwheelSpeed, CHANGE); //inizializzo il pin 2 per l'interrupt
attachInterrupt(RIGHT, RwheelSpeed, CHANGE); //inizializzo il pin 3 per l'interrupt
pinMode(M1, OUTPUT); //pin per il controllo dei due motori
pinMode(M2, OUTPUT);
Serial.begin(9600);
}
void loop(){
Serial.print("Coder value: "); //stampo a monitor il valore dell'array
Serial.print(coder[LEFT]);
Serial.print("[Left Wheel] ");
Serial.print(coder[RIGHT]);
Serial.println("[Right Wheel]");
digitalWrite(M1,LOW); //per definire il senso di rotazione
digitalWrite(M2, LOW);
if(coder[LEFT] < 50 && coder[RIGHT] < 50){ //dovrebbe fare 50 passi dell'encoder e poi fermarsi
analogWrite(SX, velocita_sx);
analogWrite(DX, velocita_dx);
}
if(coder[LEFT] >= 50 && coder[RIGHT] >= 50){
analogWrite(DX, 0);
analogWrite(SX, 0);
}
}
//le due funzioni chiamate dall'interrupt per aumentare il contatore dei passi
void LwheelSpeed()
{
coder[LEFT] ++;
}
void RwheelSpeed()
{
coder[RIGHT] ++;
}
Thanks for your help.