# ENCODER HOW TO ENCREASE THE PRECISION ,?

i want to increase the precision of the encoder .
i’v got an incremental encoder with 38 Holes ;
here is the Code :

``````const int piste_A=2 , piste_B=3;
int a;
void setup (){
pinMode(piste_A,INPUT);
pinMode(piste_B,INPUT);
Serial.begin(9600);
}
void loop (){
Serial.print("vitesse=");
encoder( piste_A, piste_B);
}
void encoder(const int piste_A, const int piste_B)
{

attachInterrupt(0,direction_speed, RISING);
}
void direction_speed()
{
int direction = 0;
double t;
double angle;
int i=0;
double d;
double speed;
//direction
if (digitalRead(piste_B) == LOW) direction =1;
else direction= - 1;
//speed:
t = millis();
while(i<20)
{
attachInterrupt(0,increment,RISING);

i=i+1;
}
t =millis() - t;
angle = a* 9.5;// 380/38=9.5° the angle of each hole.
d = 3* angle;// diametre of the wheel = 3 cm .
speed = (direction*d)/t;
Serial.println(vitesse);
}

void increment()
{
a = a+1;
}
``````
``````void encoder(const int piste_A, const int piste_B)
{

attachInterrupt(0,direction_speed, RISING);
}
``````

What is this function supposed to be doing ? It is supplied 2 parameters that are never used in the function and attaches an interrupt each time through the loop() function when it only needs to be attached once in setup()

Then, later on, in the middle of the ISR you attach the same interrupt to another routine 20 times

``````  while(i<20)
{
attachInterrupt(0,increment,RISING);

i=i+1;
}
``````

Later in the same ISR you attempt to print a variable that is not defined even though Serial.print() does not work in an ISR because interrupts are disabled.

``````  Serial.println(vitesse);
``````

This shows what you need to implement:-
http://www.thebox.myzen.co.uk/Workshop/Rotary_Max.html
It is implemented in hardware but it is just as easy to do it in software.

I totally agree that function void encoder is useless.
And vitesse i just forgot to change it to speed when posting the code.
And about attach interrupt (0,increment,RISING) inside loop while
It's just to know how many rising i have during period t to calcul the speed.

Sorry for my english. :*
And I'm still noob in programming. :*

``````And about attach interrupt (0,increment,RISING) inside loop while
It's just to know how many rising i have during period t to calcul the speed.
``````

Once the interrupt is attached it will not be explicitly detached unless you do it so you only need to do it once. Doing it 20 times achieves nothing.

Could you explain more .???
I think function interrupt will test if there is RISING and if it's true it will
Increment "a" Then i will multiply It by the angle of each hole
To Get the angle of rotation of my wheel then to get the distance I will apply distance =angle*(diameter/2)
Then speed =distance/t.
t I will count it using millis .
So to get the period To cross the distance interrupted should be inside
Loop "while"

Can you post your code as it is now, with the corrections?