Skinny Satan

A cool Nerd To Hangout With

How to: use and Interface Rotary Encoders

Encoders are some very lovely devices if you ask me.
They gives you some really great stream of pulses while you are rotating them.
We had seen a few people struggling with it so i thought ‘hey lets document it too’
J-Encoder
Note: Above device is 100ppr Hollow shaft Encoder by J-Encoders.

Encoders are rotary mechanical devices, which do come in mainly 2 different forms. Shaft ones and hollow shaft ones. And as when you couple your motor, pulley or whatever that rotary actuator you are using for your application, the shaft rotates giving out pulses as an output.

There are generally 5 important pins coming out of the encoder. Vcc- Gnd ( as it generally works on 5V DC only) and other pins that are A,B and Z. ( There are also A/, B/ and Z/ that are complementary pins i.e. they give only inverted outputs and they will or will not be there in your encoder)

Encoders are Shipped with certain Pulses per Rotation PPR ratings. and they are available in 100’s to thousands of pprs in market.

A PPR is the rating how precisely your Locomotion can be. Lets say we are having an encoder with 360ppr i.e. for one whole rotation we will get total 360 pulses. that is for each degree of movement we have a pulse. And trust me, this precision is so enough that it will take the exact value every damn time.

these 360 pulses we get on points A and B. So here is the question why do we have 2 different o/ps for same thing? The trick here is both of them are in out of phase with each other. that is if the shaft is moving in a clock wise direction it goes90 degree plus phase and for anticlockwise it gets 90 degree out of phase.
And then there is this Z o/p which gives a single pulse after one whole rotation is done.

So how should i poll the Encoder?

If you are using any sort of micro controllers, ( we are using our very favorite atmega series :* ) there are counters inbuilt. for our atmega 8 in 16bit timer/counter look here

external clock
There is this option of external clock source on pin T1, where we can give our train of pulses. fire up our encoder, the TCNT1 register will start loading the encoder value.

So how do we can use it? Endless possibilities guys, make a tachometer, start measuring distances, implement fuzzy logic. Its totally up to you.

here is a demo code so you will get the idea.

#include
#include
int count=0;

void timer_init()
{
TCCR1B |= (1<<CS11) | (1<<CS12); // External source
DDRD &= ~(1<<PD5); // T1 Pin as input
PORTD |= (1<<PD5); //Pullup high
TCNT1=0;
}

/*
It will go straight till 20 rotations of wheels and then it will stop the motor */

int main()
{

timer_init();

while(1)
{
	while(TCNT1<=2000)
	{
	fwd(); //motor forward
	}

	stop(); //motor stop
}

return 0;
} 

Leave a comment

Information

This entry was posted on September 29, 2013 by in Tutorial and tagged , .