Go Down

### Topic: Arduino code counting the encoder pulses dc motor (Read 9625 times)previous topic - next topic

#### SirKnumskull

##### Apr 05, 2013, 09:22 pm
I have a 12 Volt 92.6 rpm dc motor with encoder.I have this code to calculate the number of pulses.the number of pulses that is counted when 1 second is passed was counted with using the serial monitor of the Arduino
Code: [Select]
`volatile int count = 0;long int i = 0;int cassy = 10;int n;void setup(){attachInterrupt(0, counter, RISING);}void counter(){count++;}void loop(){// 15,000 corresponds to 1 second. So, 150 => 10 ms.if(i == 150){n = count;count = 0;i = 0;}int w = map(26*n, 0, 555.6, 0, 255);analogWrite(cassy, w);i++;}`
but it doesn't work.Code is wrong or connections between arduino and dc motor is wrong.

#### PaulS

#1
##### Apr 06, 2013, 05:04 pm
Quote
but it doesn't work.

Perhaps the problem is your assumption that 15000 somethings equals one second.

There are millis() and micros() functions that report elapsed time, so you don't have to guess how many iterations of loop() correspond to some amount of time.

You should have no trouble determining if the problem is the hardware or the software. If the number of pulses is increasing, at a reasonable rate, when the motor spins at a known speed, then the hardware (the encoder) iw working fine, and your means of counting is wrong. If the number of pulses is not increasing at a reasonable rate, when the motor spins at a known speed, then the encoder is not connected correctly.

What kind of encoder is it? Typically, an encoder requires two interrupt pins, so that you can also determine direction. If your motor only spins one direction, then getting the direction from the encoder isn't necessary.

#### SirKnumskull

#2
##### Apr 07, 2013, 02:09 pm
thanks for the reply.encoder has two interrupt pins.yellow one and orange one.how do they connect to arduino?.maybe I did it wrong.can you say how I must be connect pins according to code.thank you very much.

#### CrazyCreator

#3
##### Jun 20, 2013, 04:44 pm
The color of the wires isn't enough information. Typically, quadrature encoders have two signals: A and B. Attach the A signal to an interrupt that triggers on the rising edge. Then, in the function called by the interrupt, check the digital state of B. If B is high, you are spinning forward and increase your counter. If B is low, you are spinning backward and decrease your counter.

That solution gives you current encoder position and direction. If you want to get encoder speed, every loop calculated the change in encoder position and divide it by change in time (?P/?T).

#### 1ChicagoDave

#4
##### Jul 13, 2013, 01:43 am
Have you checked the Playground?

http://playground.arduino.cc/Main/RotaryEncoders

Go Up