ESP32Encoder
ESP32Encoder copied to clipboard
Liberary doesn't work when generating a PWM signal (when pins 15 and 16 split the PWM and encoder)
this is the code. if i remove the "ledcWrite(ledChannel, counter);" and "ledcAttachPin(ledPin, ledChannel);" everything works and the encoder position is kept track of. If the line is present 90% of the encoder rotations are not detected. I tried to change the ledChannel,frequency and resolution. it did nothing I used a regular ESP32 Dev Module
#include <ESP32Encoder.h> // https://github.com/madhephaestus/ESP32Encoder.git #define CLK 4 // CLK ENCODER #define DT 15 // DT ENCODER ESP32Encoder encoder;
const int ledPin = 16; // 16 corresponds to GPIO16 const int freq = 25000; const int ledChannel = 0; const int resolution = 8; int counter = 50; void setup () { encoder.attachHalfQuad ( DT, CLK ); encoder.setCount ( 0 ); ledcSetup(ledChannel, freq, resolution); ledcAttachPin(ledPin, ledChannel); ledcWrite(ledChannel, counter); Serial.begin ( 115200 ); }
void loop () {
long newPosition = encoder.getCount() / 2;
Serial.println(newPosition);
}
try using ESP32Servo library with the ESP32PWM objects. I have used those two together to make motors with encoders into industrial servo style devices before. This library combines them to make motor objects: https://github.com/WPIRoboticsEngineering/RBE1001Lib
@madhephaestus even when using the ESP32PWM object I get the same behavior (a lot of the rotations are not being detected). Allocating all or different timers does nothing. code used:
#include <ESP32Encoder.h> #define CLK 4 // CLK ENCODER #define DT 15 // DT ENCODER ESP32Encoder encoder;
#include <ESP32Servo.h> int APin = 16; ESP32PWM pwm; int freq = 25000; float brightness = 150;
void setup () { encoder.attachHalfQuad ( DT, CLK ); encoder.setCount ( 0 ); Serial.begin ( 115200 ); ESP32PWM::allocateTimer(3); pwm.attachPin(APin, freq, 8); // 1KHz 8 bit pwm.write(brightness); }
void loop () {
long newPosition = encoder.getCount() / 2;
Serial.println(newPosition);
delay(10);
}
does moving the pins around change anything? 16 and 15 are a serial port pins which means they share a crossbar for mod changing, and maybe there is some issue with the crossbar switching back and forth from input to output? just to test try moving the PWM somewhere else?
for some reason, the same code that didn't work the previous day worked today perfectly for about 3 minutes before producing the same behavior. As per your suggestion, I ended up switching the PWM pin to GPIO 32 and since then it all seems to be functioning normally
Im going to leave this open because there is some strange lower level interaction here, but i am glad you are able to move forward.
One other though could be a bad or floating ground where the PWM is inducing a transient current into the encoder pin next door.