Hi,
I want to measure the distance that have been travelled. For this purpose I bought a motor with encoder. Its model is Mitsumi M25N
I did all the connections correct. Encoder works and its lights are on. I put 1k resistor on both digital outputs of encoder to 5V. When I rotated the motor by my hand, values are only goes to one way although I rotated both ways. I tried several codes I attached both of them can anyone tell me what is wrong?
int pulses; //Output pulses.
int deg = 0;
int encoderA = 3;
int encoderB = 2; //Direction of the motor.
int pulsesChanged = 0;
//Change speed of the motor.
void setup(){
Serial.begin(115200);
pinMode(encoderA, INPUT); //3
pinMode(encoderB, INPUT); //2
attachInterrupt(digitalPinToInterrupt(2), A_CHANGE, CHANGE);
}//setup
void loop(){
if (pulsesChanged != 0) {
pulsesChanged = 0;
Serial.println(pulses);
}
}
void A_CHANGE(){ //Function that to read the pulses in x1.
if( digitalRead(encoderB) == 0 ) {
if ( digitalRead(encoderA) == 0 ) {
// A fell, B is low
pulses--; // moving reverse
} else {
// A rose, B is low
pulses++; // moving forward
}
}
pulsesChanged = 1;
}
In this code I changed the way how interrupt triggered
int pulses; //Output pulses.
int deg = 0;
int encoderA = 3;
int encoderB = 2;
const int pwm = 5; //Power of motor.
const int dir = 4; //Direction of the motor.
int pulsesChanged = 0;
#define total 980 //x4 pulses per rotation.
#define motorSpeed 180 //Change speed of the motor.
void setup() {
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(2), A_CHANGE, FALLING);
attachInterrupt(digitalPinToInterrupt(3), B_CHANGE, FALLING);
}//setup
void loop(){
if (pulsesChanged != 0) {
pulsesChanged = 0;
Serial.println(pulses);
}
}
void A_CHANGE(){
if( digitalRead(encoderB) == 0 ) {
if ( digitalRead(encoderA) == 0 ) {
// A fell, B is low
pulses--; // moving reverse
} else {
// A rose, B is low
pulses++; // moving forward
}
}else {
if ( digitalRead(encoderA) == 0 ) {
// B fell, A is high
pulses++; // moving reverse
} else {
// B rose, A is high
pulses--; // moving forward
}
}
pulsesChanged = 1;
}
void B_CHANGE(){
if ( digitalRead(encoderA) == 0 ) {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is low
pulses++; // moving forward
} else {
// B rose, A is low
pulses--; // moving reverse
}
} else {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is high
pulses--; // moving reverse
} else {
// B rose, A is high
pulses++; // moving forward
}
}
pulsesChanged = 1;
}