Hello, i am making a project where i want to calculate the velocity and rotation direction of a arduino motor.
This is the code so far:
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
int enableA = 9;
int in1= 6;
int in2= 5;
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
void setup() {
pinMode(enableA, OUTPUT);
pinMode (in1, OUTPUT);
pinMode (in2, OUTPUT);
// Set encoder pins as inputs
pinMode(CLK,INPUT_PULLUP);
pinMode(DT,INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// Call updateEncoder() when any high/low changed seen on interrupt 0 (pin 2), or interrupt 1 (pin 3)
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
}
void loop() {
digitalWrite(enableA, 255);
analogWrite(in1, LOW);
analogWrite(in2, HIGH);
}
void updateEncoder(){
// Read the current state of CLK
currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1){
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
counter --;
currentDir ="CCW";
} else {
// Encoder is rotating CW so increment
counter ++;
currentDir ="CW";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}
i am simulating this project on tinkercad: Login | Tinkercad
the motor isn`t spinning fast but i think that this is a tinkercad problem?
however i have managed to get the counter and the direction working but the next problem is how i can calculate the velocity based on the pulses from the encoder.
any suggestions?