How to calculate RPM correctly using encoders?
I have optical encoders that read the ticks and publishes the tick count everytime when there is a new tick:
def tick_callback(channel):
global tick
global pub
tick += 1
pub.publish(tick)
class EncoderNodeLeft:
def __init__(self,encoder):
self.tick = 0
self.encoder = encoder
self.rate = rospy.Rate(100)
GPIO.setmode(GPIO.ASUS)
GPIO.setwarnings(False)
GPIO.setup(encoder, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def run(self):
global tick
GPIO.add_event_detect(self.encoder, GPIO.RISING, callback=tick_callback)
while not rospy.is_shutdown():
self.rate.sleep()
But the problem arises when I need to count the RPM and in order to do that, I need a current tick, the last tick and the time difference. The difference between current and last tick is always 1:
void MotorRPM::encoderCallbackRight(const std_msgs::Int64::ConstPtr &msg) {
std_msgs::Float64 rpm_msg;
// get the time difference
ros::Time now = ros::Time::now();
ros::Duration time = now - lastMessageTime;
int rightDifference = msg->data - lastRightEncoder.data;
//ROS_INFO("The tick: %d, the lastData: %d", msg->data, lastRightEncoder.data);
rpm_msg.data = rpmFromEncoderCount(rightDifference, time.toSec());
// publish all the time
rpmPubRight.publish(rpm_msg);
lastMessageTime = now;
lastRightRPM.data = rpm_msg.data;
lastRightEncoder.data = msg->data;
}
Am I doing something wrong? Because I always have a difference of 1 I get incorrect RPM