diff --git a/docs/recipes.md b/docs/recipes.md index 8c638ef..e88f9c1 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -343,3 +343,36 @@ sleep(5) left_motor.off() right_motor.off() ``` + +## Potentiometer + +Continually print the value of a potentiometer (values between 0 and 1023): + +```python +from gpiozero import MCP3008 + +while True: + with MCP3008(channel=0) as pot: + print(pot.read()) +``` + +## Full Colour LED controlled by 3 Potentiometers + +Wire up three potentiometers (for red, green and blue) and use each of their values to make up the colour of the LED: + +```python +from gpiozero import RGBLED, MCP3008 + +def read_pot(channel): + with MCP3008(channel=channel) as pot: + return 100 * pot.read() / 1023 + +led = RGBLED(red=2, green=3, blue=4) + +while True: + red = read_pot(0) + green = read_pot(1) + blue = read_pot(2) + led.rgb = (red, green, blue) + print(red, green, blue) +``` diff --git a/gpiozero/__init__.py b/gpiozero/__init__.py index d60ec04..85e7088 100644 --- a/gpiozero/__init__.py +++ b/gpiozero/__init__.py @@ -11,6 +11,7 @@ from .input_devices import ( MotionSensor, LightSensor, TemperatureSensor, + MCP3008, ) from .output_devices import ( OutputDevice, @@ -29,4 +30,3 @@ from .boards import ( FishDish, TrafficHat, ) - diff --git a/gpiozero/input_devices.py b/gpiozero/input_devices.py index cfbe2d4..c850647 100644 --- a/gpiozero/input_devices.py +++ b/gpiozero/input_devices.py @@ -8,6 +8,7 @@ from threading import Event from RPi import GPIO from w1thermsensor import W1ThermSensor +from spidev import SpiDev from .devices import GPIODeviceError, GPIODeviceClosed, GPIODevice, GPIOQueue @@ -346,3 +347,32 @@ class TemperatureSensor(W1ThermSensor): @property def value(self): return self.get_temperature() + + +class MCP3008(object): + """ + MCP3008 ADC (Analogue-to-Digital converter). + """ + def __init__(self, bus=0, device=0, channel=0): + self.bus = bus + self.device = device + self.channel = channel + self.spi = SpiDev() + + def __enter__(self): + self.open() + return self + + def open(self): + self.spi.open(self.bus, self.device) + + def read(self): + adc = self.spi.xfer2([1, (8 + self.channel) << 4, 0]) + data = ((adc[1] & 3) << 8) + adc[2] + return data + + def __exit__(self, type, value, traceback): + self.close() + + def close(self): + self.spi.close() diff --git a/setup.py b/setup.py index 80bbf92..8f501c3 100644 --- a/setup.py +++ b/setup.py @@ -21,6 +21,7 @@ setup( install_requires=[ "RPi.GPIO", "w1thermsensor", + "spidev", ], long_description=read('README.rst'), classifiers=[