-
Notifications
You must be signed in to change notification settings - Fork 0
/
potentiometer.py
75 lines (57 loc) · 2.28 KB
/
potentiometer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import os
import time
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
import math
# create the spi bus
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
# create the cs (chip select)
cs = digitalio.DigitalInOut(board.D22)
# create the mcp object
mcp = MCP.MCP3008(spi, cs)
# create an analog input channel on pin 0
chan0 = AnalogIn(mcp, MCP.P0)
last_read = 0 # this keeps track of the last potentiometer value
def remap_range(value, in_min, in_max, out_min, out_max):
# this remaps a value from original (left) range to new (right) range
# Figure out how 'wide' each range is
in_span = in_max - in_min
out_span = out_max - out_min
# Convert the left range into a 0-1 range
valueScaled = float(value - in_min) / float(in_span)
#print("this should be between 0 and 1: ", valueScaled)
# Logarithmically map the value
# first, scale the value to a 0.1-10 range
valueScaled = float(0.1 + (valueScaled * 9.9))
#print("this should be between 0.1 and 10: ", valueScaled)
# then, map it to log base 10
valueScaled = math.log(valueScaled, 10)
#print("this should be between -1 and 1: ", valueScaled)
# then scale it to between 0 and 1
valueScaled = (valueScaled + 1) / 2
# Linearly scale the value to the new range
valueScaled = float(out_min + (valueScaled * out_span))
# Convert the 0-1 range into a value in the right range.
return valueScaled
while True:
# read the analog pin
trim_pot = chan0.value
# if the trim pot is 0 discard the reading
if trim_pot < 1:
trim_pot = last_read
# if trim pot only dropped a bit discard the reading (lots of noise there)
if trim_pot > (last_read - 250) and trim_pot < last_read:
trim_pot = last_read
# convert 16bit adc0 (0-65535) trim pot read into 0-100 volume level
volume = remap_range(trim_pot, 0, 65535, 0, 100)
print("trim pot is ", trim_pot, " remapped to ", volume)
# save the potentiometer reading for the next loop
last_read = trim_pot
# hang out and do nothing for a half second
time.sleep(0.01)