Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: mbed
encoder.cpp
00001 #include "encoder.h" 00002 00003 // Represents a quadrature motor encoder. Modified from mbed QEI 00004 Encoder::Encoder(PinName channelA, PinName channelB) : 00005 channelA_(channelA), 00006 channelB_(channelB){ 00007 pulses = 0; 00008 00009 //Workout what the current state is. 00010 int chanA = channelA_.read(); 00011 int chanB = channelB_.read(); 00012 00013 //2-bit state. 00014 currState_ = (chanA << 1) | (chanB); 00015 prevState_ = currState_; 00016 00017 channelA_.rise(this, &Encoder::encode); 00018 channelA_.fall(this, &Encoder::encode); 00019 } 00020 00021 //Internally updates the pulse count for the encoder. 00022 void Encoder::encode(void) { 00023 int chanA = channelA_.read(); 00024 int chanB = channelB_.read(); 00025 00026 //2-bit state. 00027 currState_ = (chanA << 1) | (chanB); 00028 00029 //11->00->11->00 is counter clockwise rotation or "forward". 00030 if ((prevState_ == 0x3 && currState_ == 0x0) || 00031 (prevState_ == 0x0 && currState_ == 0x3)) { 00032 pulses+=2; 00033 } 00034 //10->01->10->01 is clockwise rotation or "backward". 00035 else if ((prevState_ == 0x2 && currState_ == 0x1) || 00036 (prevState_ == 0x1 && currState_ == 0x2)) { 00037 pulses-=2; 00038 } 00039 00040 prevState_ = currState_; 00041 } 00042 00043 //Resets the encoder 00044 void Encoder::reset(void) { 00045 pulses = 0; 00046 } 00047 00048 // Reset both encoders 00049 void Encoder:: resetEncoders(){ 00050 leftEncoder.reset(); 00051 rightEncoder.reset(); 00052 } 00053 00054 // Returns the average number of pulses across both encoders since last reset. Unit is encoder pulses; intended for straight driving only. 00055 int Encoder:: getEncoderDistance(bool left){ 00056 00057 return (left == 1) ? leftEncoder : rightEncoder; 00058 }
Generated on Thu Jul 14 2022 05:30:38 by
