I originally built my project on the Arduino Uno R4 Wifi. Everything seemed to work fine.
#include <Arduino.h>
#define CLK_PIN D2
#define DT_PIN D3
unsigned long lastTime = 0;
bool blinkState = true;
int leftEncoderAngle = 0;
void onLeftTrigger()
{
bool dirState = digitalRead(DT_PIN);
if (dirState)
leftEncoderAngle++;
else
leftEncoderAngle--;
}
void setup()
{
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(CLK_PIN, INPUT_PULLDOWN);
pinMode(DT_PIN, INPUT_PULLDOWN);
attachInterrupt(digitalPinToInterrupt(CLK_PIN), onLeftTrigger, RISING);
}
void loop()
{
auto timeStamp = millis();
if (timeStamp - lastTime >= 100)
{
if (blinkState)
{
digitalWrite(LED_BUILTIN, LOW);
}
else
{
digitalWrite(LED_BUILTIN, HIGH);
}
blinkState = !blinkState;
lastTime = timeStamp;
Serial.println(leftEncoderAngle);
}
delay(10);
}
I then tried to move the project to Arduino Nano ESP32 due to its form factor. I'm running the exact same code and the readings go totally wacko. Sometimes it triggers and other times it doesn't.
The bool dirState = digitalRead(DT_PIN); never seems to work, i.e. when leftEncoderAngle increments (on the random occasion) the state of the other pin is never detected
Here is an image of the encoder signals on a scope.
I am using the yellow and purple lines.
