From Imperial College Robotics Society
Jump to: navigation, search


These are small black boxes which are able to count how far round the wheel has turned. Although not required, they are extremely helpful and highly recommended when doing task that require a knowledge of your position, such as navigating a maze or drawing a picture (next weeks challenge).

There is a small semi-circular hole in the side of the encoder where you can slot the wheel axle in. As you will notice we have already filled down one end of this axle which will allow you to simply slot it into the encoder. The rest of the encoder then needs to be secured firmly to the base so that it does not move as well. It could possibly by placing it on a small platform and attaching it with blue tack.

Encoder circuit.png

The encoder wired up as shown in the circuit diagram. Pins A and B, the outer pins, must be connected to digital input pins on the mbed and pin C, the central pin, must be connected to the ground.

Encoder outputs.png

As the encoder spins around the switches are closed and opened. When open a the full voltage is inputed to the mbed, however, when the switch is closed the source is grounded and no voltage is inputed to the mbed. Thus, as the encoder spins it will produce a digital wave, jumping between 0 and 5 volts, the frequency of which indicates the speed the device is turning. Two separate waves will be output from pins A and B as shown in the picture to the right. The waves are slightly out of phase and so the by identifying which wave leads one can also identify which direction the wheel is turning. In the diagram shown, where A is leading, the encoder is turning in the clockwise direction. If B were leading then it would be turning anti-clockwise. Don't worry about this as it is quite easy to negate the direction in the code.

Fortunately, actually wiring it up is very simple. Just plug the wire connected to the central pin (pin C) to the ground and then the other two pins to separate pins on the mbed. The mbed is able to handle pullup resistances in its pins. A library exists which makes use of encoders much easier. Simply go to this page and then click "import this library into a program" and simply select the program you want to include it in. The following is an example code with the encoders attached to pins 29 and 30 and will output the encoders position.

Example Code

#include "QEI.h"
//setup the pins here as per normal
DigitalIn pin29(p29);
DigitalIn pin30(p30);
Serial pc(USBTX, USBRX);
//Use X4 encoding.
//QEI wheel(p29, p30, NC, 624, QEI::X4_ENCODING);
//Use X2 encoding by default.
QEI wheel (p29, p30, NC, 624);
int main() {
    //the pins must be setup manually to act as pullup resistors
        pc.printf("Pulses is: %i\n", wheel.getPulses());