Wednesday 29 April 2015

Raspberry Pi, MCP3008 ADC & Python

I'm converting a vintage radio into a Raspberry Pi powered music player and I needed an analogue to digital converter (ADC) to allow my raspberry pi to read the old crusty switched and volume controls.

The MCP3008 ADC is pretty cheap and easy to use with the Pi, so I bagged myself one.

Raspberry Pi Spy has got a really good tutorial on setting up an MCP3008 to read analogue sensors which I followed to get everything running, but the code didn't fit my needs so I created a python class for reading data from the MCP3008.
from spidev import SpiDev

class MCP3008:
    def __init__(self, bus = 0, device = 0, channel = 0):
        self.bus, self.device, = bus, device, channel
        self.spi = SpiDev()

    def __enter__(self):
        return self

    def open(self):, self.device)
    def read(self):
        adc = self.spi.xfer2([1, (8 + << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def __exit__(self, type, value, traceback):
    def close(self):

The class is really easy to use, using Python's 'with' statement to control it:
with MCP3008(channel = 0) as ch0:
The code is here -

No comments:

Post a Comment

Note: only a member of this blog may post a comment.