Hello,
I am doing a project consisting of an Arduino Mega 2560 and of a motor. The motor comes with an encoder. I am able to set the encoder to work correctly the problem is that now I need to output the speed of the motor shaft in the SerialMonitor. I am attaching below the code until now.
#include <digitalWriteFast.h>
const int pin_enc_A_rising = 2;
const int interrupt_nr_pin_enc_A_rising = 0;
const int pin_enc_A_falling = 3;
const int interrupt_nr_pin_enc_A_falling = 1;
// These variables will be updated in interrupts
volatile long enc_counter = 0;
volatile bool enc_A_high = false;
volatile float vel;
const int Ts = 0.1;
float oldCounter=0;
float oldTime = 0;
bool veru=false;
void setup() {
Serial.begin(9600);
pinMode(pin_enc_A_rising, INPUT);
attachInterrupt(interrupt_nr_pin_enc_A_rising, handleEncA_Rising, RISING);
attachInterrupt(interrupt_nr_pin_enc_A_falling, handleEncA_Falling, FALLING);
}
void handleEncA_Rising(){
enc_A_high= true;
if (digitalReadFast(21) == HIGH){
enc_counter -= 1;
}else{
enc_counter += 1;
}
}
void handleEncA_Falling(){
enc_A_high= false;
if (digitalReadFast(21)==HIGH){
enc_counter += 1;
}else{
enc_counter -= 1;
}
}
void loop(){
if(veri){
tempo1 = tempo2;
tempo2 = micros() ;
velo =enc_counter-oldCounter /(tempo2 - tempo1);
oldCounter=enc_counter;
Serial.println(velo);
veri = false;
}
}
I am using two pins for attach interrupt for encoder A and one digitalread for encoder B. I know I can use only one for the encoder A and a digital pin for the other one but I am testing different versions. I need to calculate the angular speed (velocity) of the motor.
I would be very grateful if you helped me.
Thank your for your time,
Albi Mema