Add MCP3008 and potentiometer example

This commit is contained in:
Ben Nuttall
2015-09-30 19:02:12 +01:00
parent 21297ab2bb
commit fbede611df
4 changed files with 65 additions and 1 deletions

View File

@@ -343,3 +343,36 @@ sleep(5)
left_motor.off() left_motor.off()
right_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)
```

View File

@@ -11,6 +11,7 @@ from .input_devices import (
MotionSensor, MotionSensor,
LightSensor, LightSensor,
TemperatureSensor, TemperatureSensor,
MCP3008,
) )
from .output_devices import ( from .output_devices import (
OutputDevice, OutputDevice,
@@ -29,4 +30,3 @@ from .boards import (
FishDish, FishDish,
TrafficHat, TrafficHat,
) )

View File

@@ -8,6 +8,7 @@ from threading import Event
from RPi import GPIO from RPi import GPIO
from w1thermsensor import W1ThermSensor from w1thermsensor import W1ThermSensor
from spidev import SpiDev
from .devices import GPIODeviceError, GPIODeviceClosed, GPIODevice, GPIOQueue from .devices import GPIODeviceError, GPIODeviceClosed, GPIODevice, GPIOQueue
@@ -346,3 +347,32 @@ class TemperatureSensor(W1ThermSensor):
@property @property
def value(self): def value(self):
return self.get_temperature() 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()

View File

@@ -21,6 +21,7 @@ setup(
install_requires=[ install_requires=[
"RPi.GPIO", "RPi.GPIO",
"w1thermsensor", "w1thermsensor",
"spidev",
], ],
long_description=read('README.rst'), long_description=read('README.rst'),
classifiers=[ classifiers=[