Description
Hi, Having trouble when my rpm goes over 500 RPM then the calculations just dies and show zero.
Im using this encoder.
https://www.ebay.co.uk/itm/155166834587?hash=item2420a9ff9b:g:S78AAOSwoi9jJXEm
Here is the code.
I have tried both pullup and pulldown but it doesnt help.
Cant figure it out.
#include <Arduino.h>
#include <ESP32Encoder.h>
// Define pin numbers for encoder A and B channels
const int encoderPinA = 14;
const int encoderPinB = 12;
// Create an encoder object
ESP32Encoder encoder;
// Variables for RPM calculation
volatile long pulseCount = 0;
unsigned long lastTime = 0;
unsigned long lastCount = 0;
unsigned long rpm = 0;
unsigned int ppr = 1000;
uint32_t next, myInt = 0;
void calculateRPM();
void setup()
{
Serial.begin(115200);
// Set encoder pins as input
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
//ESP32Encoder::useInternalWeakPullResistors = puType::DOWN;
// Enable the weak pull up resistors
//ESP32Encoder::useInternalWeakPullResistors = puType::UP;
// Attach the encoder pins to the ESP32Encoder object
encoder.attachFullQuad(encoderPinA, encoderPinB);
// Set initial position (optional)
encoder.setCount(0);
}
void loop()
{
calculateRPM();
// Your main loop code goes here
}
void calculateRPM()
{
// Calculate RPM every second
unsigned long currentTime = millis();
if (currentTime - lastTime >= 1000)
{
// Read encoder position
long currentPosition = encoder.getCount();
// Calculate change in position considering rollover
long positionChange = currentPosition - lastCount;
// Determine the direction of rotation
int direction = (positionChange >= 0) ? 1 : -1;
// Update pulse count based on direction
pulseCount += direction * positionChange;
// Calculate RPM based on direction
if (direction == 1)
{
rpm = ((positionChange * 60) / ppr) ;
}
else
{
rpm = ((-positionChange * 60) / ppr) ;
}
// Update variables for the next calculation
lastCount = currentPosition;
lastTime = currentTime;
}
}