2012-09-08

Raspberry Pi distance measuring sensor with LCD output

Measure distances from the Sharp GP2Y0A02YK0F sensor using an MCP3008 ADC and hardware SPI.


The Sharp GP2Y0A02YK0F can be powered from the 5V supply on the Raspberry Pi. The Analog output is less than 3V and so can easily work with the logic level circuit. If you buy one of these look for the cable that goes with it to save you some bother.

This project builds on two previous projects in this blog. For the Analog to Digital SPI electronics and Python code first go here: Raspberry Pi hardware SPI analog inputs using the MCP3008. For the TextStar LCD first read this: Raspberry Pi with TextStar Serial LCD Display.

In the first video below the sensor is held in a clamp at the very top left of the picture. You can just about make out the display showing the distance to my hand. At the other end of the table there's a chair so when I lift my hand up it shows the distance to that instead - about 118 cm. The second video is a close-up of the screen while I move my hand forward and backwards in front of the sensor. Again the jumps to 118 cm are when I raise a lower my hand. 



All the code is available on github. You'll need mcp3008.py and distance-screen.py to run this project. The code assumes that you have the sensor output connected to CH1 on the MCP3008. The main routine to look at in the code is the translation from the sensor output to a distance. In the datasheet there's a graph which plots distance against voltage output:
I compared this against my sensor by laying a tape measure on the table and looking at the voltage output - it matched perfectly. I was about to start working out a formula to fit this curve when I found a good set of comments on the Sparkfun page including a magic formula!

Here's my Python routine which is called 10 times a second using the on_tick handler from the screen driver:

def write_distance():
    display.position_cursor(1, 1)
    r = []
    for i in range (0,10):
        r.append(mcp3008.readadc(1))
    a = sum(r)/10.0
    v = (a/1023.0)*3.3
    d = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 306.439
    cm = int(round(d))
    val = '%d cm' % cm
    percent = int(cm/1.5)
    display.ser.write(str(val).ljust(16))
    display.capped_bar(16, percent)


  • Firstly, take ten readings and find the average (a) - this smooths things out a little.
  • Convert this to a voltage (v)
  • Use the magic formula to get the distance (d)
  • Round this to the nearest centimetre (cm)
  • Then write this to the display along with a 16 character capped bar graph
So the code happily reads from the sensor 100 times a second and does the calculation and screen update 10 times a second. The CPU usage hovers around 2% in top.

2012-09-05

Raspberry Pi hardware SPI analog inputs using the MCP3008

A hardware SPI remake of the bit-banged Adafruit project:  Analog Inputs for Raspberry Pi Using the MCP3008.


Take a look at the Adafruit project and particularly the datasheet for the MCP3008 - what we're making is a hardware volume control using a 10K potentiometer. Instead of using the GPIO pins and bit-banging the SPI protocol I'm using the proper SPI pins and the hardware driver.

Hardware


The connections from the cobbler to the MCP3008 are as follows:
  • MCP3008 VDD -> 3.3V (red)
  • MCP3008 VREF -> 3.3V (red)
  • MCP3008 AGND -> GND (orange)
  • MCP3008 CLK -> SCLK (yellow)
  • MCP3008 DOUT -> MISO (green)
  • MCP3008 DIN -> MOSI (yellow)
  • MCP3008 CS -> CE0 (red)
  • MCP3008 DGND -> GND (orange)

Operating system and packages

This project was built using Occidentalis v0.2 from Adafruit which takes the hassle out of fiddling with Linux. It comes with the hardware SPI driver ready to go. (It also has super-simple wifi setup if you have a dongle like the Edimax EW-7811UN). A couple of packages are required to complete this project. Firstly the mp3 player:
sudo apt-get install mpg321

and secondly the Python wrapper for SPI:
cd ~

git clone git://github.com/doceme/py-spidev

cd py-spidev/

sudo python setup.py install

Talking to the MCP3008

With the bit-banging code you're in control of the chip-select, clock, in and out pins and so you can effectively write and read a single bit at a time. When you use the hardware driver you talk using 8-bit words and it takes care of the lower level protocol for you. This changes the challenge slightly because the MCP3008 uses 10-bits for the values giving a range from 0 to 1023. Thankfully the Python wrapper is excellent and the datasheet has good documentation:

So from the diagram above you can see that to read the value on CH0 we need to send 24 bits:

.... ...s S210 xxxx xxxx xxxx
0000 0001 1000 0000 0000 0000

Let's say the current value is 742 which is 10 1110 0110 in 10-bit binary. This is what is returned in B9 to B0 in the diagram. The driver and Python wrapper returns this as 3 8-bit bytes as seen above, the mildly confusing thing is that you'll get some bits set where the question marks are in the diagram which you have to ignore (if you were sending a continuous stream these would be more useful). The 24 bits returned will be something like this:

???? ???? ???? ?n98 7654 3210
0110 0111 1000 0010 1110 0110

The python wrapper will give you 3 ints in a list:

[103,130,230]

So, we ignore the first int and then mask out all the bits apart from the last two of the second int by anding it with 3 (0000 0011). In this case you get 0000 0010. We then shift this left by 8 positions to give 10 0000 0000 and then add the third int to give 10 1110 0110 which is 742 decimal. Here's the Python for that:

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum):
        if ((adcnum > 7) or (adcnum < 0)):
                return -1
        r = spi.xfer2([1,(8+adcnum)<<4,0])
        adcout = ((r[1]&3) << 8) + r[2]
        return adcout
The rest of the code is pretty much the same as the Adafruit example. My version is available on git here: https://github.com/jerbly/Pi/blob/master/raspi-adc-pot.py

Run it

Start up mpg321 with your favourite mp3 in the background and then run the Python code:
mpg321 song.mp3 &

sudo python raspi-adc-pot.py
Turn the pot to adjust the volume.


Extra goodies

Combine this with the TextStar screen and the Python code from my previous blog entry: Raspberry Pi with TextStar serial LCD to have a nice bar graph for the pot position. Just use this method on one of the pages and in the on_tick handler so it updates every 0.1 seconds:

# Add this to the display class
    def capped_bar(self, length, percent):
        self.ser.write(ESC+'b'+chr(length)+chr(percent))

s = spidev.SpiDev()
s.open(0,0)

def get_val():
    r = s.xfer2([1,128,0])
    v = ((r[1]&3) << 8) + r[2]
    return v

def write_pots():
    display.position_cursor(1, 1)
    val = get_val()
    percent = int(val/10.23)
    display.ser.write(str(val).ljust(16))
    display.capped_bar(16, percent)