Hello;
I am working on a project in which there are two rotary encoder. I need to display RPM of both encoder on serial monitor. But the RPM of only encoder connected to pin 2 & 3 is displayed and RPM of encoder connected to pin 20 & 21 is sowing 0.00. The code is as follows:
int encoderPin1 = 2;
int encoderPin2 = 3;
int encoderPin3 = 20;
int encoderPin4 = 21;
volatile int lastEncoded = 0;
volatile int lastEncoded2 = 0;
volatile long encoderValue = 0;
volatile long encoderValue2 = 0;
long lastencoderValue = 0;
long lastencoderValue2 = 0;
int lastMSB = 0;
int lastLSB = 0;
long previousMillis = 0;
long currentMillis = 0;
void setup() {
Serial.begin (9600);
pinMode(encoderPin1, INPUT);
pinMode(encoderPin2, INPUT);
pinMode(encoderPin3, INPUT);
pinMode(encoderPin4, INPUT);
digitalWrite(encoderPin1, HIGH);
digitalWrite(encoderPin2, HIGH);
digitalWrite(encoderPin3, HIGH);
digitalWrite(encoderPin4, HIGH);
attachInterrupt(encoderPin1, updateEncoder, CHANGE);
attachInterrupt(encoderPin2, updateEncoder, CHANGE);
attachInterrupt(encoderPin3, updateEncoder2, CHANGE);
attachInterrupt(encoderPin4, updateEncoder2, CHANGE);
}
void loop() {
currentMillis = millis();
if (currentMillis - previousMillis > 1000) {
previousMillis = currentMillis;
float rpm = (encoderValue * 60.00 / 1600.00);
float rpm2 = (encoderValue2 * 60.00 / 1600.00);
Serial.print(rpm);
Serial.print(" ");
Serial.print(rpm2);
Serial.println();
encoderValue = 0;
encoderValue2 = 0;
}
}
void updateEncoder() {
int MSB = digitalRead(encoderPin1);
int LSB = digitalRead(encoderPin2);
int encoded = (MSB << 1) | LSB;
int sum = (lastEncoded << 2) | encoded;
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
encoderValue ++;
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
encoderValue --;
lastEncoded = encoded;
}
void updateEncoder2() {
int MSB2 = digitalRead(encoderPin3);
int LSB2 = digitalRead(encoderPin4);
int encoded2 = (MSB2 << 1) | LSB2;
int sum = (lastEncoded2 << 2) | encoded2;
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
encoderValue2 ++;
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
encoderValue2 --;
lastEncoded2 = encoded2;
}
from SoftwareSerial library Not all pins on the Mega and Mega 2560 boards support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
I am not using change interrupts because Mega 2560 board already has 06 interrupt pins i.e 2,3,18,19,20,21. My problem is why the value of pin 20 & 21 sowing 0.
Otherwise look into the "pin change" interrupt process. It is slightly more complex in that you have to do a bit of work to find out what pin on what channel caused the interrupt.