INCREMENTAL MOTOR ENCODER EXAMPLE

This is an example of using a small DC brushed motor that has an incremental optical encoder on the shaft. The encoder is read by an opto interrupter. The assembly was salvaged from a dead HP printer. No datasheet could be had for the opto interrupter, there are many similar projects like this on the web.

The plan for this project was to first just be able to calculate the motor rpm from the opto interrupter pulses.

The LED side of the opto interrupter was powered from the mbed 3.3V out and had a measured current of 20mA.

/media/uploads/lhiggs/_scaled_imag0519.jpg /media/uploads/lhiggs/_scaled_encoder_crop.jpg /media/uploads/lhiggs/_scaled_inc_encoder.png /media/uploads/lhiggs/_scaled_imag0521.jpg

Import programOPTO_INTERRUPTER

Example brushed dc motor example using an H-Bridge for motor direction/speed control and an opto interrupter for position/velocity feedback.

#include "mbed.h"
 
PwmOut EN(p22);
DigitalOut A1(p16);
DigitalOut A2(p17);
 
Serial pc(USBTX, USBRX);
 
long float delta_time = 0;
float rpm = 0;
float inc_enc_constant = 0.03125;    // 32 Encoder Ticks per Revolution
 
 
Timer t;
// t.read_us() is 32bit interger, max 2^31 - 1 = 2147483647 us = 2147.483647 s = 35.7913941167 min
 
class Counter
{
public:
 
 
    Counter(PinName pin) : _interrupt(pin) {        // create the InterruptIn on the pin specified to Counter
        _interrupt.fall(this, &Counter::increment); // attach increment function of this counter instance
    }
 
 
    void increment() {
        delta_time = t.read_us();
        t.reset();
 
        rpm = ( inc_enc_constant  / (delta_time/1000000) ) *60 ; // rev / m
 
        _count++;
    }
 
    int read() {
        return _count;
    }
 
private:
    InterruptIn _interrupt;
    volatile int _count;
};
 
 
 
 
 
Counter counter(p30);   // opto interrupter counter
 
int main()
{
    pc.baud(115200);
    EN.period(0.020);
 
    t.start();
 
    float duty = 0.10;
 
    while(1) {
 
        wait(1);
 
        EN.write(duty);
        duty = duty + 0.01; // increment H-Bridge EN PWM duty cycle 1%
        A1 = 1;         // set H-Bridge input A1 high
        A2 = 0;         // set H-Bridge input A2 low
 
        // pc.printf("Count so far: %d\n", counter.read());
        // pc.printf("dt: %d\n", delta_time);
 
        pc.printf("RPM: %f\n", rpm);
        pc.printf("DUTY CYCLE: %f\n",duty);
 
    }
}



1 comment on INCREMENTAL MOTOR ENCODER EXAMPLE:

06 Jan 2016

Counter(PinName pin) : _interrupt(pin) { create the InterruptIn on the pin specified to Counter _interrupt.fall(this, &Counter::increment); attach increment function of this counter instance }

not clear about this line

Please log in to post comments.