interfacing encoder of a dc motor with arduino uno

hello,

I am trying to read the speed of a dc motor with encoder using arduino uno board. From the available information in arduino website I could write a program to read pulses using attachinterrupt. But in the program I used as well as in the examples I referred, they have used an encoder which gives either 12 pulse per rotation or 24 pulse for rotation. My actual motor's encoder gives 255 pulses for rotation. Can some one help me out with the situation and also tell me if there is a better way to write a program.

Here is my current program

It is just a test program to read the speed from the encoder

/* read a rotary encoder with interrupts
Encoder hooked up with common to GROUND,
encoder0PinA to pin 2, encoder0PinB to pin 4

*/

#define encoder0PinA 2
#define encoder0PinB 4

unsigned int encoder0Pos=0;
int newposition;
int oldposition;
int newtime;
int oldtime;
float vel;
void setup()
{

pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // turn on pullup resistor
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH); // turn on pullup resistor
attachInterrupt(0, doEncoder, RISING); // encoDER ON PIN 2
Serial.begin (9600);
Serial.println("start"); // a personal quirk

}

void loop()
{
newposition = encoder0Pos;
newtime = (0.001*millis());
vel = (newposition-oldposition)/(newtime-oldtime);
Serial.print ("\n speed = ");
Serial.print (vel);
oldposition = newposition;
oldtime = newtime;
delay(1000);
}

void doEncoder()
{
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
encoder0Pos++;
} else {
encoder0Pos--;
}

Serial.println (encoder0Pos, DEC);
}

Thanks in Advance :slight_smile:

sir,
i use 20 step rotary encoder,
the code you provided works weel and good for me..i have a doubt to ask...
the values the encoder provides
is it counter value?
or the the positional value of the controller?