What is the code to read the analog values of the Sharp Distance Sensor



I want a code a script on the raspberry pi that would read the analog values from the Sharp Distance Sensor the model is GP2Y0A21YK0F, the Sharp Distance Sensor is interface to the MCP3002 ADC chip and the Raspberry Pi, This is how the circuit is built

All the connection that I have done are the same within this image, the only difference is I just have to substitute the potentiometer for the Infrared Distance Sensor
this is what I tried to do:

import time
import botbook_mcp3002 as mcp #

def readSharpdistancesensor():
global sharpdistancesensor
sharpdistancesensor = mcp.readAnalog() #

def main():
while True: #
readSharpdistancesensor() #
print("The current sharpdistancesensor value is %i " % sharpdistancesensor) #
time.sleep( 0.5) # s

if name = = “main”:

The objective for this code is to get the Sharp Distance Sensor to detect an object and return a distance value so what would be the right code for this


Thanks, that’s an interesting one.

I’ve reviewed the datasheets, focusing on the pinouts, and the specs, and there’s something fundamentally wrong with your design; the distance sensor is specified for 5V operation and you are powering it at 3.3V. The ADC chip can run at 5V, but the Raspberry Pi I/O pins cannot. So you should power the distance sensor from 5V, the ADC chip from 3.3V, and use a resistive divider between the output of the distance sensor and the input of the ADC chip to bring the signal voltage into range. Datasheet links:

On the other hand, I’ve been able to run these types of distance sensors at the wrong voltage, it is just that they don’t work so well because they are running outside their specifications. My guess is that you tried it anyway.

What happens when you try to run the script? You must have had some problem to want to ask for help, but I’m not sure what that problem is.

It might be the missing indentation in the Python script. Looking around at other people who have done the same thing, I’ve found what looks to be what you’ve been basing your work on;

Unfortunately, that author did not properly indent their example code. If you copied it as is, you would have got an error from Python and it would not have run.

Other people who have done something similar do properly indent, and they don’t use a separate library file, you might review their work;

That’s just the tip of the iceberg.


While I said above;

use a resistive divider between the output of the distance sensor and the input of the ADC chip to bring the signal voltage into range

further reading of the datasheet shows the output voltage is unlikely to reach above 3.3V, so a series 1K resistor should be enough instead of using a divider arrangement. As a result, you’ll get better resolution.

Compare Figure 2 on page 5 with distance measuring range specification of 10cm minimum.


You know how you mention “you should power the distance sensor from 5V, the ADC chip from 3.3V, and use a resistive divider between the output of the distance sensor and the input of the ADC chip to bring the signal voltage into range” How exactly do I build a voltage divider circuit of the Distance Sensor and the ADC? can you please give me an example on how to do this like images or diagrams


Now that I’ve looked at the datasheet again, as I said above in my second reply, I don’t think you need to use a voltage divider.

But for the sake of interest, a voltage divider is a pair of resistors in series, with the lower resistor tied to ground, with the higher voltage applied to to top resistor, and the divided voltage stolen from the middle. It divides voltage by a fixed fraction.

You can find references elsewhere that better explain it with diagrams;

You don’t need it in your case because the output voltage of the distance sensor won’t normally exceed 3.3V even though the component is powered from 5V.

To protect against a cascading fault, add a resistor of about 1K between the distance sensor output and the ADC chip input.

A cascading fault is where a fault in one component cascades into causing faults in other components. In your case, should the distance sensor fail with a fault that raises output to 5V in contravention of the datasheet specifications, that voltage would go on to damage the ADC chip, because the ADC chip has an absolute maximum rating of 3.3V plus 0.6V.

A resistor on that path would limit the voltage the ADC experiences, during the fault.


Hi this is the circuit that I’ve built already

within this circuit where do I add a 1k resistor between the distance sensor output and the ADC chip input


You have a connection from the output wire of the distance sensor to the input pin 2 of the MCP3002 ADC chip.

In the photograph, the output wire of the distance sensor is white, then you have a green jumper wire connecting it to pin 2 of the MCP3002 ADC chip.

Place the resistor in series with that connection, such that current has no choice but to flow through the resistor.


Hi I think I found a similar code through these links https://github.com/ryochiji/roll-e/blob/master/code/irdar/irdar.py and https://github.com/ryochiji/roll-e/blob/master/code/irdar/distance.py
But for my case I’m using a Distance Sensor, MCP3002 and a Raspberry Pi so how can I modify this code in order to suit my objective in order to get the Distance Sensor to detect an object and return a distance value

And also is this where I should place the resistor according to this image?


I can’t tell from the photograph; it is dark, and some of the wires are behind other wires. As long as the resistor is in series with the output wire of the distance sensor, it is placed correctly. If there’s something I’m saying you don’t understand, or not sure about, ask me.

The code you referred to is for a distance sensor mounted on a servo connected to an MCP3008, not an MCP3002. To use it you might have to understand each of the meaningful differences between the MCP3008 datasheet and the MCP3002 datasheet. It’s a big job. It is better to stick with code for the MCP3002.

You might also try writing the code directly, using the spidev module. You can do this interactively, at the Python interpreter prompt, until you’ve understood what is needed to get the data. For example;

# python
>>> from spidev import SpiDev
>>> spi = SpiDev()
>>> spi.open(0,0)
>>> bytes = spi.xfer2([128, 0])
>>> print bytes

Also, remember that the ADC gives you a number that is related to the voltage it receives, and the sensor gives a voltage that is related to the distance to the object. The MCP3008 code in distance.py shows the author calibrated their sensor and ADC combination using mathematical curve fitting. That calibration won’t work for you, it will be different. The datasheet for the sensor does have a curve, in figure 2 on page 5, which may be helpful if you need to estimate a calibration.

To use code someone else has written in a different environment, you often have to be able to understand every line and letter of the code. Well done for trying! If you have questions about how their code works, contact them, or reference a line here and I’ll try to explain it.


So what would be the right code to detect an object and calculate the distance using a raspberry pi, sharp distance sensor and the MCP3002. If you do know could you please write the code for me and send it to me because I’m not a programmer.


To our other community readers; can any of you help write this code?

Mate, don’t underestimate yourself. You may learn to be a programmer. You’ll need at least ten hours to get started. There are courses, and videos, and podcasts, and tutorials, and people you can ask when you have small questions.

Yes, I could write the code, but I would have to ask you more questions, buy the same components and do some engineering. I’ve other engineering work, so I would give you a quote. The engineering in my replies above won’t be included in the quote. You can contact me by e-mail on quozl@netrek.org.

But to be fair, I’m not here to drum up work for myself. You may ask other people as well, not just me. You may write to help@littlebirdelectronics.com to see if they have a list of other people they can refer you to. There are also online hiring services such as Airtasker. There may be a hackerspace near you. There are also the people whose web pages you saw above.

Hope that helps!


Just another question can I use a digital multimeter to measure the voltages of the Infrared Distance Sensor like this one https://www.jaycar.com.au/low-cost-digital-multimeter-dmm/p/QM1500



Set the meter for 2V. Connect the black lead from the multimeter to the ground of the sensor. Connect the red lead from the multimeter to the output of the sensor. If the measurement is above 2V, the meter will safely show overvoltage, and you can switch to 20V; which gives less resolution.

While the leads are connected, the ADC chip may receive extra noise, but this will go away once you disconnect.

If you haven’t got it yet, I’ve comments on the meter itself.

The meter has a comparatively low 1M input impedance, which is one reason it is so cheap. The sensor has an output circuit that should overcome that impedance easily, but it isn’t specified in the sensor datasheet, so expect the voltage to fall very slightly as a result of attaching the meter.

Last time I checked this meter in a shop, I didn’t like the feel of the leads and probes, but again, for the price one can ignore that. They may have changed since.

Looking at the manual, the specifications are valid for 23 C plus or minus 5 C, which to me seems a little short changing, but for the price one can ignore that too.

Hope that helps.