Count the number of rising edges

htliew:
Hi,

I want to count the number of rising edges on the A encoder signals coming out form the motor between two rising edges of the z encoder pulse. My code is as below,

int countA = 0;

void setup()
{
pinMode(2, INPUT); //z encoder
pinMode(3, INPUT); //A encoder

Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(2), doEncoder, RISING);
Serial.println("start");
}
void loop(){

}
void doEncoder()
{

for (digitalRead(2) == HIGH) {
if (digitalRead(3) == HIGH) {
countA = countA + 1;
}
}Serial.println(countA, DEC);

}

May i know what's wrong with the code as it won't stop counting the positive edge on encoder A. I only want it to count once when there is a rising edge of z encoder.

Thanks.

Just curious - how does the above code compile? The complier should generate syntax error on incorrect "for(...)".

The code would be much simpler, less variables, if you gate in the ISR on z first then advance the "new rising edge " counter.

if(z)
new rising edge counter++

then in loop() compare new and old rising edge counter and if different do your processing.

But .. you will need a code to monitor the z "pulse" window , perhaps add an ISR for z also.

Time to draw a flow chart before coding.