Skip to content

Instantly share code, notes, and snippets.

@teddokano
Last active June 15, 2023 10:01
Show Gist options
  • Save teddokano/440c86c229fa5650ca0a044a55eaefcc to your computer and use it in GitHub Desktop.
Save teddokano/440c86c229fa5650ca0a044a55eaefcc to your computer and use it in GitHub Desktop.
Simple LED brightness control (via PCA9956)l by music envelope
from machine import Pin, ADC, Timer
import utime
from machine import I2C
from nxp_periph import PCA9956B, LED
class periodic_adc:
def __init__( self, pin_name, *, interval = 1, scaling = (2 ** 16) ):
self.timer_flag = False
self.adc = ADC( Pin( pin_name ) )
self.scaling = scaling
self.tim = Timer(0)
self.tim.init( period = interval, mode = Timer.PERIODIC, callback = self.timer_callback )
def read( self, blocking = True ):
if blocking:
while not self.timer_flag:
pass
self.timer_flag = False
return self.adc.read_u16() / self.scaling
def timer_callback( self, _ ):
self.timer_flag = True
def main():
i2c = I2C( 0, freq = (400 * 1000) )
led_c = PCA9956B( i2c, 0x02 >>1, iref = 0xFF )
led_d = PCA9956B( i2c, 0x04 >>1, iref = 0xFF )
leds = [ LED( led_c, i ) for i in range( led_c.CHANNELS ) ]
adc = periodic_adc( "A0", interval = 10 )
for i in range( 3 ):
leds[ 0 ].v = 1.0
utime.sleep( 0.1 )
leds[ 0 ].v = 0.0
utime.sleep( 0.1 )
count = 0
while True:
v = adc.read()
# leds[ count % led_c.CHANNELS ].v = v * v
led_c.pwm( [ v ] * led_c.CHANNELS )
led_d.pwm( [ v ] * led_d.CHANNELS )
count += 1
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment