3

I'm using an arduino UNO, and i want to turn a motor a set number of revolutions, i'm trying to read the clicks of the encoder which has a resolution of 360 clicks/ revolution, my logic is that i count the number of clicks until i get to the desired number which represents the the number of revolutions * the resolution of the encoder:

1 revolution ==> 360 clicks
5 revolutions ==> 360*5 (desired number)

i'm a beginner with arduino so here is my code:

volatile int counter=0;
int motor=5;  // motor is connected to pin 5

void setup(){
  pinMode(motor,OUTPUT);
  attachInterrupt(0, count,RISING); // attaching encoder on interrupt 0
}

void loop(){
  while(counter< 360*5){
    analogWrite(motor,255);
  }
}

void count(){
  counter++;
}

This code is not working at all, how can i fix it?

sachleen
  • 7,565
  • 5
  • 40
  • 57
Apastrix
  • 33
  • 1
  • 4

2 Answers2

2

You never tell the motor to stop.

void loop(){
   while(counter< 360*5){
     analogWrite(motor,255);
   }
   analogWrite(motor, 0); //add something like this or whatever could stop it
   //you may want to disable the counter now too
}

However, even with that change you are likely a long way from having a working, or at least reliable system - see other issues in my comment on the question.

Chris Stratton
  • 5,411
  • 20
  • 40
0

Since the Encoder resolution is high, the Arduino Uno misses some pulses hence you could not get the accurate reading from it. You could use the hardware quadrature decoder in Arduine Due board which can easily read the encoder values.

Here is a code which can only be executed in arduino Due to Read one quadrature encoder. How to configure 2nd Quadrature Decoder IO pins in Arduino IDE

Masood Salik
  • 47
  • 2
  • 9