Skip to content

Commit 6c89c4e

Browse files
author
brentru
committed
analog pwm output example
add configurable channel to analog_output example catch prev. values fixup analog_out
1 parent bd26808 commit 6c89c4e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

examples/basics/analog_output.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
`analog_output.py`
3+
-------------------
4+
PWM a LED from
5+
Adafruit IO!
6+
7+
Requires:
8+
- Adafruit-Blinka
9+
- Adafruit-CircuitPython-PCA9685
10+
"""
11+
# import system libraries
12+
import time
13+
14+
# import Adafruit Blinka
15+
from board import SCL, SDA
16+
from busio import I2C
17+
18+
# import the PCA9685 module.
19+
from adafruit_pca9685 import PCA9685
20+
21+
# import Adafruit IO REST client
22+
from Adafruit_IO import Client, Feed, RequestError
23+
24+
# Set to your Adafruit IO key.
25+
# Remember, your key is a secret,
26+
# so make sure not to publish it when you publish this code!
27+
ADAFRUIT_IO_KEY = 'YOUR_IO_KEY'
28+
29+
# Set to your Adafruit IO username.
30+
# (go to https://accounts.adafruit.com to find your username)
31+
ADAFRUIT_IO_USERNAME = 'YOUR_IO_USERNAME'
32+
33+
# Create the I2C bus interface.
34+
i2c_bus = I2C(SCL, SDA)
35+
36+
# Create a simple PCA9685 class instance.
37+
pca = PCA9685(i2c_bus)
38+
PCA_CHANNEL = 4
39+
40+
# Set the PWM frequency to 60hz.
41+
pca.frequency = 60
42+
prev_read = 0
43+
44+
# Create an instance of the REST client.
45+
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
46+
47+
try: # if we have a 'analog' feed
48+
analog = aio.feeds('analog')
49+
except RequestError: # create an `analog` feed
50+
feed = Feed(name='analog')
51+
analog = aio.create_feed(feed)
52+
53+
54+
def map_range(x, in_min, in_max, out_min, out_max):
55+
"""re-maps a number from one range to another."""
56+
mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
57+
if out_min <= out_max:
58+
return max(min(mapped, out_max), out_min)
59+
return min(max(mapped, out_max), out_min)
60+
61+
while True:
62+
# grab the `analog` feed value
63+
analog_read = aio.receive(analog.key)
64+
if analog_read.value != prev_read:
65+
print('received <- ', analog_read.value)
66+
# map the analog value from 0 - 1023 to 0 - 65534
67+
analog_value = map_range(int(analog_read.value), 0, 1024, 0, 65534)
68+
# set the LED to the mapped feed value
69+
pca.channels[PCA_CHANNEL].duty_cycle = int(analog_value)
70+
prev_read = analog_read.value
71+
# timeout so we don't flood IO with requests
72+
time.sleep(0.5)

0 commit comments

Comments
 (0)