-->
Page 1 of 1

Irregular readings from encoder with attachInterrupt()

PostPosted: Tue Jan 11, 2022 6:47 pm
by Cleiton Alves
Hi guys.

I need to read an encoder using the interrupt function by the wemos d1 mini board. However, plotting the readings results in an irregular waveform.

So I tested doing the reading without the interrupt function, just with digitalRead, and when plotting, the waveform was as expected.

In my project I can't just use digitalRead because I can lose readings while executing other functions. Any solution to this problem?

I attached the waveforms that I obtained in each of the tests, through the Serial Plotter. Also, I attached the circuit.

https://drive.google.com/file/d/1WTYii8 ... sp=sharing.

Frequency of the waveform is 40hz.

Below is a simplified code that I used to do just these reading tests:

Code: Select all#define motor 4
#define rotary_encoder 14

boolean signal_encoder = 0;

ICACHE_RAM_ATTR void waveForm() {
  signal_encoder = !signal_encoder;
}

void setup() {
  Serial.begin(115200);
  pinMode(rotary_encoder, INPUT_PULLUP);
  pinMode(motor, OUTPUT);
 // attachInterrupt(digitalPinToInterrupt(rotary_encoder), waveForm, CHANGE);
}

void loop() {
  digitalWrite(motor, 1);

  if(digitalRead(rotary_encoder))signal_encoder=1;
  else signal_encoder = 0;
 
  Serial.println(signal_encoder);
  delay(1);
}

Re: Irregular readings from encoder with attachInterrupt()

PostPosted: Wed Jan 12, 2022 2:24 am
by pratheek
Your signal_encoder variable should be declaread as volatile as you are you using it in an interrupt.

Checkout -
https://www.arduino.cc/reference/en/lan ... /volatile/

If you modify a variable inside an interrupt, then you should declare this variable as volatile.

Also in the digitalPinToInterrupt function, the mode is CHANGE. Check if this is what is you want.

Re: Irregular readings from encoder with attachInterrupt()

PostPosted: Wed Jan 12, 2022 4:38 am
by btidey
I built a library for handling encoders using interrupts that is reliable and can handle up to 3 encoders.

It is included in the rotary encoder button project

https://github.com/roberttidey/RotaryEncoderButton