Skip to content

Commit 0a63db8

Browse files
authored
Merge pull request adafruit#515 from adafruit/Analog_Inputs_for_Raspberry_Pi_Using_the_MCP3008
Analog inputs for raspberry pi using the mcp3008
2 parents af51290 + 8d11b96 commit 0a63db8

4 files changed

+72
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import os
2+
import time
3+
import busio
4+
import digitalio
5+
import board
6+
import adafruit_mcp3xxx.mcp3008 as MCP
7+
from adafruit_mcp3xxx.analog_in import AnalogIn
8+
9+
# create the spi bus
10+
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
11+
12+
# create the cs (chip select)
13+
cs = digitalio.DigitalInOut(board.D22)
14+
15+
# create the mcp object
16+
mcp = MCP.MCP3008(spi, cs)
17+
18+
# create an analog input channel on pin 0
19+
chan0 = AnalogIn(mcp, MCP.P0)
20+
21+
print('Raw ADC Value: ', chan0.value)
22+
print('ADC Voltage: ' + str(chan0.voltage) + 'V')
23+
24+
last_read = 0 # this keeps track of the last potentiometer value
25+
tolerance = 250 # to keep from being jittery we'll only change
26+
# volume when the pot has moved a significant amount
27+
# on a 16-bit ADC
28+
29+
def remap_range(value, left_min, left_max, right_min, right_max):
30+
# this remaps a value from original (left) range to new (right) range
31+
# Figure out how 'wide' each range is
32+
left_span = left_max - left_min
33+
right_span = right_max - right_min
34+
35+
# Convert the left range into a 0-1 range (int)
36+
valueScaled = int(value - left_min) / int(left_span)
37+
38+
# Convert the 0-1 range into a value in the right range.
39+
return int(right_min + (valueScaled * right_span))
40+
41+
while True:
42+
# we'll assume that the pot didn't move
43+
trim_pot_changed = False
44+
45+
# read the analog pin
46+
trim_pot = chan0.value
47+
48+
# how much has it changed since the last read?
49+
pot_adjust = abs(trim_pot - last_read)
50+
51+
if pot_adjust > tolerance:
52+
trim_pot_changed = True
53+
54+
if trim_pot_changed:
55+
# convert 16bit adc0 (0-65535) trim pot read into 0-100 volume level
56+
set_volume = remap_range(trim_pot, 0, 65535, 0, 100)
57+
58+
# set OS volume playback volume
59+
print('Volume = {volume}%' .format(volume = set_volume))
60+
set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' \
61+
.format(volume = set_volume)
62+
os.system(set_vol_cmd)
63+
64+
# save the potentiometer reading for the next loop
65+
last_read = trim_pot
66+
67+
# hang out and do nothing for a half second
68+
time.sleep(0.5)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Analog_Inputs_for_Raspberry_Pi_Using_the_MCP3008
2+
3+
Code to accompany this tutorial:
4+
https://learn.adafruit.com/reading-a-analog-in-and-controlling-audio-volume-with-the-raspberry-pi

0 commit comments

Comments
 (0)