Optical Wheel Encoder from Infrared Printer Sensor


Quick post about some intermediary work I had to do while working on my new Self Balancing robot.

Once the basics were done and the robot was balancing, I realised that it seemed unstable as it wasn’t staying in place…

The easiest way to deal with this would be an optical encoder for the wheels, that would tell me how much each moves.

Optical sensor mounted

Optical sensor mounted

I can’t remember exactly what model it was, but I got these from an old printer that I dismantled.

Optical sensors from printer

Optical sensors from printer

They are very simple hardware wise, and also very easy to use (many thanks to this guy, who’s post helped me understand the circuit).

Printer optical sensor shematic

Printer optical sensor shematic

All I had to do was to 3D print an encoder wheel and put it on the same axle as the actual wheel

Encoder wheel

Encoder wheel

Here’s the sample Arduino code, not the most useful 🙂 but I think it’s a pretty good starting point as it uses interrupts to detect the changes, making sure it doesn’t miss any step.

#define MOTOR_ENABLE_PIN 5
#define MOTOR_IN3_PIN 7
#define MOTOR_IN4_PIN 4

volatile int count = 0;
volatile int speed = 80;

void setup(){
 Serial.begin(115200);
 
 pinMode(MOTOR_ENABLE_PIN, OUTPUT);
 pinMode(MOTOR_IN3_PIN, OUTPUT);
 pinMode(MOTOR_IN4_PIN, OUTPUT);
 
 // enable PULL-UP resistor for interrupt pins
 pinMode(3, INPUT_PULLUP);
 
 // attach interrupt on digital pin 2
 attachInterrupt(1, event, RISING);
}

void loop(){
 Serial.print(count);Serial.print(" / ");
 setMotorSpeed(80);
 while(count < 18) delay(1);
 Serial.println(count);
 setMotorSpeed(-80);
 while(count > -18) delay(1);
}

void setMotorSpeed(int s){
 // put this in a global variable so that we can read it in the ISR for the direction
 speed = s;
 
 if(speed > 0){
 digitalWrite(MOTOR_IN3_PIN, LOW);
 digitalWrite(MOTOR_IN4_PIN, HIGH);
 }else{
 digitalWrite(MOTOR_IN3_PIN, HIGH);
 digitalWrite(MOTOR_IN4_PIN, LOW);
 }
 
 analogWrite(MOTOR_ENABLE_PIN, abs(speed));
}

void event(){
 // we can't know from the even itself the direction, so use the speed of the motor
 if(speed > 0){
 count ++;
 }else if(speed < 0){
 count --;
 }
}

And finally, here’s the video corresponding to the above code. Not very captivating, I know… 🙂

 

One Response to Optical Wheel Encoder from Infrared Printer Sensor

  1. Pingback: Self Balancing Robot – V3 | Robotics / Electronics / Physical Computing

Leave a comment