Interfacing Optocoupler motor speed sensor with raspberry pi

Sharad Rawat
3 min readOct 30, 2020

Before you begin reading this blog, if you have not checked my previous blog about coupling the IMU with raspberry pi, then read the blog.

One of the first things this robot should/will have is its control over its wheels. The plan is to implement a longitudinal control system and a lateral control system.

However, before rushing to implement these cool control algorithms, we need some more information about the robot. We need to know the actual velocity of the robot (rpm of the wheels). Once we know the actual velocity and the set reference velocity (which we will set in the code), we compute the error and implement the control algorithms to minimize this error. In this blog, we will talk about one such sensor which gives this information, a speed sensor.

Speed Sensor for raspberry pi.

Here’s a quick explanation of how this speed sensor works. The sensor has an IR emitter, and directly opposite to it is the photoelectric receiver. When an object is placed in between the transmitter and the receiver, the beam is broken and the sensor detects the presence of an object.

Using this sensor and a little acrylic disk attached to a motor, we calculate how fast the motor is spinning.

Acrylic disk a.k.a. encoder

Now, let’s have a look at the connections. It has 4 pins and its connections are as follows:

1) VCC — 3.3 V pin of raspebrry pi (Pin 1)

2) GND — GND of raspberry pi (Pin 34)

3) D0 (Digital Output pin) — GPIO 16 of raspberry pi (Pin 36)

4) A0 (Analog Output pin) — Not to be used

The setup looks something like this.

Encoder in between the sensor.

Once the hardware integration is done, its time to test its functionality.
For testing, a small python program is written which can be found in my repository.

The console output is as follows:

Console output gives the motor rpm.

Perfect. This works like a charm. Our job here is done.
Note: the rpm values are fluctuating, a simple moving average algorithm would dampen these fluctuations.

Photo by NeONBRAND on Unsplash

In this blog, we learnt how to connect the speed sensor with raspberry pi and how to extract the rpm data from it. Finally, I should be able to start working on the software module.

Thanks for reading this blog. If you like reading this series of blogs, please clap. Your appreciation is a huge encouragement.

Photo by Tyler Nix on Unsplash

--

--