Hello,
I was trying to compute the speed of the motors in tinkercad and I observed that after I stop the motor, either by setting the pwm value to 0 or by writing LOW on both inputs of the motor, and then starting it again, the volatile variable inside my isr stops incrementing.
For the moment I am not computing the speed, but only printing the position variables:
#define IN1 8
#define IN2 7
#define IN3 11
#define IN4 12
#define ENA 10
#define ENB 9
#define ENCAL 2
#define ENCBL 4
#define ENCAR 3
#define ENCBR 5
// interrupt variables
volatile int pos_iL = 0;
volatile int pos_iR = 0;
void setup()
{
Serial.begin(9600);
// left motor setup
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(ENA, OUTPUT);
// right motor setup
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENB, OUTPUT);
// encoder setup
pinMode(ENCAL, INPUT_PULLUP);
pinMode(ENCBL, INPUT_PULLUP);
pinMode(ENCAR, INPUT_PULLUP);
pinMode(ENCBR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCAL), readEncoderLeft, RISING);
attachInterrupt(digitalPinToInterrupt(ENCAR), readEncoderRight, RISING);
}
void loop()
{
// periodically toggle the pwm between 0 and 100
int pwm = (int)(100*(sin(micros()/1e6)>0));
runMotors(pwm, 1, -1);
}
int runMotors(int speed, int dirLeft, int dirRight) {
int posL = 0, posR = 0;
noInterrupts();
posL = pos_iL;
posR = pos_iR;
interrupts();
Serial.print(posL);
Serial.print(" ");
Serial.println(posR);
setMotor(IN1, IN2, ENA, speed, dirLeft);
setMotor(IN3, IN4, ENB, speed, dirRight);
}
void setMotor(int in1, int in2, int en, int pwm, int dir) {
analogWrite(en, pwm);
if (dir == 1) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
} else if (dir == -1) {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
} else {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
}
void readEncoderLeft() {
int b = digitalRead(ENCBL);
int increment = 0;
if (b > 0) {
increment = 1;
}
else {
increment = -1;
}
pos_iL = pos_iL + increment;
}
void readEncoderRight() {
int b = digitalRead(ENCBR);
int increment = 0;
if (b > 0) {
increment = 1;
}
else {
increment = -1;
}
pos_iR = pos_iR + increment;
}
The position variables increment until the motor stops, but when the motor starts again, they remain the same.
Here is the tinkercad design link:
https://www.tinkercad.com/things/eogJ4CCPVqh?sharecode=GVcSaNppgpvYntTKRMj66LSi94V9TuspmHKZ36gmFa4