From c2f614d15a6dae47ed9e0b7277b43680c2b14067 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 16:23:40 +0100 Subject: [PATCH 01/83] Ignore PyCharm config files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2c49db743..b0494d9d6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *~ Hue_Controller/secrets.h +.idea From 269f23833d2b981b960dce13978a6bb03df01c0e Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 16:39:20 +0100 Subject: [PATCH 02/83] Format ufo --- ufo/ufo.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/ufo/ufo.py b/ufo/ufo.py index ef697fb91..ade775333 100644 --- a/ufo/ufo.py +++ b/ufo/ufo.py @@ -3,14 +3,16 @@ # Plays UFO lights and sounds if the board is upside down only, # Tilt to change light color, cycle speed, tone pitch -from adafruit_circuitplayground.express import cpx -import neopixel -import board import time -#create neopixel object. set brightness lower if needed, say .2 +import board +import neopixel +from adafruit_circuitplayground.express import cpx + +# create neopixel object. set brightness lower if needed, say .2 pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.8) + def simpleCircle(wait, R, G, B): # timing, color values per channel baseFreq = int(20 + (G * 0.3)) # tone value derived from rotation @@ -23,6 +25,7 @@ def simpleCircle(wait, R, G, B): # timing, color values per channel pixels[i] = ((R, G, B)) time.sleep(wait) + # Main loop gets x, y and z axis acceleration, prints the values, and turns on # lights if the UFO is upside down, plays tones while True: From 8357190e7d3685a5a16b8ab1e63c259d3ba6afef Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 16:39:34 +0100 Subject: [PATCH 03/83] Format Trinket Ultrasonic Rangefinder --- .../Trinket_Ultrasonic_Rangefinder.py | 101 ++++++++++-------- 1 file changed, 56 insertions(+), 45 deletions(-) diff --git a/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py b/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py index 667e7aa15..04f98e357 100644 --- a/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py +++ b/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py @@ -15,13 +15,14 @@ # * LV-EZ1 Ultrasonic Sensor PW pin to Trinket GPIO #1 # * Backlight can be hard wired by connecting LCD pin 16, 17 or 18 to GND +import time + +import adafruit_character_lcd import board import busio -import time import pulseio -import adafruit_character_lcd -ez1pin = board.D1 # Trinket GPIO #1 +ez1pin = board.D1 # Trinket GPIO #1 # i2c LCD initialize bus and class i2c = busio.I2C(board.SCL, board.SDA) @@ -30,12 +31,12 @@ rows = 2 lcd = adafruit_character_lcd.Character_LCD_I2C(i2c, cols, rows) # calculated mode or median distance -mode_result = 0 +mode_result = 0 # pulseio can store multiple pulses # read in time for pin to transition samples = 18 -pulses = pulseio.PulseIn(board.D1, maxlen=samples) +pulses = pulseio.PulseIn(board.D1, maxlen=samples) # sensor reads which are in range will be stored here rangevalue = [0, 0, 0, 0, 0, 0, 0, 0, 0] @@ -43,79 +44,89 @@ rangevalue = [0, 0, 0, 0, 0, 0, 0, 0, 0] # 25ms sensor power up pause time.sleep(.25) -# EZ1 ultrasonic sensor is measuring "time of flight" -# * convert time of flight into distance -# * centimeters (divide by 58mS) -# * inches (divide by 147mS) -# * centimeter is default output, flip comments for inches -def tof_to_distance(tof): -# convert_to_inches = 147 - convert_to_cm = 58 -# inches = tof / convert_to_inches +def tof_cm(tof): + """ + EZ1 ultrasonic sensor is measuring "time of flight" + Converts time of flight into distance in centimeters + """ + convert_to_cm = 58 cm = tof / convert_to_cm -# return inches return cm -# find the mode (most common value reported) -# will return median (center of sorted list) -# should mode not be found -def mode(x, n): - maxcount = 0 +def tof_inches(tof): + """ + EZ1 ultrasonic sensor is measuring "time of flight" + Converts time of flight into distance in inches + """ + convert_to_inches = 147 + inches = tof / convert_to_inches + + return inches + + +def find_mode(x): + """ + find the mode (most common value reported) + will return median (center of sorted list) + should mode not be found + """ + n = len(x) + + max_count = 0 mode = 0 bimodal = 0 - prevcount = 0 counter = 0 - i = 0 + index = 0 - while ( i < ( n - 1 ) ): - prevcount = counter + while index < (n - 1): + prev_count = counter counter = 0 - while ( ( x[i] ) == ( x[i+1] ) ): + while (x[index]) == (x[index + 1]): counter += 1 - i += 1 + index += 1 - if ( ( counter > prevcount ) and ( counter > maxcount ) ): - mode = x[i] - maxcount = counter + if (counter > prev_count) and (counter > max_count): + mode = x[index] + max_count = counter bimodal = 0 - if ( counter == 0 ): - i += 1 + if counter == 0: + index += 1 # If the dataset has 2 or more modes. - if ( counter == maxcount ): + if counter == max_count: bimodal = 1 # Return the median if there is no mode. - if ( ( mode == 0 ) or ( bimodal == 1 ) ): - mode = x [ int ( n / 2 ) ] + if (mode == 0) or (bimodal == 1): + mode = x[int(n / 2)] return mode + while True: # wait between samples time.sleep(.5) - if ( len(pulses) == samples ): - j = 0 # rangevalue array counter + if len(pulses) == samples: + j = 0 # rangevalue array counter # only save the values within range # range readings take 49mS # pulse width is .88mS to 37.5mS - for i in range( 0, samples ): - tof = pulses[i] # time of flight - PWM HIGH + for i in range(0, samples): + tof = pulses[i] # time of flight - PWM HIGH - if ( ( tof > 880 ) and ( tof < 37500 ) ): - if ( j < len(rangevalue) ): - rangevalue[j] = tof_to_distance(tof) + if 880 < tof < 37500: + if j < len(rangevalue): + rangevalue[j] = tof_cm(tof) j += 1 - # clear pulse samples pulses.clear() # clear all values in pulses[] @@ -123,10 +134,10 @@ while True: rangevalue = sorted(rangevalue) # returns mode or median - mode_result = int(mode(rangevalue, len(rangevalue))) + mode_result = int(find_mode(rangevalue)) # python console prints both centimeter and inches distance - cm2in = .393701 + cm2in = .393701 mode_result_in = mode_result * cm2in print(mode_result, "cm", "\t\t", int(mode_result_in), "in") @@ -138,5 +149,5 @@ while True: lcd.message(" ") lcd.message(digit_string) lcd.message("cm") - + time.sleep(2) From e4d795dfa7fac4e67c9ada21bb6e5d5e9dc1bfab Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 16:42:19 +0100 Subject: [PATCH 04/83] Format Gemma Space Invader Pendant --- .../Trinket_Gemma_Space_Invader_Pendant.py | 144 +++++++++--------- 1 file changed, 72 insertions(+), 72 deletions(-) diff --git a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py index d6ff31498..13a02f8cd 100644 --- a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py +++ b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py @@ -1,7 +1,8 @@ -import board import time + +import adafruit_ht16k33.matrix +import board import busio as io -import adafruit_ht16k33.matrix import touchio touch = touchio.TouchIn(board.D1) @@ -11,13 +12,13 @@ matrix = adafruit_ht16k33.matrix.Matrix8x8(i2c) # pixels initializers xpix = ypix = 8 -x = y = 0 +x = y = 0 matrix.fill(0) matrix.show() # seconds to pause between frames -frame_delay = [ .25,.25,.25,.25,.25,.25,.25,.25,.25,.25,.25,.25, - .125,.125,.125,.125,.125,.125,.125,.125,.125 ] +frame_delay = [.25, .25, .25, .25, .25, .25, .25, .25, .25, .25, .25, .25, + .125, .125, .125, .125, .125, .125, .125, .125, .125] # counter for animation frames frame_count = 0 @@ -25,99 +26,98 @@ frame_count = 0 # animation bitmaps anim = [ # frame 0 - alien #1 frame 1 - [ [0,0,0,1,1,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,0,1,0,0,1,0,0], - [0,1,0,1,1,0,1,0], [1,0,1,0,0,1,0,1] ], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1]], # frame 1 - alien #1 frame 2 - [ [0,0,0,1,1,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,0,1,0,0,1,0,0], - [0,1,0,1,1,0,1,0], [0,1,0,0,0,0,1,0] ], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 2 - alien #1 frame 1 (duplicate frame 1) - [ [0,0,0,1,1,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,0,1,0,0,1,0,0], - [0,1,0,1,1,0,1,0], [1,0,1,0,0,1,0,1] ], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1]], # frame 3 - alien #1 frame 2 (duplicate frame 2) - [ [0,0,0,1,1,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,0,1,0,0,1,0,0], - [0,1,0,1,1,0,1,0], [0,1,0,0,0,0,1,0] ], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 4 - alien #2 frame 1 - [ [0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,0,1,1,0,1,1], [0,1,1,1,1,1,1,0], - [0,0,1,0,0,1,0,0], [1,1,0,0,0,0,1,1] ], + [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1]], # frame 5 - alien #2 frame 2 - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,1,0,1,1,0,1,1], - [1,1,0,1,1,0,1,1], [0,1,1,1,1,1,1,0], [0,0,1,0,0,1,0,0], - [0,0,1,0,0,1,0,0], [0,0,1,0,0,1,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 6 - alien #2 frame 1 (duplicate frame 5) - [ [0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,0,1,1,0,1,1], [0,1,1,1,1,1,1,0], - [0,0,1,0,0,1,0,0], [1,1,0,0,0,0,1,1] ], + [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1]], # frame 7 - alien #2 frame 2 (duplicate frame 6) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,1,0,1,1,0,1,1], - [1,1,0,1,1,0,1,1], [0,1,1,1,1,1,1,0], [0,0,1,0,0,1,0,0], - [0,0,1,0,0,1,0,0], [0,0,1,0,0,1,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 8 - alien #3 first frame - [ [0,0,1,0,0,1,0,0], [0,0,1,0,0,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1], - [1,0,1,0,0,1,0,1], [0,0,1,0,0,1,0,0] ], + [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 9 - alien #3 second frame - [ [0,0,1,0,0,1,0,0], [1,0,1,0,0,1,0,1], [1,1,1,1,1,1,1,1], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,1,1,1,1,1,1,0], - [0,0,1,0,0,1,0,0], [0,1,0,0,0,0,1,0] ], + [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 10 - alien #3 first frame (duplicate frame 9) - [ [0,0,1,0,0,1,0,0], [0,0,1,0,0,1,0,0], [0,1,1,1,1,1,1,0], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1], - [1,0,1,0,0,1,0,1], [0,0,1,0,0,1,0,0] ], + [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 11 - alien #3 second frame (duplicate frame 10) - [ [0,0,1,0,0,1,0,0], [1,0,1,0,0,1,0,1], [1,1,1,1,1,1,1,1], - [1,1,0,1,1,0,1,1], [1,1,1,1,1,1,1,1], [0,1,1,1,1,1,1,0], - [0,0,1,0,0,1,0,0], [0,1,0,0,0,0,1,0] ], + [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 12 - alien #4 first frame - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [0,0,1,1,0,0,1,1], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,1,0,0,0], [0,0,0,0,0,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 13 - alien #4 second frame - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,0,0,1,1,0,0,1], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,1,0,0,0], [0,0,0,0,1,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 14 - alien #4 third frame (not a repeat) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,1,0,0,1,1,0,0], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], [0,0,0,0,1,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 15 - alien #4 fourth frame (not a repeat) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [0,1,1,0,0,1,1,0], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 16 - alien #4 first frame (duplicate frame 12) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [0,0,1,1,0,0,1,1], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,1,0,0,0], [0,0,0,0,0,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 17 - alien #4 second frame (duplicate frame 13) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,0,0,1,1,0,0,1], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,1,0,0,0], [0,0,0,0,1,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 18 - alien #4 second frame (duplicate frame 14) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [1,1,0,0,1,1,0,0], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], [0,0,0,0,1,0,0,0] ], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 19 - alien #4 second frame (duplicate frame 15) - [ [0,0,1,1,1,1,0,0], [0,1,1,1,1,1,1,0], [0,1,1,0,0,1,1,0], - [0,1,1,1,1,1,1,0], [0,0,1,1,1,1,0,0], [0,0,0,0,0,0,0,0], - [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0] ] - ] - + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] +] # # run until we are out of animation frames # use Gemma's built-in reset button or switch to restart # # populate matrix -while True: +while True: - if ( frame_count < len(anim) ): + if frame_count < len(anim): for x in range(xpix): - for y in range (ypix): - matrix.pixel(x,y,anim[frame_count][x][y]) + for y in range(ypix): + matrix.pixel(x, y, anim[frame_count][x][y]) # next animation frame frame_count += 1 @@ -136,5 +136,5 @@ while True: # A0/D1 pin has been touched # reset animation - if ( touch.value ): + if touch.value: frame_count = 0 From 707fa4ff243464ffafb4039e26b46295ac94e732 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 16:46:56 +0100 Subject: [PATCH 05/83] Format Trinket Gemma Servo Control --- .../Trinket_Gemma_Servo_Control.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py b/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py index cfdb0bc29..086c8d32b 100644 --- a/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py +++ b/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py @@ -1,7 +1,6 @@ -import time import board -from analogio import AnalogIn import simpleio +from analogio import AnalogIn # servo pin for the M0 boards: servo = simpleio.Servo(board.A2) @@ -10,19 +9,21 @@ angle = 0 # potentiometer trimpot = AnalogIn(board.A1) # pot pin for servo control -def remapRange(value, leftMin, leftMax, rightMin, rightMax): + +def remap_range(value, left_min, left_max, right_min, right_max): # this remaps a value from original (left) range to new (right) range # Figure out how 'wide' each range is - leftSpan = leftMax - leftMin - rightSpan = rightMax - rightMin + left_span = left_max - left_min + right_span = right_max - right_min # Convert the left range into a 0-1 range (int) - valueScaled = int(value - leftMin) / int(leftSpan) + value_scaled = int(value - left_min) / int(left_span) # Convert the 0-1 range into a value in the right range. - return int(rightMin + (valueScaled * rightSpan)) + return int(right_min + (value_scaled * right_span)) + while True: - angle = remapRange(trimpot.value, 0, 65535, 0, 180) + angle = remap_range(trimpot.value, 0, 65535, 0, 180) servo.angle = angle - #time.sleep(0.05) + # time.sleep(0.05) From 4bc3226be12b3e9bbf0829deb8462e3807bf1992 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:03:40 +0100 Subject: [PATCH 06/83] Fix pylint issues --- ufo/ufo.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/ufo/ufo.py b/ufo/ufo.py index ade775333..d5fa1ec56 100644 --- a/ufo/ufo.py +++ b/ufo/ufo.py @@ -1,7 +1,9 @@ -# UFO Flying Saucer with Circuit Playground Express -# https://learn.adafruit.com/ufo-circuit-playground-express/ -# Plays UFO lights and sounds if the board is upside down only, -# Tilt to change light color, cycle speed, tone pitch +""" +UFO Flying Saucer with Circuit Playground Express +https://learn.adafruit.com/ufo-circuit-playground-express/ +Plays UFO lights and sounds if the board is upside down only, +Tilt to change light color, cycle speed, tone pitch +""" import time @@ -13,8 +15,9 @@ from adafruit_circuitplayground.express import cpx pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.8) -def simpleCircle(wait, R, G, B): # timing, color values per channel - baseFreq = int(20 + (G * 0.3)) # tone value derived from rotation +def simple_circle(wait, red, green, blue): + """timing, color values per channel""" + baseFreq = int(20 + (green * 0.3)) # tone value derived from rotation for i in range(10): pixels[i] = ((0, 0, 0)) @@ -22,7 +25,7 @@ def simpleCircle(wait, R, G, B): # timing, color values per channel time.sleep(wait) for i in range(10): - pixels[i] = ((R, G, B)) + pixels[i] = ((red, green, blue)) time.sleep(wait) @@ -41,7 +44,7 @@ while True: # check for upside down state on z axis if z < 0: # any negative number on z axis means it's upside down enough speed = (0.01 * (B * 0.025)) - simpleCircle(speed, R, G, B) # speed based on tilt, .01 is good start + simple_circle(speed, R, G, B) # speed based on tilt, .01 is good start else: # right side up means no colors or sound! pixels.fill((0, 0, 0)) From 46f0b6f7ed2f6a34331c1d498740a15ce8ac9062 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:07:40 +0100 Subject: [PATCH 07/83] Format for PyLint --- .../Trinket_Ultrasonic_Rangefinder.py | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py b/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py index 04f98e357..ba801063d 100644 --- a/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py +++ b/Trinket_Ultrasonic_Rangefinder/Trinket_Ultrasonic_Rangefinder.py @@ -1,19 +1,21 @@ -# This Code uses the: -# * Adafruit LCD backpack using MCP23008 I2C expander -# * Maxbotic LV-EZ1 Ultrasonic Sensor -# -# Tested with the Trinket M0 -# The ultrasonic sensor and pin use should be Gemma M0 compatible -# This sketch reads the LV-EZ1 by pulse count -# Then prints the distance to the LCD and python console -# -# The circuit: -# * 5V to Trinket M0 USB or BAT pin, I2C Backpack 5V and EZ1 +5 -# * GND to Trinket M0 GND pin, I2C Backpack GND and EZ1 GND -# * Display I2C Backpack SLK to Trinket GPIO #2 -# * Display I2C backpack SDA to Trinket GPIO #0 -# * LV-EZ1 Ultrasonic Sensor PW pin to Trinket GPIO #1 -# * Backlight can be hard wired by connecting LCD pin 16, 17 or 18 to GND +""" +This Code uses the: +* Adafruit LCD backpack using MCP23008 I2C expander +* Maxbotic LV-EZ1 Ultrasonic Sensor + +Tested with the Trinket M0 +The ultrasonic sensor and pin use should be Gemma M0 compatible +This sketch reads the LV-EZ1 by pulse count +Then prints the distance to the LCD and python console + +The circuit: +* 5V to Trinket M0 USB or BAT pin, I2C Backpack 5V and EZ1 +5 +* GND to Trinket M0 GND pin, I2C Backpack GND and EZ1 GND +* Display I2C Backpack SLK to Trinket GPIO #2 +* Display I2C backpack SDA to Trinket GPIO #0 +* LV-EZ1 Ultrasonic Sensor PW pin to Trinket GPIO #1 +* Backlight can be hard wired by connecting LCD pin 16, 17 or 18 to GND +""" import time @@ -33,7 +35,7 @@ lcd = adafruit_character_lcd.Character_LCD_I2C(i2c, cols, rows) # calculated mode or median distance mode_result = 0 -# pulseio can store multiple pulses +# pulseio can store multiple pulses # read in time for pin to transition samples = 18 pulses = pulseio.PulseIn(board.D1, maxlen=samples) @@ -45,24 +47,24 @@ rangevalue = [0, 0, 0, 0, 0, 0, 0, 0, 0] time.sleep(.25) -def tof_cm(tof): +def tof_cm(time_of_flight): """ EZ1 ultrasonic sensor is measuring "time of flight" Converts time of flight into distance in centimeters """ convert_to_cm = 58 - cm = tof / convert_to_cm + cm = time_of_flight / convert_to_cm return cm -def tof_inches(tof): +def tof_inches(time_of_flight): """ EZ1 ultrasonic sensor is measuring "time of flight" Converts time of flight into distance in inches """ convert_to_inches = 147 - inches = tof / convert_to_inches + inches = time_of_flight / convert_to_inches return inches From cb45ddce17a2f341c9d63a591a34521dc84fe119 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:09:14 +0100 Subject: [PATCH 08/83] Format Space Invader Pendant for PyLint --- .../Trinket_Gemma_Space_Invader_Pendant.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py index 13a02f8cd..b590aa5fa 100644 --- a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py +++ b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py @@ -10,8 +10,8 @@ touch = touchio.TouchIn(board.D1) i2c = io.I2C(board.SCL, board.SDA) matrix = adafruit_ht16k33.matrix.Matrix8x8(i2c) -# pixels initializers -xpix = ypix = 8 +# pixels initializers +x_pix = y_pix = 8 x = y = 0 matrix.fill(0) matrix.show() @@ -24,7 +24,7 @@ frame_delay = [.25, .25, .25, .25, .25, .25, .25, .25, .25, .25, .25, .25, frame_count = 0 # animation bitmaps -anim = [ +animation = [ # frame 0 - alien #1 frame 1 [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], @@ -114,10 +114,10 @@ anim = [ # populate matrix while True: - if frame_count < len(anim): - for x in range(xpix): - for y in range(ypix): - matrix.pixel(x, y, anim[frame_count][x][y]) + if frame_count < len(animation): + for x in range(x_pix): + for y in range(y_pix): + matrix.pixel(x, y, animation[frame_count][x][y]) # next animation frame frame_count += 1 From b126b1ad054ef4a7765b7a0af81798fd1341f2a2 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:11:01 +0100 Subject: [PATCH 09/83] Remove trailing whitespace --- Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py b/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py index 086c8d32b..522c095d6 100644 --- a/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py +++ b/Trinket_Gemma_Servo_Control/Trinket_Gemma_Servo_Control.py @@ -6,7 +6,7 @@ from analogio import AnalogIn servo = simpleio.Servo(board.A2) angle = 0 -# potentiometer +# potentiometer trimpot = AnalogIn(board.A1) # pot pin for servo control From 566e629611e021597cbc6c659e1505c714e4dac8 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:14:55 +0100 Subject: [PATCH 10/83] Format Mini Theramin --- .../Trinket_Gemma_Mini_Theramin.py | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Trinket_Gemma_Mini_Theramin/Trinket_Gemma_Mini_Theramin.py b/Trinket_Gemma_Mini_Theramin/Trinket_Gemma_Mini_Theramin.py index d270e9459..2d71138e5 100644 --- a/Trinket_Gemma_Mini_Theramin/Trinket_Gemma_Mini_Theramin.py +++ b/Trinket_Gemma_Mini_Theramin/Trinket_Gemma_Mini_Theramin.py @@ -1,27 +1,30 @@ -# Adafruit Trinket/Gemma Example: Simple Theramin -# Read the voltage from a Cadmium Sulfide (CdS) photocell voltage -# divider and output a corresponding tone to a piezo buzzer -# -# Photocell voltage divider center wire to GPIO #2 (analog 1) -# and output tone to GPIO #0 (digital 0) +""" +Adafruit Trinket/Gemma Example: Simple Theramin +Read the voltage from a Cadmium Sulfide (CdS) photocell voltage +divider and output a corresponding tone to a piezo buzzer + +Photocell voltage divider center wire to GPIO #2 (analog 1) +and output tone to GPIO #0 (digital 0) +""" -import board -import pulseio -import analogio import time +import analogio +import board +import pulseio + photocell_pin = board.A1 # CdS photocell connected to this ANALOG pin -speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin -scale = 0.03 # Change this to adjust tone scale +speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin +scale = 0.03 # Change this to adjust tone scale # Initialize input/output pins photocell = analogio.AnalogIn(photocell_pin) -pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0) +pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0) while True: # Loop forever... - # Read photocell analog pin and convert voltage to frequency - pwm.frequency = 220 + int(scale * float(photocell.value)) - pwm.duty_cycle = 32767 # 50% duty cycle - time.sleep(0.4) # Play for 400 ms (adjust to your liking) - pwm.duty_cycle = 0 # Stop playing - time.sleep(0.05) # Delay 50 ms between notes (also adjustable) + # Read photocell analog pin and convert voltage to frequency + pwm.frequency = 220 + int(scale * float(photocell.value)) + pwm.duty_cycle = 32767 # 50% duty cycle + time.sleep(0.4) # Play for 400 ms (adjust to your liking) + pwm.duty_cycle = 0 # Stop playing + time.sleep(0.05) # Delay 50 ms between notes (also adjustable) From e8f054d2e9c5cdcc6da360a307c3f74d76248e5d Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:38:30 +0100 Subject: [PATCH 11/83] Format IR Reader --- Trinket_Gemma_IR_Control/IR_reader.py | 31 ++--- .../Trinket_Gemma_IR_Control.py | 107 ++++++++++++------ 2 files changed, 89 insertions(+), 49 deletions(-) diff --git a/Trinket_Gemma_IR_Control/IR_reader.py b/Trinket_Gemma_IR_Control/IR_reader.py index a9df5f654..29bb9f259 100644 --- a/Trinket_Gemma_IR_Control/IR_reader.py +++ b/Trinket_Gemma_IR_Control/IR_reader.py @@ -1,9 +1,10 @@ -import board -import pulseio -import adafruit_irremote import time -IR_PIN = board.D2 # Pin connected to IR receiver. +import adafruit_irremote +import board +import pulseio + +IR_PIN = board.D2 # Pin connected to IR receiver. print('IR listener') print() @@ -22,16 +23,20 @@ while True: # Wait for a pulse to be detected. detected = decoder.read_pulses(pulses) - # print the number of pulses detected - # note: pulse count is an excellent indicator as to the quality of IR code - # received. - # - # If you are expecting 67 each time (Adafruit Mini Remote Control #389) - # and only receive 57 this will result in a incomplete list + """ + print the number of pulses detected + note: pulse count is an excellent indicator as to the quality of IR code + received. + + If you are expecting 67 each time (Adafruit Mini Remote Control #389) + and only receive 57 this will result in a incomplete listener + """ print("pulse count: ", len(detected)) - # print in list form of the pulse duration in microseconds - # typically starts with ~9,000 microseconds followed by a ~4,000 microseconds - # which is standard IR preamble + """ + print in list form of the pulse duration in microseconds + typically starts with ~9,000 microseconds followed by a ~4,000 microseconds + which is standard IR preamble + """ print(detected) print() diff --git a/Trinket_Gemma_IR_Control/Trinket_Gemma_IR_Control.py b/Trinket_Gemma_IR_Control/Trinket_Gemma_IR_Control.py index b2b844b70..676935f95 100644 --- a/Trinket_Gemma_IR_Control/Trinket_Gemma_IR_Control.py +++ b/Trinket_Gemma_IR_Control/Trinket_Gemma_IR_Control.py @@ -1,60 +1,96 @@ +""" +IR codes for button 0, 1, 2, 3 these were acquired from the +Adafruit Mini Remote Control #389 +https://www.adafruit.com/product/389 +stored as a 2D list +these codes were collected from running IR_reader.py +and watching the output on the REPL console +""" + +import time + +import adafruit_irremote import board import pulseio -import time -import adafruit_irremote import simpleio speaker_pin = board.D0 # speaker connected to digital pin -ir_pin = board.D2 # pin connected to IR receiver. +ir_pin = board.D2 # pin connected to IR receiver. -fuzzyness = 0.2 # IR remote timing must be within 20% tolerance +fuzzyness = 0.2 # IR remote timing must be within 20% tolerance -# IR codes for button 0, 1, 2, 3 these were acquired from the -# Adafruit Mini Remote Control #389 -# https://www.adafruit.com/product/389 -# stored as a 2D list -# these codes were collected from running IR_reader.py -# and watching the output on the REPL console -button_press = [ +button_presses = [ -[9073, 4504, 575, 589, 557, 581, 546, 592, 553, 585, 542, 595, 550, 588, 552, 588, 544, 591, 549, 1671, 579, 1669, 572, 1675, 577, 1671, 570, 1678, 574, 1673, 579, 559, 572, 1676, 575, 589, 542, 596, 546, 1674, 577, 1671, 571, 567, 574, 590, 552, 586, 545, 593, 548, 1672, 569, 1678, 574, 591, 550, 588, 550, 1670, 575, 1673, 579, 1671, 570, 1675, 586], + [ + 9073, 4504, 575, 589, 557, 581, 546, 592, 553, 585, 542, 595, + 550, 588, 552, 588, 544, 591, 549, 1671, 579, 1669, 572, 1675, + 577, 1671, 570, 1678, 574, 1673, 579, 559, 572, 1676, 575, 589, + 542, 596, 546, 1674, 577, 1671, 571, 567, 574, 590, 552, 586, + 545, 593, 548, 1672, 569, 1678, 574, 591, 550, 588, 550, 1670, + 575, 1673, 579, 1671, 570, 1675, 586 + ], -[9075, 4498, 571, 566, 575, 562, 569, 569, 573, 564, 577, 587, 544, 567, 577, 587, 551, 586, 545, 1675, 577, 1671, 575, 1672, 574, 1674, 580, 1668, 572, 1675, 576, 589, 542, 1678, 574, 564, 577, 588, 543, 594, 547, 591, 551, 1669, 572, 592, 553, 585, 542, 595, 550, 1671, 577, 1670, 571, 1677, 575, 1673, 569, 576, 565, 1675, 577, 1670, 572, 1676, 575], + [ + 9075, 4498, 571, 566, 575, 562, 569, 569, 573, 564, 577, 587, 544, + 567, 577, 587, 551, 586, 545, 1675, 577, 1671, 575, 1672, 574, 1674, + 580, 1668, 572, 1675, 576, 589, 542, 1678, 574, 564, 577, 588, 543, + 594, 547, 591, 551, 1669, 572, 592, 553, 585, 542, 595, 550, 1671, + 577, 1670, 571, 1677, 575, 1673, 569, 576, 565, 1675, 577, 1670, 572, + 1676, 575 + ], -[9070, 4505, 574, 563, 578, 559, 572, 566, 575, 562, 569, 569, 573, 564, 577, 561, 570, 567, 575, 1674, 578, 1669, 577, 1670, 577, 1670, 571, 1677, 575, 1672, 569, 569, 573, 1674, 577, 1671, 571, 566, 575, 562, 569, 575, 566, 1675, 577, 560, 571, 567, 574, 563, 568, 569, 573, 1675, 576, 1671, 571, 1681, 571, 562, 569, 1679, 575, 1672, 578, 1670, 570], + [ + 9070, 4505, 574, 563, 578, 559, 572, 566, 575, 562, 569, 569, 573, 564, + 577, 561, 570, 567, 575, 1674, 578, 1669, 577, 1670, 577, 1670, 571, + 1677, 575, 1672, 569, 569, 573, 1674, 577, 1671, 571, 566, 575, 562, + 569, 575, 566, 1675, 577, 560, 571, 567, 574, 563, 568, 569, 573, 1675, + 576, 1671, 571, 1681, 571, 562, 569, 1679, 575, 1672, 578, 1670, 570 + ], -[9080, 4500, 569, 568, 573, 564, 577, 561, 570, 567, 574, 564, 578, 559, 577, 561, 575, 562, 579, 1669, 572, 1675, 577, 1671, 570, 1677, 575, 1673, 578, 1672, 570, 570, 571, 1671, 574, 564, 574, 1678, 573, 560, 571, 568, 574, 1671, 570, 568, 573, 564, 577, 561, 570, 1677, 575, 563, 578, 1669, 572, 1676, 576, 561, 570, 1677, 574, 1674, 578, 1669, 572] + [ + 9080, 4500, 569, 568, 573, 564, 577, 561, 570, 567, 574, 564, 578, 559, + 577, 561, 575, 562, 579, 1669, 572, 1675, 577, 1671, 570, 1677, 575, + 1673, 578, 1672, 570, 570, 571, 1671, 574, 564, 574, 1678, 573, 560, + 571, 568, 574, 1671, 570, 568, 573, 564, 577, 561, 570, 1677, 575, 563, + 578, 1669, 572, 1676, 576, 561, 570, 1677, 574, 1674, 578, 1669, 572 + ] ] + def fuzzy_pulse_compare(received): # Did we receive a full IR code? # Should be 67 timings for this remote - if ( len(received) == len(button_press[0]) ): + if len(received) == len(button_presses[0]): - # compare received IR code with our stored button_press list + # compare received IR code with our stored button_press list # remote control button codes for : [0-3] - for b in range(len(button_press)): + for b_index, button_press in enumerate(button_presses): # compare individual timings for each IR code # confirm that every entry is within fuzzyness 20% accuracy - for i in range(len(button_press[b])): + for i, press in enumerate(button_press): - threshold = int(button_press[b][i] * fuzzyness) + threshold = int(press * fuzzyness) + + if abs(press - received[i]) < threshold: + match_count[b_index] += 1 - if ( abs(button_press[b][i] - received[i]) < threshold ): - match_count[b] += 1 -# half second tones based on button selection [0-3] def play_tone(): - if ( remote_control_press == 0 ): - simpleio.tone(speaker_pin, 400, .5) # 400Hz beep, 1/2 sec - elif ( remote_control_press == 1 ): - simpleio.tone(speaker_pin, 500, .5) # 500Hz beep, 1/2 sec - elif ( remote_control_press == 2 ): - simpleio.tone(speaker_pin, 600, .5) # 600Hz beep, 1/2 sec - elif ( remote_control_press == 3 ): - simpleio.tone(speaker_pin, 700, .5) # 700Hz beep, 1/2 sec + """ half second tones based on button selection [0-3] """ + if remote_control_press == 0: + simpleio.tone(speaker_pin, 400, .5) # 400Hz beep, 1/2 sec + + elif remote_control_press == 1: + simpleio.tone(speaker_pin, 500, .5) # 500Hz beep, 1/2 sec + + elif remote_control_press == 2: + simpleio.tone(speaker_pin, 600, .5) # 600Hz beep, 1/2 sec + + elif remote_control_press == 3: + simpleio.tone(speaker_pin, 700, .5) # 700Hz beep, 1/2 sec + # Create pulse input and IR decoder. pulses = pulseio.PulseIn(ir_pin, maxlen=200, idle_state=True) @@ -63,7 +99,7 @@ decoder = adafruit_irremote.GenericDecode() # Loop waiting to receive pulses. while True: # total count of IR code matches for each button {0, 1, 2, 3} - match_count = [0] * len(button_press) + match_count = [0] * len(button_presses) # make sure pulses is empty pulses.clear() @@ -72,17 +108,16 @@ while True: # Wait for a pulse to be detected. detected = decoder.read_pulses(pulses) - + fuzzy_pulse_compare(detected) # confirm that we know this button - # received IR code compared with saved button_presses + # received IR code compared with saved button_presses # 100% match (+/- fuzziness) # otherwise we don't know this button pressed - if ( max(match_count) == len(button_press[0]) ): + if max(match_count) == len(button_presses[0]): remote_control_press = match_count.index(max(match_count)) play_tone() print(match_count.index(max(match_count))) else: print("unknown button") - From d5829fdee4e9d9bf5d8ccd82d5c70fe993cf5e64 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:48:53 +0100 Subject: [PATCH 12/83] Format IR Reader --- Trinket_Gemma_IR_Control/IR_reader.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Trinket_Gemma_IR_Control/IR_reader.py b/Trinket_Gemma_IR_Control/IR_reader.py index 29bb9f259..f81fa7782 100644 --- a/Trinket_Gemma_IR_Control/IR_reader.py +++ b/Trinket_Gemma_IR_Control/IR_reader.py @@ -23,20 +23,18 @@ while True: # Wait for a pulse to be detected. detected = decoder.read_pulses(pulses) - """ - print the number of pulses detected - note: pulse count is an excellent indicator as to the quality of IR code - received. + # print the number of pulses detected + # note: pulse count is an excellent indicator as to the quality of IR code + # received. + # + # If you are expecting 67 each time (Adafruit Mini Remote Control #389) + # and only receive 57 this will result in a incomplete listener - If you are expecting 67 each time (Adafruit Mini Remote Control #389) - and only receive 57 this will result in a incomplete listener - """ print("pulse count: ", len(detected)) - """ - print in list form of the pulse duration in microseconds - typically starts with ~9,000 microseconds followed by a ~4,000 microseconds - which is standard IR preamble - """ + # print in list form of the pulse duration in microseconds + # typically starts with ~9,000 microseconds followed by a ~4,000 microseconds + # which is standard IR preamble + print(detected) print() From 42fc4881f3b8fdc56e54efc758c442918e166b38 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 17:55:50 +0100 Subject: [PATCH 13/83] Format Blinky Eyes --- .../Trinket_Gemma_Blinky_Eyes.py | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Trinket_Gemma_Blinky_Eyes/Trinket_Gemma_Blinky_Eyes.py b/Trinket_Gemma_Blinky_Eyes/Trinket_Gemma_Blinky_Eyes.py index 61a564e3c..6e90423b5 100644 --- a/Trinket_Gemma_Blinky_Eyes/Trinket_Gemma_Blinky_Eyes.py +++ b/Trinket_Gemma_Blinky_Eyes/Trinket_Gemma_Blinky_Eyes.py @@ -1,11 +1,12 @@ -# Name: Blinking Eyes - based on code by Brad Blumenthal, MAKE Magazine -# License: GPLv3 -# 2013 - Adafruit Learning System - Modified for 8 MHz ATTiny85 and low light photocell -# 2018 - Adafruit Learning System - Modified for Gemma M0 and Circuit Python +""" +Blinking Eyes - based on code by Brad Blumenthal, MAKE Magazine +License: GPLv3 +""" -import board -import analogio import time + +import analogio +import board import pulseio try: @@ -14,18 +15,18 @@ except ImportError: import random # Initialize photocell -photocell_pin = board.A1 # cds photocell connected to this ANALOG pin -darkness_max = (2**16 / 2) # more dark than light > 32k out of 64k +photocell_pin = board.A1 # cds photocell connected to this ANALOG pin +darkness_max = (2 ** 16 / 2) # more dark than light > 32k out of 64k photocell = analogio.AnalogIn(photocell_pin) # Initialize PWM -# PWM (fading) - Both LEDs are connected on D0 +# PWM (fading) - Both LEDs are connected on D0 # (PWM not avail on D1) pwm_leds = board.D0 pwm = pulseio.PWMOut(pwm_leds, frequency=1000, duty_cycle=0) -brightness = 0 # how bright the LED is -fade_amount = 1285 # 2% steping of 2^16 -counter = 0 # counter to keep track of cycles +brightness = 0 # how bright the LED is +fade_amount = 1285 # 2% steping of 2^16 +counter = 0 # counter to keep track of cycles # blink delay blink_delay = True @@ -33,19 +34,19 @@ blink_freq_min = 3 blink_freq_max = 6 # Loop forever... -while True: +while True: # turn on LEDs if it is dark out - if ( photocell.value < darkness_max ): + if photocell.value < darkness_max: # blink frequency and timer - if ( blink_delay ): + if blink_delay: blink_delay = False blink_timer_start = time.monotonic() blink_freq = random.randint(blink_freq_min, blink_freq_max) # time to blink? Blink once every 3 - 6 seconds (random assingment) - if ( ( time.monotonic() - blink_timer_start ) >= blink_freq ): + if (time.monotonic() - blink_timer_start) >= blink_freq: blink_delay = True pwm.duty_cycle = 0 time.sleep(.1) @@ -57,10 +58,10 @@ while True: brightness = brightness + fade_amount # reverse the direction of the fading at the ends of the fade: - if ( brightness <= 0 ): + if brightness <= 0: fade_amount = -fade_amount counter += 1 - elif ( brightness >= 65535 ): + elif brightness >= 65535: fade_amount = -fade_amount counter += 1 From 6558031f906a6e2d8ea383b39a972550e34a4adc Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:04:33 +0100 Subject: [PATCH 14/83] Format Textile Potentiometer --- .../Textile_Potentiometer_Hoodie.py | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/Textile_Potentiometer_Hoodie/Textile_Potentiometer_Hoodie.py b/Textile_Potentiometer_Hoodie/Textile_Potentiometer_Hoodie.py index 46f6c91ec..c69ff8480 100644 --- a/Textile_Potentiometer_Hoodie/Textile_Potentiometer_Hoodie.py +++ b/Textile_Potentiometer_Hoodie/Textile_Potentiometer_Hoodie.py @@ -1,51 +1,53 @@ -import board import analogio -import time +import board import neopixel # Initialize input/output pins -sensorpin = board.A1 # input pin for the potentiometer -sensor = analogio.AnalogIn(sensorpin) +sensor_pin = board.A1 # input pin for the potentiometer +sensor = analogio.AnalogIn(sensor_pin) -pixpin = board.D1 # pin where NeoPixels are connected -numpix = 8 # number of neopixels -strip = neopixel.NeoPixel(pixpin, numpix, brightness=.15, auto_write=False) +pix_pin = board.D1 # pin where NeoPixels are connected +num_pix = 8 # number of neopixels +strip = neopixel.NeoPixel(pix_pin, num_pix, brightness=.15, auto_write=False) + +color_value = 0 +sensor_value = 0 -colorvalue = 0 -sensorvalue = 0 def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): - return (0, 0, 0) - if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) - elif (pos < 170): + return 0, 0, 0 + if pos < 85: + return int(pos * 3), int(255 - (pos * 3)), 0 + elif pos < 170: pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) - else: - pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return int(255 - pos * 3), 0, int(pos * 3) -def remapRange(value, leftMin, leftMax, rightMin, rightMax): + pos -= 170 + return 0, int(pos * 3), int(255 - pos * 3) + + +def remap_range(value, left_min, left_max, right_min, right_max): # this remaps a value from original (left) range to new (right) range # Figure out how 'wide' each range is - leftSpan = leftMax - leftMin - rightSpan = rightMax - rightMin + left_span = left_max - left_min + right_span = right_max - right_min # Convert the left range into a 0-1 range (int) - valueScaled = int(value - leftMin) / int(leftSpan) + valueScaled = int(value - left_min) / int(left_span) # Convert the 0-1 range into a value in the right range. - return int(rightMin + (valueScaled * rightSpan)) + return int(right_min + (valueScaled * right_span)) + # Loop forever... -while True: +while True: # remap the potentiometer analog sensor values from 0-65535 to RGB 0-255 - colorvalue = remapRange(sensor.value, 0, 65535, 0, 255) + color_value = remap_range(sensor.value, 0, 65535, 0, 255) - for i in range( 0, len(strip) ): - strip[i] = wheel(colorvalue) + for i in range(len(strip)): + strip[i] = wheel(color_value) strip.write() From 319c507a38bacca47502e0ab4b9ccf9983aa5d05 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:14:16 +0100 Subject: [PATCH 15/83] Format superhero power plant --- .../Superhero_Power_Plant.py | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Superhero_Power_Plant/Superhero_Power_Plant.py b/Superhero_Power_Plant/Superhero_Power_Plant.py index 62f9d9570..6f30973e1 100644 --- a/Superhero_Power_Plant/Superhero_Power_Plant.py +++ b/Superhero_Power_Plant/Superhero_Power_Plant.py @@ -1,36 +1,36 @@ import board import neopixel -import time + try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random -numpix = 17 # Number of NeoPixels -pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix) +num_pix = 17 # Number of NeoPixels +pix_pin = board.D1 # Pin where NeoPixels are connected +strip = neopixel.NeoPixel(pix_pin, num_pix) -minAlpha = 0.1 # Minimum brightness -maxAlpha = 0.4 # Maximum brightness -alpha = (minAlpha + maxAlpha) / 2 # Start in middle -alphaDelta = 0.01 # Amount to change brightness each time through loop -alphaUp = True # If True, brightness increasing, else decreasing +min_alpha = 0.1 # Minimum brightness +max_alpha = 0.4 # Maximum brightness +alpha = (min_alpha + max_alpha) / 2 # Start in middle +alpha_delta = 0.01 # Amount to change brightness each time through loop +alpha_up = True # If True, brightness increasing, else decreasing strip.fill([0, 0, 255]) # Fill blue, or change to R,G,B of your liking while True: # Loop forever... - if random.randint(1, 5) == 5: # 1-in-5 random chance - alphaUp = not alphaUp # of reversing direction - if alphaUp: # Increasing brightness? - alpha += alphaDelta # Add some amount - if alpha >= maxAlpha: # At or above max? - alpha = maxAlpha # Limit to max - alphaUp = False # and switch direction - else: # Else decreasing brightness - alpha -= alphaDelta # Subtract some amount - if alpha <= minAlpha: # At or below min? - alpha = minAlpha # Limit to min - alphaUp = True # and switch direction + if random.randint(1, 5) == 5: # 1-in-5 random chance + alpha_up = not alpha_up # of reversing direction + if alpha_up: # Increasing brightness? + alpha += alpha_delta # Add some amount + if alpha >= max_alpha: # At or above max? + alpha = max_alpha # Limit to max + alpha_up = False # and switch direction + else: # Else decreasing brightness + alpha -= alpha_delta # Subtract some amount + if alpha <= min_alpha: # At or below min? + alpha = min_alpha # Limit to min + alpha_up = True # and switch direction - strip.brightness = alpha # Set brightness to 0.0 to 1.0 - strip.write() # and issue data to LED strip + strip.brightness = alpha # Set brightness to 0.0 to 1.0 + strip.write() # and issue data to LED strip From aee8ab67d59006691648dcc9bb08bdc21aaff517 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:14:25 +0100 Subject: [PATCH 16/83] Format Theme Songs --- Spy_Theme_Songs/bond.py | 238 +++++++++++++++++++------------------- Spy_Theme_Songs/carmen.py | 168 ++++++++++++++------------- 2 files changed, 207 insertions(+), 199 deletions(-) diff --git a/Spy_Theme_Songs/bond.py b/Spy_Theme_Songs/bond.py index 605c503d7..89b4b95d6 100644 --- a/Spy_Theme_Songs/bond.py +++ b/Spy_Theme_Songs/bond.py @@ -1,10 +1,13 @@ -# Plays the 007 theme song -# Gemma M0 with Piezo on D0 and GND +""" +Plays the 007 theme song +Gemma M0 with Piezo on D0 and GND +""" -import pulseio -import board import time +import board +import pulseio + piezo = pulseio.PWMOut(board.D0, duty_cycle=0, frequency=440, variable_frequency=True) @@ -87,7 +90,7 @@ B5 = 987 C6 = C5 * 2 Cs6 = Cs5 * 2 Db6 = Db5 * 2 -D6 = D5 * 2 +D6 = D5 * 2 Ds6 = Ds5 * 2 Eb6 = Eb5 * 2 E6 = E5 * 2 @@ -104,89 +107,88 @@ B6 = B5 * 2 rst = 24000 # rest is just a tone out of normal hearing range -Bond01=[[B3, half_note], - [C4, half_note], - [Cs4, half_note], - [C4, half_note]] +Bond01 = [[B3, half_note], + [C4, half_note], + [Cs4, half_note], + [C4, half_note]] -Bond02=[[E3, eighth_note], - [Fs3, sixteenth_note], - [Fs3, sixteenth_note], - [Fs3, eighth_note], - [Fs3, eighth_note], - [Fs3, eighth_note], - [E3, eighth_note], - [E3, eighth_note], - [E3, eighth_note]] +Bond02 = [[E3, eighth_note], + [Fs3, sixteenth_note], + [Fs3, sixteenth_note], + [Fs3, eighth_note], + [Fs3, eighth_note], + [Fs3, eighth_note], + [E3, eighth_note], + [E3, eighth_note], + [E3, eighth_note]] -Bond03=[[E3, eighth_note], - [G3, sixteenth_note], - [G3, sixteenth_note], - [G3, eighth_note], - [G3, eighth_note], - [G3, eighth_note], - [Fs3, eighth_note], - [Fs3, eighth_note], - [Fs3, eighth_note]] +Bond03 = [[E3, eighth_note], + [G3, sixteenth_note], + [G3, sixteenth_note], + [G3, eighth_note], + [G3, eighth_note], + [G3, eighth_note], + [Fs3, eighth_note], + [Fs3, eighth_note], + [Fs3, eighth_note]] +Bond04 = [[E3, eighth_note], + [G3, sixteenth_note], + [G3, sixteenth_note], + [G3, eighth_note], + [G3, eighth_note], + [G3, eighth_note], + [Fs3, eighth_note], + [Fs3, eighth_note], + [E3, eighth_note]] -Bond04=[[E3, eighth_note], - [G3, sixteenth_note], - [G3, sixteenth_note], - [G3, eighth_note], - [G3, eighth_note], - [G3, eighth_note], - [Fs3, eighth_note], - [Fs3, eighth_note], - [E3, eighth_note]] +Bond05 = [[Ds4, eighth_note], + [D4, eighth_note], + [D4, half_note], + [B3, eighth_note], + [A3, eighth_note], + [B3, whole_note]] -Bond05=[[Ds4, eighth_note], - [D4, eighth_note], - [D4, half_note], - [B3, eighth_note], - [A3, eighth_note], - [B3, whole_note]] +Bond06 = [[E4, eighth_note], + [G4, quarter_note], + [Ds5, eighth_note], + [D5, quarter_note], + [D5, eighth_note], + [G4, eighth_note], + [As4, eighth_note], + [B4, eighth_note], + [B4, half_note], + [B4, quarter_note]] -Bond06=[[E4, eighth_note], - [G4, quarter_note], - [Ds5, eighth_note], - [D5, quarter_note], - [D5, eighth_note], - [G4, eighth_note], - [As4, eighth_note], - [B4, eighth_note], - [B4, half_note], - [B4, quarter_note]] +Bond07 = [[G4, quarter_note], + [A4, sixteenth_note], + [G4, sixteenth_note], + [Fs4, quarter_note], + [Fs4, eighth_note], + [B3, eighth_note], + [E4, eighth_note], + [Cs4, eighth_note], + [Cs4, whole_note]] -Bond07=[[G4, quarter_note], - [A4, sixteenth_note], - [G4, sixteenth_note], - [Fs4, quarter_note], - [Fs4, eighth_note], - [B3, eighth_note], - [E4, eighth_note], - [Cs4, eighth_note], - [Cs4, whole_note]] +Bond08 = [[G4, quarter_note], + [A4, sixteenth_note], + [G4, sixteenth_note], + [Fs4, quarter_note], + [Fs4, eighth_note], + [B3, eighth_note], + [Ds4, eighth_note], + [E4, eighth_note], + [E4, whole_note]] -Bond08=[[G4, quarter_note], - [A4, sixteenth_note], - [G4, sixteenth_note], - [Fs4, quarter_note], - [Fs4, eighth_note], - [B3, eighth_note], - [Ds4, eighth_note], - [E4, eighth_note], - [E4, whole_note]] +Bond09 = [[E4, eighth_note], + [E4, quarter_note], + [E4, eighth_note], + [Fs4, eighth_note], + [Fs4, sixteenth_note], + [E4, eighth_note], + [Fs4, quarter_note]] -Bond09=[[E4, eighth_note], - [E4, quarter_note], - [E4, eighth_note], - [Fs4, eighth_note], - [Fs4, sixteenth_note], - [E4, eighth_note], - [Fs4, quarter_note]] - -Bond10=[ +Bond10 = [ [G4, eighth_note], [G4, quarter_note], [G4, eighth_note], @@ -195,50 +197,52 @@ Bond10=[ [G4, eighth_note], [Fs4, quarter_note]] -Bond11=[[B4, eighth_note], - [B4, eighth_note], - [rst, eighth_note], - [B3, eighth_note], - [B3, quarter_note], - [B4, eighth_note], - [B4, eighth_note], - [rst, eighth_note], - [B3, eighth_note], - [B3, quarter_note], - [B4, sixteenth_note], - [B4, eighth_note], - [B4, sixteenth_note], - [B4, eighth_note], - [B4, eighth_note]] +Bond11 = [[B4, eighth_note], + [B4, eighth_note], + [rst, eighth_note], + [B3, eighth_note], + [B3, quarter_note], + [B4, eighth_note], + [B4, eighth_note], + [rst, eighth_note], + [B3, eighth_note], + [B3, quarter_note], + [B4, sixteenth_note], + [B4, eighth_note], + [B4, sixteenth_note], + [B4, eighth_note], + [B4, eighth_note]] + +Bond12 = [[E3, eighth_note], + [G3, quarter_note], + [Ds4, eighth_note], + [D4, quarter_note], + [G3, eighth_note], + [B3, quarter_note], + [Fs4, eighth_note], + [F4, quarter_note], + [B3, eighth_note], + [D4, quarter_note], + [As4, eighth_note], + [A4, quarter_note], + [F4, eighth_note], + [A4, quarter_note], + [Ds5, eighth_note], + [D5, quarter_note], + [rst, eighth_note], + [rst, quarter_note], + [Fs4, whole_note]] -Bond12=[[E3, eighth_note], - [G3, quarter_note], - [Ds4, eighth_note], - [D4, quarter_note], - [G3, eighth_note], - [B3, quarter_note], - [Fs4, eighth_note], - [F4, quarter_note], - [B3, eighth_note], - [D4, quarter_note], - [As4, eighth_note], - [A4, quarter_note], - [F4, eighth_note], - [A4, quarter_note], - [Ds5, eighth_note], - [D5, quarter_note], - [rst, eighth_note], - [rst, quarter_note], - [Fs4, whole_note]] def song_playback(song): - for n in range(len(song)): - piezo.frequency = (song[n][0]) - piezo.duty_cycle = 65536//2 # on 50% - time.sleep(song[n][1]) # note duration + for note in song: + piezo.frequency = (note[0]) + piezo.duty_cycle = 65536 // 2 # on 50% + time.sleep(note[1]) # note duration piezo.duty_cycle = 0 # off time.sleep(0.01) + # this plays the full song roadmap song_playback(Bond01) song_playback(Bond01) diff --git a/Spy_Theme_Songs/carmen.py b/Spy_Theme_Songs/carmen.py index 9c382c49c..9e2cff390 100644 --- a/Spy_Theme_Songs/carmen.py +++ b/Spy_Theme_Songs/carmen.py @@ -1,14 +1,17 @@ -# Plays the Carmen Sandiego theme song -# Gemma M0 with Piezo on D0 and GND +""" +Plays the Carmen Sandiego theme song +Gemma M0 with Piezo on D0 and GND +""" -import pulseio -import board import time +import board +import pulseio + piezo = pulseio.PWMOut(board.D0, duty_cycle=0, frequency=440, variable_frequency=True) -tempo = 1.6 +tempo = 1.6 # tempo is length of whole note in seconds, e.g. 1.5 # set up time signature whole_note = tempo # adjust this to change tempo of everything @@ -86,7 +89,7 @@ B5 = 987 C6 = C5 * 2 Cs6 = Cs5 * 2 Db6 = Db5 * 2 -D6 = D5 * 2 +D6 = D5 * 2 Ds6 = Ds5 * 2 Eb6 = Eb5 * 2 E6 = E5 * 2 @@ -103,93 +106,94 @@ B6 = B5 * 2 rst = 24000 # rest is just a tone out of normal hearing range -carmen01 =[[As4, quarter_note], - [As4, eighth_note], - [rst, eighth_note], - [rst, sixteenth_note], - [B4, eighth_note], - [rst, sixteenth_note], - [B4, eighth_note], - [B4, eighth_note]] +carmen01 = [[As4, quarter_note], + [As4, eighth_note], + [rst, eighth_note], + [rst, sixteenth_note], + [B4, eighth_note], + [rst, sixteenth_note], + [B4, eighth_note], + [B4, eighth_note]] -carmen02 =[[Gs4, quarter_note], - [Gs4, eighth_note], - [rst, eighth_note], - [rst, sixteenth_note], - [Gs4, eighth_note], - [rst, sixteenth_note], - [Gs4, eighth_note], - [B4, eighth_note]] +carmen02 = [[Gs4, quarter_note], + [Gs4, eighth_note], + [rst, eighth_note], + [rst, sixteenth_note], + [Gs4, eighth_note], + [rst, sixteenth_note], + [Gs4, eighth_note], + [B4, eighth_note]] -carmen03 =[[Gs4, quarter_note], - [Gs4, eighth_note], - [rst, eighth_note], - [rst, quarter_note], - [Cs4, eighth_note], - [Cs4, eighth_note]] +carmen03 = [[Gs4, quarter_note], + [Gs4, eighth_note], + [rst, eighth_note], + [rst, quarter_note], + [Cs4, eighth_note], + [Cs4, eighth_note]] -carmen04 =[[As4, eighth_note], - [As4, sixteenth_note], - [As4, eighth_note], - [As4, eighth_note], - [B4, sixteenth_note], - [B4, quarter_note], - [B4, eighth_note], - [B4, eighth_note]] +carmen04 = [[As4, eighth_note], + [As4, sixteenth_note], + [As4, eighth_note], + [As4, eighth_note], + [B4, sixteenth_note], + [B4, quarter_note], + [B4, eighth_note], + [B4, eighth_note]] -carmen05 =[[Gs4, eighth_note], - [Fs4, eighth_note], - [Gs4, eighth_note], - [Fs4, sixteenth_note], - [Cs5, sixteenth_note], - [Cs5, sixteenth_note], - [As4, eighth_note], - [As4, sixteenth_note], - [Fs4, eighth_note], - [Fs4, eighth_note]] +carmen05 = [[Gs4, eighth_note], + [Fs4, eighth_note], + [Gs4, eighth_note], + [Fs4, sixteenth_note], + [Cs5, sixteenth_note], + [Cs5, sixteenth_note], + [As4, eighth_note], + [As4, sixteenth_note], + [Fs4, eighth_note], + [Fs4, eighth_note]] -carmen06 =[[Gs4, eighth_note], - [Fs4, eighth_note], - [Gs4, eighth_note], - [Fs4, sixteenth_note], - [Gs4, sixteenth_note], - [Gs4, sixteenth_note], - [Gs4, eighth_note], - [rst, eighth_note], - [rst, eighth_note], - [Fs4, eighth_note]] +carmen06 = [[Gs4, eighth_note], + [Fs4, eighth_note], + [Gs4, eighth_note], + [Fs4, sixteenth_note], + [Gs4, sixteenth_note], + [Gs4, sixteenth_note], + [Gs4, eighth_note], + [rst, eighth_note], + [rst, eighth_note], + [Fs4, eighth_note]] -carmen07 =[[Gs4, eighth_note], - [Fs4, eighth_note], - [Gs4, eighth_note], - [Fs4, sixteenth_note], - [Cs5, sixteenth_note], - [Cs5, sixteenth_note], - [As4, eighth_note], - [As4, sixteenth_note], - [Gs4, eighth_note], - [Fs4, eighth_note]] +carmen07 = [[Gs4, eighth_note], + [Fs4, eighth_note], + [Gs4, eighth_note], + [Fs4, sixteenth_note], + [Cs5, sixteenth_note], + [Cs5, sixteenth_note], + [As4, eighth_note], + [As4, sixteenth_note], + [Gs4, eighth_note], + [Fs4, eighth_note]] + +carmen08 = [[Fs4, eighth_note], + [rst, eighth_note], + [Fs4, eighth_note], + [Fs4, eighth_note], + [Gs4, eighth_note], + [rst, eighth_note], + [Gs4, eighth_note], + [rst, eighth_note], + [E3, eighth_note], + [E3, eighth_note], + [E3, eighth_note], + [E3, sixteenth_note], + [Fs3, eighth_note], + [Fs3, eighth_note], + [rst, quarter_note]] -carmen08 =[[Fs4, eighth_note], - [rst, eighth_note], - [Fs4, eighth_note], - [Fs4, eighth_note], - [Gs4, eighth_note], - [rst, eighth_note], - [Gs4, eighth_note], - [rst, eighth_note], - [E3, eighth_note], - [E3, eighth_note], - [E3, eighth_note], - [E3, sixteenth_note], - [Fs3, eighth_note], - [Fs3, eighth_note], - [rst, quarter_note]] def song_playback(song): for n in range(len(song)): piezo.frequency = (song[n][0]) - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(song[n][1]) # note duration piezo.duty_cycle = 0 # off time.sleep(0.01) From 0b369946059d60f86b7dcc66ea9eaa83cfb9578e Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:16:37 +0100 Subject: [PATCH 17/83] Format Space Face LED --- .../Space_Face_LED_Galaxy_Makeup.py | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Space_Face_LED_Galaxy_Makeup/Space_Face_LED_Galaxy_Makeup.py b/Space_Face_LED_Galaxy_Makeup/Space_Face_LED_Galaxy_Makeup.py index da3b8a03d..0b887ce38 100644 --- a/Space_Face_LED_Galaxy_Makeup/Space_Face_LED_Galaxy_Makeup.py +++ b/Space_Face_LED_Galaxy_Makeup/Space_Face_LED_Galaxy_Makeup.py @@ -1,20 +1,23 @@ -from digitalio import DigitalInOut, Direction -import board -import neopixel import time -pixpin = board.D1 -numpix = 5 +import board +import neopixel +from digitalio import DigitalInOut, Direction + +pix_pin = board.D1 +num_pix = 5 led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT -strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) +strip = neopixel.NeoPixel(pix_pin, num_pix, brightness=1, auto_write=True) -def colorWipe(color, wait): + +def color_wipe(color, wait): for j in range(len(strip)): - strip[j] = (color) - time.sleep(wait) + strip[j] = (color) + time.sleep(wait) + while True: - colorWipe( (50, 0, 50), .1 ) # Purple LEDs + color_wipe((50, 0, 50), .1) # Purple LEDs From 109c0e7be0cc6a0639f53cf4136cd6e4a0599723 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:21:42 +0100 Subject: [PATCH 18/83] Format sound reactive neopixel peace pendant --- .../Sound_Reactive_NeoPixel_Peace_Pendant.py | 114 +++++++++--------- 1 file changed, 59 insertions(+), 55 deletions(-) diff --git a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py index 18d59a287..b77e3be9b 100644 --- a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py +++ b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py @@ -1,46 +1,48 @@ -import board -import neopixel -import time -from analogio import AnalogIn import array -led_pin = board.D0 # NeoPixel LED strand is connected to GPIO #0 / D0 -n_pixels = 12 # Number of pixels you are using -dc_offset = 0 # DC offset in mic signal - if unusure, leave 0 -noise = 100 # Noise/hum/interference in mic signal -samples = 60 # Length of buffer for dynamic level adjustment -top = n_pixels + 1 # Allow dot to go slightly off scale +import board +import neopixel +from analogio import AnalogIn -peak = 0 # Used for falling dot -dotcount = 0 # Frame counter for delaying dot-falling speed -volcount = 0 # Frame counter for storing past volume data +led_pin = board.D0 # NeoPixel LED strand is connected to GPIO #0 / D0 +n_pixels = 12 # Number of pixels you are using +dc_offset = 0 # DC offset in mic signal - if unusure, leave 0 +noise = 100 # Noise/hum/interference in mic signal +samples = 60 # Length of buffer for dynamic level adjustment +top = n_pixels + 1 # Allow dot to go slightly off scale -lvl = 10 # Current "dampened" audio level -minlvlavg = 0 # For dynamic adjustment of graph low & high -maxlvlavg = 512 +peak = 0 # Used for falling dot +dot_count = 0 # Frame counter for delaying dot-falling speed +vol_count = 0 # Frame counter for storing past volume data + +lvl = 10 # Current "dampened" audio level +min_level_avg = 0 # For dynamic adjustment of graph low & high +max_level_avg = 512 # Collection of prior volume samples -vol = array.array('H', [0]*samples) +vol = array.array('H', [0] * samples) mic_pin = AnalogIn(board.A1) strip = neopixel.NeoPixel(led_pin, n_pixels, brightness=.1, auto_write=True) + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) - elif (pos < 170): + if pos < 85: + return (int(pos * 3), int(255 - (pos * 3)), 0) + elif pos < 170: pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) -def remapRange(value, leftMin, leftMax, rightMin, rightMax): + +def remap_range(value, leftMin, leftMax, rightMin, rightMax): # this remaps a value from original (left) range to new (right) range # Figure out how 'wide' each range is leftSpan = leftMax - leftMin @@ -52,51 +54,54 @@ def remapRange(value, leftMin, leftMax, rightMin, rightMax): # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) + while True: - n = int ( ( mic_pin.value / 65536 ) * 1000 ) # 10-bit ADC format - n = abs(n - 512 - dc_offset) # Center on zero + n = int((mic_pin.value / 65536) * 1000) # 10-bit ADC format + n = abs(n - 512 - dc_offset) # Center on zero - if ( n >= noise ): # Remove noise/hum - n = n - noise + if n >= noise: # Remove noise/hum + n = n - noise - lvl = int ( ( (lvl * 7) + n ) / 8 ) # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) + lvl = int(((lvl * 7) + n) / 8) # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) # Calculate bar height based on dynamic min/max levels (fixed point): - height = top * (lvl - minlvlavg) / (maxlvlavg - minlvlavg) + height = top * (lvl - min_level_avg) / (max_level_avg - min_level_avg) # Clip output - if(height < 0): - height = 0 - elif (height > top): + if height < 0: + height = 0 + elif height > top: height = top # Keep 'peak' dot at top - if(height > peak): - peak = height + if height > peak: + peak = height - # Color pixels based on rainbow gradient + # Color pixels based on rainbow gradient for i in range(0, len(strip)): - if (i >= height): - strip[i] = [0,0,0] + if i >= height: + strip[i] = [0, 0, 0] else: - strip[i] = wheel(remapRange(i, 0, (n_pixels - 1), 30, 150)) + strip[i] = wheel(remap_range(i, 0, (n_pixels - 1), 30, 150)) # Save sample for dynamic leveling - vol[volcount] = n + vol[vol_count] = n - # Advance/rollover sample counter - if (++volcount >= samples): - volcount = 0 + # Advance/rollover sample counter + vol_count += 1 - # Get volume range of prior frames - minlvl = vol[0] - maxlvl = vol[0] + if vol_count >= samples: + vol_count = 0 + + # Get volume range of prior frames + min_level = vol[0] + max_level = vol[0] for i in range(1, len(vol)): - if(vol[i] < minlvl): - minlvl = vol[i] - elif (vol[i] > maxlvl): - maxlvl = vol[i] + if vol[i] < min_level: + min_level = vol[i] + elif vol[i] > max_level: + max_level = vol[i] # minlvl and maxlvl indicate the volume range over prior frames, used # for vertically scaling the output graph (so it looks interesting @@ -104,11 +109,10 @@ while True: # (e.g. at very low volume levels) the graph becomes super coarse # and 'jumpy'...so keep some minimum distance between them (this # also lets the graph go to zero when no sound is playing): - if( (maxlvl - minlvl) < top ): - maxlvl = minlvl + top + if (max_level - min_level) < top: + max_level = min_level + top + + min_level_avg = (min_level_avg * 63 + min_level) >> 6 # Dampen min/max levels - divide by 64 (2^6) + max_level_avg = (max_level_avg * 63 + max_level) >> 6 # fake rolling average - divide by 64 (2^6) - minlvlavg = ( minlvlavg * 63 + minlvl ) >> 6 # Dampen min/max levels - divide by 64 (2^6) - maxlvlavg = ( maxlvlavg * 63 + maxlvl ) >> 6 # fake rolling average - divide by 64 (2^6) - print(n) - From b6e71dafd045c0802a9b795c9bed9ecda3fd9f39 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:26:03 +0100 Subject: [PATCH 19/83] Format Snow Globe --- SnowGlobe/main.py | 69 +++++++++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 26 deletions(-) diff --git a/SnowGlobe/main.py b/SnowGlobe/main.py index 76a84b93c..6c1a0d216 100644 --- a/SnowGlobe/main.py +++ b/SnowGlobe/main.py @@ -1,11 +1,10 @@ -# Snow Globe -# for Adafruit Circuit Playground express -# with CircuitPython +"""Snow Globe for Adafruit Circuit Playground express with CircuitPython """ -from adafruit_circuitplayground.express import cpx import math import time +from adafruit_circuitplayground.express import cpx + ROLL_THRESHOLD = 30 # Total acceleration cpx.pixels.brightness = 0.1 # set brightness value @@ -21,7 +20,8 @@ new_roll = False rolling = False -def fade_pixels(fade_color): # pick from colors defined above, e.g., RED, GREEN, BLUE, WHITE, etc. +# pick from colors defined above, e.g., RED, GREEN, BLUE, WHITE, etc. +def fade_pixels(fade_color): # fade up for j in range(25): pixel_brightness = (j * 0.01) @@ -36,6 +36,7 @@ def fade_pixels(fade_color): # pick from colors defined above, e.g., RED, GREEN for i in range(10): cpx.pixels[i] = fade_color + # fade in the pixels fade_pixels(GREEN) @@ -53,49 +54,64 @@ def play_song(song_number): eighth_note = whole_note / 8 # set up note values - A3 = 220 - Bb3 = 233 - B3 = 247 + # A3 = 220 + # Bb3 = 233 + # B3 = 247 C4 = 262 - Db4 = 277 + # Db4 = 277 D4 = 294 - Eb4 = 311 + # Eb4 = 311 E4 = 330 F4 = 349 - Gb4 = 370 + # Gb4 = 370 G4 = 392 - Ab4 = 415 + # Ab4 = 415 A4 = 440 - Bb4 = 466 + # Bb4 = 466 B4 = 494 if song_number == 1: # jingle bells - jingle_bells_song = [[E4, quarter_note], [E4, quarter_note], - [E4, half_note], [E4, quarter_note], [E4, quarter_note], - [E4, half_note], [E4, quarter_note], [G4, quarter_note], - [C4, dotted_quarter_note], [D4, eighth_note], [E4, whole_note]] + jingle_bells_song = [ + [E4, quarter_note], + [E4, quarter_note], + [E4, half_note], + [E4, quarter_note], + [E4, quarter_note], + [E4, half_note], + [E4, quarter_note], + [G4, quarter_note], + [C4, dotted_quarter_note], + [D4, eighth_note], + [E4, whole_note], + ] for n in range(len(jingle_bells_song)): cpx.start_tone(jingle_bells_song[n][0]) time.sleep(jingle_bells_song[n][1]) cpx.stop_tone() - if song_number == 2: # Let It Snow - let_it_snow_song = [[B4, dotted_quarter_note], [A4, eighth_note], - [G4, quarter_note], [G4, dotted_quarter_note], [F4, eighth_note], - [E4, quarter_note], [E4, dotted_quarter_note], [D4, eighth_note], - [C4, whole_note]] + let_it_snow_song = [ + [B4, dotted_quarter_note], + [A4, eighth_note], + [G4, quarter_note], + [G4, dotted_quarter_note], + [F4, eighth_note], + [E4, quarter_note], + [E4, dotted_quarter_note], + [D4, eighth_note], + [C4, whole_note], + ] for n in range(len(let_it_snow_song)): cpx.start_tone(let_it_snow_song[n][0]) time.sleep(let_it_snow_song[n][1]) cpx.stop_tone() -play_song(1) # play music on start +play_song(1) # play music on start # Loop forever while True: @@ -114,7 +130,8 @@ while True: y_total = y_total / 10 z_total = z_total / 10 - total_accel = math.sqrt(x_total*x_total + y_total*y_total + z_total*z_total) + total_accel = math.sqrt(x_total * x_total + y_total * + y_total + z_total * z_total) # Check for rolling if total_accel > ROLL_THRESHOLD: @@ -127,7 +144,7 @@ while True: # Keep rolling for a period of time even after shaking stops if new_roll: if time.monotonic() - roll_start_time > 2: # seconds to run - rolling = False + rolling = False # Light show if rolling: @@ -140,7 +157,7 @@ while True: new_roll = False # play a song! play_song(2) - #return to resting color + # return to resting color fade_pixels(GREEN) cpx.pixels.brightness = 0.05 cpx.pixels.fill(GREEN) From 7e7e396b976a2e05fb8490aa3c3f782a8d641739 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:30:46 +0100 Subject: [PATCH 20/83] Format Sensor Plotting --- .../audio.py | 23 ++++++++++++++----- .../buttons_switch.py | 5 ++-- .../color.py | 17 +++++++++----- .../light.py | 9 ++++---- .../potentiometer.py | 3 +++ .../pulse.py | 11 +++++---- .../temperature.py | 12 ++++++---- .../touch.py | 1 + 8 files changed, 53 insertions(+), 28 deletions(-) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/audio.py b/Sensor_Plotting_With_Mu_CircuitPython/audio.py index 596b50ec1..b9c7f4830 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/audio.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/audio.py @@ -1,8 +1,9 @@ -import audiobusio -import time -import board -import array +import array import math +import time + +import audiobusio +import board def mean(values): @@ -11,10 +12,20 @@ def mean(values): def normalized_rms(values): minbuf = int(mean(values)) - return math.sqrt(sum(float(sample-minbuf)*(sample-minbuf) for sample in values) / len(values)) + sum_of_samples = sum( + float(sample - minbuf) * (sample - minbuf) + for sample in values + ) + + return math.sqrt(sum_of_samples / len(values)) -mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, frequency=16000, bit_depth=16) +mic = audiobusio.PDMIn( + board.MICROPHONE_CLOCK, + board.MICROPHONE_DATA, + frequency=16000, + bit_depth=16 +) samples = array.array('H', [0] * 160) mic.record(samples, len(samples)) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/buttons_switch.py b/Sensor_Plotting_With_Mu_CircuitPython/buttons_switch.py index 40dd4dc34..11ba047b8 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/buttons_switch.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/buttons_switch.py @@ -1,7 +1,8 @@ -import digitalio -import board import time +import board +import digitalio + button_a = digitalio.DigitalInOut(board.BUTTON_A) button_a.direction = digitalio.Direction.INPUT button_a.pull = digitalio.Pull.DOWN diff --git a/Sensor_Plotting_With_Mu_CircuitPython/color.py b/Sensor_Plotting_With_Mu_CircuitPython/color.py index 9b854a6c0..48fbbe5fc 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/color.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/color.py @@ -1,6 +1,6 @@ -import neopixel -import analogio +import analogio import board +import neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0) light = analogio.AnalogIn(board.LIGHT) @@ -9,12 +9,17 @@ while True: pixels.fill((0, 0, 0)) pixels[1] = (255, 0, 0) raw_red = light.value - red = int(raw_red * (255/65535)) + + red = int(raw_red * (255 / 65535)) pixels[1] = (0, 255, 0) raw_green = light.value - green = int(raw_green * (255/65535)) + + green = int(raw_green * (255 / 65535)) pixels[1] = (0, 0, 255) raw_blue = light.value - blue = int(raw_blue * (255/65535)) + + blue = int(raw_blue * (255 / 65535)) pixels.fill((0, 0, 0)) - print((green, blue, red)) # Printed to match the color lines on the Mu plotter! The orange line represents red. + + # Printed to match the color lines on the Mu plotter! The orange line represents red. + print((green, blue, red)) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/light.py b/Sensor_Plotting_With_Mu_CircuitPython/light.py index ded46aba6..5728d160c 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/light.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/light.py @@ -1,9 +1,10 @@ +import time + import analogio import board -import time - + light = analogio.AnalogIn(board.LIGHT) - + while True: - print((light.value,)) + print(light.value) time.sleep(0.1) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/potentiometer.py b/Sensor_Plotting_With_Mu_CircuitPython/potentiometer.py index ce548f8d3..c9c74675e 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/potentiometer.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/potentiometer.py @@ -1,12 +1,15 @@ import time + import analogio import board potentiometer = analogio.AnalogIn(board.A1) + def get_voltage(pin): return (pin.value * 3.3) / 65536 + while True: print((get_voltage(potentiometer),)) time.sleep(0.1) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/pulse.py b/Sensor_Plotting_With_Mu_CircuitPython/pulse.py index bc52ca379..2d350c03e 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/pulse.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/pulse.py @@ -1,7 +1,8 @@ -import neopixel -import analogio import time + +import analogio import board +import neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0) light = analogio.AnalogIn(board.LIGHT) @@ -22,8 +23,8 @@ while True: for s in range(NUM_OVERSAMPLE): oversample += float(light.value) # and save the average from the oversamples - samples[i] = oversample / NUM_OVERSAMPLE # Find the average + samples[i] = oversample / NUM_OVERSAMPLE # Find the average mean = sum(samples) / float(len(samples)) # take the average - print((samples[i] - mean,)) # 'center' the reading - time.sleep(0.025) # change to go faster/slower + print((samples[i] - mean,)) # 'center' the reading + time.sleep(0.025) # change to go faster/slower diff --git a/Sensor_Plotting_With_Mu_CircuitPython/temperature.py b/Sensor_Plotting_With_Mu_CircuitPython/temperature.py index ce61d74c3..d7f80a02c 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/temperature.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/temperature.py @@ -1,10 +1,12 @@ -import adafruit_thermistor -import board -import time +import time -thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950) +import adafruit_thermistor +import board + +thermistor = adafruit_thermistor.Thermistor( + board.TEMPERATURE, 10000, 10000, 25, 3950) while True: - print((thermistor.temperature,)) + print(thermistor.temperature) # print(((thermistor.temperature * 9 / 5 + 32),)) # Fahrenheit time.sleep(0.25) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/touch.py b/Sensor_Plotting_With_Mu_CircuitPython/touch.py index f9ce06d3b..f8457f83b 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/touch.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/touch.py @@ -1,4 +1,5 @@ import time + import board import touchio From e2a22db1edc000196b12a6f7e2604c0f99ced865 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:34:39 +0100 Subject: [PATCH 21/83] Format Screaming Cauldron --- ScreamingCauldron/screamingCauldron.py | 30 +++++++++++++++----------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/ScreamingCauldron/screamingCauldron.py b/ScreamingCauldron/screamingCauldron.py index b544b56f9..31f5222e9 100644 --- a/ScreamingCauldron/screamingCauldron.py +++ b/ScreamingCauldron/screamingCauldron.py @@ -1,12 +1,13 @@ # Screaming Cauldron # for Adafruit Industries Learning Guide -from digitalio import DigitalInOut, Direction -from analogio import AnalogIn -import neopixel -import board import time +import board +import neopixel +from analogio import AnalogIn +from digitalio import DigitalInOut, Direction + led = DigitalInOut(board.D13) # on board red LED led.direction = Direction.OUTPUT @@ -24,27 +25,30 @@ pixels = neopixel.NeoPixel(neoPin, numPix, auto_write=0, brightness=.8) pixels.fill((0, 0, 0,)) pixels.show() -def getVoltage(pin): + +def get_voltage(pin): return (pin.value * 3.3) / 65536 -def remapRange(value, leftMin, leftMax, rightMin, rightMax): + +def remap_range(value, left_min, left_max, right_min, right_max): # this remaps a value from original (left) range to new (right) range # Figure out how 'wide' each range is - leftSpan = leftMax - leftMin - rightSpan = rightMax - rightMin + leftSpan = left_max - left_min + rightSpan = right_max - right_min # Convert the left range into a 0-1 range (int) - valueScaled = int(value - leftMin) / int(leftSpan) + valueScaled = int(value - left_min) / int(leftSpan) # Convert the 0-1 range into a value in the right range. - return int(rightMin + (valueScaled * rightSpan)) + return int(right_min + (valueScaled * rightSpan)) + while True: distRaw = analog0in.value # read the raw sensor value print("A0: %f" % distRaw) # write raw value to REPL - distRedColor = remapRange(distRaw, 0, 64000, 0, 255) - distGreenColor = remapRange(distRaw, 0, 64000, 200, 0) - if(distRaw > 40000): # at about 4 inches, this goes off! + distRedColor = remap_range(distRaw, 0, 64000, 0, 255) + distGreenColor = remap_range(distRaw, 0, 64000, 200, 0) + if distRaw > 40000: # at about 4 inches, this goes off! led.value = True aFXPin.value = False time.sleep(.35) From 7bc3b9cfd73cf0834166148d046470b3ea24b884 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:34:53 +0100 Subject: [PATCH 22/83] Format RGB LED Scripts --- RGB_LED_Strips/main.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/RGB_LED_Strips/main.py b/RGB_LED_Strips/main.py index 05064de40..96e66def4 100644 --- a/RGB_LED_Strips/main.py +++ b/RGB_LED_Strips/main.py @@ -1,23 +1,28 @@ -import board -import pulseio import time -RED_PIN = board.D5 # Red LED pin +import board +import pulseio + +RED_PIN = board.D5 # Red LED pin GREEN_PIN = board.D6 # Green LED pin -BLUE_PIN = board.D3 # Blue LED pin +BLUE_PIN = board.D3 # Blue LED pin FADE_SLEEP = 10 # Number of milliseconds to delay between changes. - # Increase to slow down, decrease to speed up. +# Increase to slow down, decrease to speed up. # Define PWM outputs: red = pulseio.PWMOut(RED_PIN) green = pulseio.PWMOut(GREEN_PIN) blue = pulseio.PWMOut(BLUE_PIN) + # Function to simplify setting duty cycle to percent value. + + def duty_cycle(percent): return int(percent / 100.0 * 65535.0) + # Fade from nothing up to full red. for i in range(100): red.duty_cycle = duty_cycle(i) From fe7f6fb2d05a11c2d4222763d67d38b79d168af6 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:42:07 +0100 Subject: [PATCH 23/83] Autoformat Guardian Sword --- .../3D_Printed_Guardian_Sword.py | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py b/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py index 6f999044a..8a9b15f7c 100644 --- a/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py +++ b/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py @@ -18,32 +18,32 @@ pixels = neopixel.NeoPixel(pin, pixel_count, brightness=1, auto_write=False) while True: - # For the first 14 pixels, make them orange, + # For the first 14 pixels, make them orange, # starting from pixel number 0. - for i in range( 0, APIXELS ): - # Set Pixels to Orange Color - pixels[i] = ( 255, 50, 0 ) + for i in range(0, APIXELS): + # Set Pixels to Orange Color + pixels[i] = (255, 50, 0) # This sends the updated pixel color to the hardware. - pixels.write() - # Delay for a period of time (in milliseconds). - time.sleep(delayval) + pixels.write() + # Delay for a period of time (in milliseconds). + time.sleep(delayval) - # Fill up 84 pixels with blue, + # Fill up 84 pixels with blue, # starting with pixel number 14. - for i in range ( 14, BPIXELS ): - # Set Pixels to Orange Color - pixels[i] = ( 0, 250, 200 ) + for i in range(14, BPIXELS): + # Set Pixels to Orange Color + pixels[i] = (0, 250, 200) # This sends the updated pixel color to the hardware. - pixels.write() - # Delay for a period of time (in milliseconds). - time.sleep(delayval) + pixels.write() + # Delay for a period of time (in milliseconds). + time.sleep(delayval) - # Fill up 9 pixels with orange, + # Fill up 9 pixels with orange, # starting from pixel number 84. - for i in range ( 84, CPIXELS ): - # Set Pixels to Orange Color - pixels[i] = ( 250, 50, 0 ) + for i in range(84, CPIXELS): + # Set Pixels to Orange Color + pixels[i] = (250, 50, 0) # This sends the updated pixel color to the hardware. - pixels.write() - # Delay for a period of time (in milliseconds). - time.sleep(delayval) + pixels.write() + # Delay for a period of time (in milliseconds). + time.sleep(delayval) From c7edeb188bec1486927ae80ec3f867b0ca0c9de4 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:42:21 +0100 Subject: [PATCH 24/83] Autoformat Microphone flag --- .../3D_Printed_LED_Microphone_Flag.py | 50 +++++++++++-------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py index c594fd273..61dc57bd3 100644 --- a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py +++ b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py @@ -33,14 +33,15 @@ import time from analogio import AnalogIn import array -n_pixels = 16 # Number of pixels you are using -mic_pin = AnalogIn(board.A1) # Microphone is attached to this analog pin -led_pin = board.D1 # NeoPixel LED strand is connected to this pin +n_pixels = 16 # Number of pixels you are using +mic_pin = AnalogIn(board.A1) # Microphone is attached to this analog pin +led_pin = board.D1 # NeoPixel LED strand is connected to this pin sample_window = .1 # Sample window for average level peak_hang = 24 # Time of pause before peak dot falls peak_fall = 4 # Rate of falling peak dot input_floor = 10 # Lower range of analogRead input -input_ceiling = 300 # Max range of analogRead input, the lower the value the more sensitive (1023 = max) +# Max range of analogRead input, the lower the value the more sensitive (1023 = max) +input_ceiling = 300 peak = 16 # Peak level of column; used for falling dots sample = 0 @@ -50,6 +51,7 @@ dothangcount = 0 # Frame counter for holding peak dot strip = neopixel.NeoPixel(led_pin, n_pixels, brightness=1, auto_write=False) + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. @@ -64,6 +66,7 @@ def wheel(pos): pos -= 170 return (0, int(pos*3), int(255 - pos*3)) + def remapRange(value, leftMin, leftMax, rightMin, rightMax): # this remaps a value fromhere original (left) range to new (right) range # Figure out how 'wide' each range is @@ -76,6 +79,7 @@ def remapRange(value, leftMin, leftMax, rightMin, rightMax): # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) + def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): originalrange = 0 newrange = 0 @@ -86,16 +90,17 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): # condition curve parameter # limit range - if (curve > 10): + if (curve > 10): curve = 10 - if (curve < -10): + if (curve < -10): curve = -10 - # - invert and scale - - # this seems more intuitive + # - invert and scale - + # this seems more intuitive # postive numbers give more weight to high end on output - curve = (curve * -.1) - curve = pow(10, curve) # convert linear scale into lograthimic exponent for other pow function + curve = (curve * -.1) + # convert linear scale into lograthimic exponent for other pow function + curve = pow(10, curve) # Check for out of range inputValues if (inputvalue < originalmin): @@ -114,21 +119,22 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): invflag = 1 zerorefcurval = inputvalue - originalmin - normalizedcurval = zerorefcurval / originalrange # normalize to 0 - 1 float + normalizedcurval = zerorefcurval / originalrange # normalize to 0 - 1 float - # Check for originalMin > originalMax - # -the math for all other cases + # Check for originalMin > originalMax + # -the math for all other cases # i.e. negative numbers seems to work out fine - if (originalmin > originalmax ): + if (originalmin > originalmax): return(0) if (invflag == 0): - rangedvalue = (pow(normalizedcurval, curve) * newrange) + newbegin + rangedvalue = (pow(normalizedcurval, curve) * newrange) + newbegin else: # invert the ranges - rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange); + rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange) return(rangedvalue) + def drawLine(fromhere, to): fromheretemp = 0 @@ -139,21 +145,23 @@ def drawLine(fromhere, to): to = fromheretemp for i in range(fromhere, to): - strip[i] = (0,0,0) + strip[i] = (0, 0, 0) + while True: time_start = time.monotonic() # current time used for sample window peaktopeak = 0 # peak-to-peak level signalmax = 0 - signalmin = 1023 + signalmin = 1023 c = 0 y = 0 # collect data for length of sample window (in seconds) - while ( ( time.monotonic() - time_start ) < sample_window): + while ((time.monotonic() - time_start) < sample_window): - sample = mic_pin.value / 64 # convert to arduino 10-bit [1024] fromhere 16-bit [65536] + # convert to arduino 10-bit [1024] fromhere 16-bit [65536] + sample = mic_pin.value / 64 if (sample < 1024): # toss out spurious readings @@ -171,7 +179,7 @@ while True: # Scale the input logarithmically instead of linearly c = fscale(input_floor, input_ceiling, (n_pixels - 1), 0, peaktopeak, 2) - if (c < peak): + if (c < peak): peak = c # keep dot on top dothangcount = 0 # make the dot hang before falling From 2a01c64600f5c888d2b541c0e3af674acaa26d31 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:42:42 +0100 Subject: [PATCH 25/83] Autoformat 3D print Neopixel Gas Mask --- .../3D_Printed_NeoPixel_Gas_Mask.py | 83 ++++++++++--------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py b/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py index 99d83de1d..aae389c44 100644 --- a/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py +++ b/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py @@ -2,54 +2,55 @@ import board import neopixel import time try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random numpix = 24 # Number of NeoPixels pixpin = board.D0 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.3) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.3) -mode = 0 # Current animation effect -offset = 0 # Position of spinner animation -color = [255, 0, 0] # RGB color - red +mode = 0 # Current animation effect +offset = 0 # Position of spinner animation +color = [255, 0, 0] # RGB color - red prevtime = time.monotonic() # Time of last animation mode switch while True: # Loop forever... - if mode == 0: # Random sparkles - lights just one LED at a time - i = random.randint(0, numpix - 1) # Choose random pixel - strip[i] = color # Set it to current color - strip.write() # Refresh LED states - # Set same pixel to "off" color now but DON'T refresh... - # it stays on for now...bot this and the next random - # pixel will be refreshed on the next pass. - strip[i] = [0,0,0] - time.sleep(0.008) # 8 millisecond delay - elif mode == 1: # Spinny wheels - # A little trick here: pixels are processed in groups of 8 - # (with 2 of 8 on at a time), NeoPixel rings are 24 pixels - # (8*3) and 16 pixels (8*2), so we can issue the same data - # to both rings and it appears correct and contiguous - # (also, the pixel order is different between the two ring - # types, so we get the reversed motion on #2 for free). - for i in range(numpix): # For each LED... - if ((offset + i) & 7) < 2: # 2 pixels out of 8... - strip[i] = color # are set to current color - else: - strip[i] = [0,0,0] # other pixels are off - strip.write() # Refresh LED states - time.sleep(0.04) # 40 millisecond delay - offset += 1 # Shift animation by 1 pixel on next frame - if offset >= 8: offset = 0 - # Additional animation modes could be added here! + if mode == 0: # Random sparkles - lights just one LED at a time + i = random.randint(0, numpix - 1) # Choose random pixel + strip[i] = color # Set it to current color + strip.write() # Refresh LED states + # Set same pixel to "off" color now but DON'T refresh... + # it stays on for now...bot this and the next random + # pixel will be refreshed on the next pass. + strip[i] = [0, 0, 0] + time.sleep(0.008) # 8 millisecond delay + elif mode == 1: # Spinny wheels + # A little trick here: pixels are processed in groups of 8 + # (with 2 of 8 on at a time), NeoPixel rings are 24 pixels + # (8*3) and 16 pixels (8*2), so we can issue the same data + # to both rings and it appears correct and contiguous + # (also, the pixel order is different between the two ring + # types, so we get the reversed motion on #2 for free). + for i in range(numpix): # For each LED... + if ((offset + i) & 7) < 2: # 2 pixels out of 8... + strip[i] = color # are set to current color + else: + strip[i] = [0, 0, 0] # other pixels are off + strip.write() # Refresh LED states + time.sleep(0.04) # 40 millisecond delay + offset += 1 # Shift animation by 1 pixel on next frame + if offset >= 8: + offset = 0 + # Additional animation modes could be added here! - t = time.monotonic() # Current time in seconds - if (t - prevtime) >= 8: # Every 8 seconds... - mode += 1 # Advance to next mode - if mode > 1: # End of modes? - mode = 0 # Start over from beginning - # Rotate color R->G->B - color = [ color[2], color[0], color[1] ] - strip.fill([0,0,0]) # Turn off all pixels - prevtime = t # Record time of last mode change + t = time.monotonic() # Current time in seconds + if (t - prevtime) >= 8: # Every 8 seconds... + mode += 1 # Advance to next mode + if mode > 1: # End of modes? + mode = 0 # Start over from beginning + # Rotate color R->G->B + color = [color[2], color[0], color[1]] + strip.fill([0, 0, 0]) # Turn off all pixels + prevtime = t # Record time of last mode change From 78d7cee1b2131e77d109c72917c255a1cc3e58d0 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:43:04 +0100 Subject: [PATCH 26/83] Autoformat 3D print NeoPixel Hair Dress --- .../3D_Printed_NeoPixel_Ring_Hair_Dress.py | 174 +++++++++++------- 1 file changed, 104 insertions(+), 70 deletions(-) diff --git a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py index fc51bddcf..96a04c8f0 100644 --- a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py +++ b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py @@ -1,27 +1,27 @@ # # 3D_Printed_NeoPixel_Ring_Hair_Dress.py # -# this was ported to CircuitPython from the 'Gemma Hoop Animator' +# this was ported to CircuitPython from the 'Gemma Hoop Animator' # # https://github.com/HerrRausB/GemmaHoopAnimator # -# unless you # don't like the preset animations or find a +# unless you # don't like the preset animations or find a # major bug, you don't need tochange anything here # import board import neopixel import time try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random from analogio import AnalogIn # available actions ACT_NOP = 0x00 # all leds off, do nothing ACT_SIMPLE_RING = 0x01 # all leds on ACT_CYCLING_RING_ACLK = 0x02 # anti clockwise cycling colors -ACT_CYCLING_RING_CLKW = 0x04 # clockwise cycling colors +ACT_CYCLING_RING_CLKW = 0x04 # clockwise cycling colors ACT_WHEEL_ACLK = 0x08 # anti clockwise spinning wheel ACT_WHEEL_CLKW = 0x10 # clockwise spinning wheel ACT_SPARKLING_RING = 0x20 # sparkling effect @@ -29,28 +29,32 @@ ACT_SPARKLING_RING = 0x20 # sparkling effect numpix = 16 # total number of NeoPixels pixel_output = board.D0 # pin where NeoPixels are connected analog_input = board.A0 # needed to seed the random generator -strip = neopixel.NeoPixel(pixel_output, numpix, brightness=.3, auto_write=False) +strip = neopixel.NeoPixel(pixel_output, numpix, + brightness=.3, auto_write=False) # available color generation methods COL_RANDOM = 0x40 # colors will be generated randomly COL_SPECTRUM = 0x80 # colors will be set as cyclic spectral wipe # specifiyng the action list -action_duration = 0 # the action's overall duration in milliseconds (be careful not - # to use values > 2^16-1 - roughly one minute :-) +# the action's overall duration in milliseconds (be careful not +action_duration = 0 +# to use values > 2^16-1 - roughly one minute :-) action_and_color_gen = 1 # the color generation method -action_step_duration = 2 # the duration of each action step rsp. the delay of the main - # loop in milliseconds - thus, controls the action speed (be - # careful not to use values > 2^16-1 - roughly one minute :-) +# the duration of each action step rsp. the delay of the main +action_step_duration = 2 +# loop in milliseconds - thus, controls the action speed (be +# careful not to use values > 2^16-1 - roughly one minute :-) color_granularity = 3 # controls the increment of the R, G, and B portions of the - # rsp. color. 1 means the increment is 0,1,2,3,..., 10 means - # the increment is 0,10,20,... don't use values > 255, and note - # that even values > 127 wouldn't make much sense... +# rsp. color. 1 means the increment is 0,1,2,3,..., 10 means +# the increment is 0,10,20,... don't use values > 255, and note +# that even values > 127 wouldn't make much sense... -color_interval = 4 # controls the speed of color changing independently from action +# controls the speed of color changing independently from action +color_interval = 4 # general global variables color = 0 @@ -65,7 +69,7 @@ curr_action = 0 curr_color_gen = COL_RANDOM idx = 0 offset = 0 -number_of_actions = 31 +number_of_actions = 31 curr_action_idx = 0 curr_color_granularity = 1 spectrum_part = 0 @@ -81,7 +85,7 @@ spectrum_part = 0 # ACT_WHEEL_ACLK anti clockwise spinning wheel # ACT_WHEEL_CLKW clockwise spinning wheel # ACT_SPARKLING_RING sparkling effect -# +# # valid color options are: # COL_RANDOM colors will be selected randomly, which might # be not very sufficient due to well known @@ -92,45 +96,71 @@ spectrum_part = 0 # action action name & action step color color change # duration color generation method duration granularity interval theactionlist = [ - [ 5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1 ], - [ 2, ACT_CYCLING_RING_CLKW | COL_RANDOM, 0.02, 1, 0.005 ], - [ 5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1 ], - [ 2, ACT_CYCLING_RING_ACLK | COL_RANDOM, 0.02, 1, 0.005 ], - [ 5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1 ], - [ 2.5, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.25, 20, 0.020 ], - [ 1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.50, 1, 0.020 ], - [ .750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.075, 1, 0.020 ], - [ .500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.100, 1, 0.020 ], - [ .500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.125, 1, 0.020 ], - [ .500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.150, 1, 0.050 ], - [ .500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.175, 1, 0.100 ], - [ .500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.200, 1, 0.200 ], - [ .750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.225, 1, 0.250 ], - [ 1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, 0.250, 1, 0.350 ], - [ 30, ACT_SIMPLE_RING | COL_SPECTRUM, 0.050, 1, 0.010 ], - [ 2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.010, 1, 0.010 ], - [ 2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.015, 1, 0.020 ], - [ 2, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.025, 1, 0.030 ], - [ 1, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.050, 1, 0.040 ], - [ 1, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.075, 1, 0.040 ], - [ 1, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.100, 1, 0.050 ], - [ .500, ACT_WHEEL_ACLK | COL_SPECTRUM, 0.125, 1, 0.060 ], - [ .500, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.125, 5, 0.050 ], - [ 1, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.100, 10, 0.040 ], - [ 1.5, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.075, 15, 0.030 ], - [ 2, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.050, 20, 0.020 ], - [ 2.5, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.025, 25, 0.010 ], - [ 3, ACT_WHEEL_CLKW | COL_SPECTRUM, 0.010, 30, 0.005 ], - [ 5, ACT_SPARKLING_RING | COL_RANDOM, 0.010, 25, 1 ], - [ 5, ACT_NOP, 0, 0, 0 ] + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2, ACT_CYCLING_RING_CLKW | COL_RANDOM, + 0.02, 1, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2, ACT_CYCLING_RING_ACLK | COL_RANDOM, + 0.02, 1, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2.5, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.25, 20, 0.020], + [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.50, 1, 0.020], + [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.075, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.100, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.125, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.150, 1, 0.050], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.175, 1, 0.100], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.200, 1, 0.200], + [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.225, 1, 0.250], + [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.250, 1, 0.350], + [30, ACT_SIMPLE_RING | COL_SPECTRUM, + 0.050, 1, 0.010], + [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.010, 1, 0.010], + [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.015, 1, 0.020], + [2, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.025, 1, 0.030], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.050, 1, 0.040], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.075, 1, 0.040], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.100, 1, 0.050], + [.500, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.125, 1, 0.060], + [.500, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.125, 5, 0.050], + [1, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.100, 10, 0.040], + [1.5, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.075, 15, 0.030], + [2, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.050, 20, 0.020], + [2.5, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.025, 25, 0.010], + [3, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.010, 30, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.010, 25, 1], + [5, ACT_NOP, 0, 0, 0] ] def nextspectrumcolor(): global spectrum_part, color_idx, curr_color_granularity, color - + # spectral wipe from green to red - if (spectrum_part == 2): + if (spectrum_part == 2): color = (color_idx, 0, 255-color_idx) color_idx += curr_color_granularity if (color_idx > 255): @@ -146,37 +176,40 @@ def nextspectrumcolor(): color_idx = 0 # spectral wipe from red to blue - elif (spectrum_part == 0 ): + elif (spectrum_part == 0): color = (255 - color_idx, color_idx, 0) color_idx += curr_color_granularity if (color_idx > 255): spectrum_part = 1 color_idx = 0 + def nextrandomcolor(): global color # granularity = 1 --> [0 .. 255] * 1 --> 0,1,2,3 ... 255 # granularity = 10 --> [0 .. 25] * 10 --> 0,10,20,30 ... 250 # granularity = 100 --> [0 .. 2] * 100 --> 0,100, 200 (boaring...) - random_red = random.randint(0, int (256 / curr_color_granularity)) + random_red = random.randint(0, int(256 / curr_color_granularity)) random_red *= curr_color_granularity - random_green = random.randint(0, int (256 / curr_color_granularity)) + random_green = random.randint(0, int(256 / curr_color_granularity)) random_green *= curr_color_granularity - random_blue = random.randint(0, int (256 / curr_color_granularity)) + random_blue = random.randint(0, int(256 / curr_color_granularity)) random_blue *= curr_color_granularity color = (random_red, random_green, random_blue) + def nextcolor(): # save some RAM for more animation actions if (curr_color_gen & COL_RANDOM): - nextrandomcolor() - else: + nextrandomcolor() + else: nextspectrumcolor() + def setup(): # fingers corssed, the seeding makes sense to really get random colors... @@ -187,13 +220,14 @@ def setup(): # let's go! nextcolor() strip.write() - + + setup() while True: # Loop forever... # do we need to load the next action? - if ( (time.monotonic() - action_timer) > curr_action_duration ): + if ((time.monotonic() - action_timer) > curr_action_duration): curr_action_duration = theactionlist[curr_action_idx][action_duration] curr_action = theactionlist[curr_action_idx][action_and_color_gen] & 0x3F curr_action_step_duration = theactionlist[curr_action_idx][action_step_duration] @@ -204,12 +238,12 @@ while True: # Loop forever... # take care to rotate the action list! curr_action_idx %= number_of_actions - action_timer = time.monotonic() - + action_timer = time.monotonic() + # do we need to change to the next color? if ((time.monotonic() - color_timer) > curr_color_interval): nextcolor() - color_timer = time.monotonic() + color_timer = time.monotonic() # do we need to step up the current action? if ((time.monotonic() - action_step_timer) > curr_action_step_duration): @@ -222,18 +256,18 @@ while True: # Loop forever... # unnecessarily, but that would mean more code and less # space for more actions within the animation for i in range(0, numpix): - strip[i] = (0,0,0) + strip[i] = (0, 0, 0) elif (curr_action == ACT_SIMPLE_RING): # even more trivial - just set the new color, if there is one for i in range(0, numpix): strip[i] = color - elif ( curr_action == (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW)): + elif (curr_action == (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW)): # spin the ring clockwise or anti clockwise if (curr_action == ACT_CYCLING_RING_ACLK): idx += 1 - else: + else: idx -= 1 # prevent overflows or underflows @@ -246,23 +280,23 @@ while True: # Loop forever... # switch on / off the appropriate pixels according to # the current offset for idx in range(0, numpix): - if ( ((offset + idx) & 7 ) < 2 ): + if (((offset + idx) & 7) < 2): strip[idx] = color else: - strip[idx] = (0,0,0) + strip[idx] = (0, 0, 0) # advance the offset and thus, spin the wheel - if (curr_action == ACT_WHEEL_CLKW): + if (curr_action == ACT_WHEEL_CLKW): offset += 1 - else: + else: offset -= 1 # prevent overflows or underflows offset %= numpix - + elif (curr_action == ACT_SPARKLING_RING): # switch current pixel off - strip[idx] = (0,0,0) + strip[idx] = (0, 0, 0) # pick a new pixel idx = random.randint(0, numpix) # set new pixel to the current color From c1e2bb96f39f9638f0e18059cd244adb0baba546 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 18:43:17 +0100 Subject: [PATCH 27/83] Autoformat Unicorn Horn --- 3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py b/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py index d9e459f0f..37ec34dd1 100644 --- a/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py +++ b/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py @@ -1,5 +1,5 @@ from digitalio import DigitalInOut, Direction -import board +import board import neopixel import time @@ -11,6 +11,7 @@ led.direction = Direction.OUTPUT strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. @@ -25,18 +26,21 @@ def wheel(pos): pos -= 170 return (0, int(pos*3), int(255 - pos*3)) + def rainbow_cycle(wait): for j in range(255*5): for i in range(len(strip)): - idx = int ((i * 256 / len(strip)) + j) + idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) time.sleep(wait) + def rainbow(wait): for j in range(255): for i in range(len(strip)): - idx = int (i+j) + idx = int(i+j) strip[i] = wheel(idx & 255) + while True: rainbow_cycle(0.05) From 1350a433a7a1922b1c8f56dca53dc31de92de498 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 19:07:55 +0100 Subject: [PATCH 28/83] Autformat everything --- .../3D_Printed_Guardian_Sword.py | 17 +- .../3D_Printed_LED_Microphone_Flag.py | 57 ++-- .../3D_Printed_NeoPixel_Gas_Mask.py | 30 ++- .../3D_Printed_NeoPixel_Ring_Hair_Dress.py | 149 +++++------ .../3D_Printed_Unicorn_Horn.py | 15 +- Adafruit_LED_Sequins/Adafruit_LED_Sequins.py | 22 +- .../Animated_NeoPixel_Glow_Fur_Scarf.py | 117 ++++----- Annoy_O_Matic/main.py | 50 ++-- .../Arcade_Button_Control_Box.py | 5 +- Breath_Mask/Breath_Mask.py | 61 +++-- Breath_Tester/Breath_Tester.py | 32 ++- Chilled_Drinkibot/main.py | 22 +- CircuitPy_OTP/main.py | 62 +++-- .../CircuitPython_AnalogIn.py | 3 +- .../CircuitPython_AnalogOut.py | 2 +- .../CircuitPython_CapTouch.py | 1 + .../CircuitPython_CapTouch_2Pins.py | 1 + .../CircuitPython_Digital_In_Out.py | 7 +- .../CircuitPython_DotStar.py | 18 +- .../CircuitPython_HID_Keyboard.py | 5 +- .../CircuitPython_HID_Mouse.py | 1 + .../CircuitPython_I2C_Scan.py | 6 +- .../CircuitPython_I2C_TSL2561.py | 8 +- .../CircuitPython_Internal_RGB_LED_colors.py | 4 +- .../CircuitPython_Internal_RGB_LED_rainbow.py | 12 +- .../CircuitPython_Logger.py | 3 +- .../CircuitPython_Logger_Boot.py | 2 +- .../CircuitPython_NeoPixel.py | 7 +- .../CircuitPython_NeoPixel_RGBW.py | 3 +- CircuitPython_Essentials/CircuitPython_PWM.py | 3 +- .../CircuitPython_PWM_Piezo.py | 8 +- .../CircuitPython_PWM_Piezo_simpleio.py | 3 +- .../CircuitPython_Servo.py | 3 +- .../CircuitPython_UART.py | 5 +- CircuitPython_Essentials/SPI_Test_Script.py | 5 +- CircuitPython_Essentials/UART_Test_Script.py | 4 +- CircuitPython_Hardware_SD_Cards/hello.py | 1 - CircuitPython_Hardware_SD_Cards/sdmount.py | 6 +- .../sdmount_lib.py | 6 +- CircuitPython_Painter/main.py | 55 ++-- .../CircuitPython_AnalogIn.py | 3 +- .../CircuitPython_AnalogOut.py | 2 +- .../CircuitPython_CapTouch.py | 1 + .../CircuitPython_CapTouch_2Pins.py | 1 + .../CircuitPython_Digital_In_Out.py | 7 +- .../CircuitPython_DotStar.py | 18 +- .../CircuitPython_Internal_RGB_LED_colors.py | 4 +- .../CircuitPython_Internal_RGB_LED_rainbow.py | 12 +- .../CircuitPython_NeoPixel.py | 7 +- .../CircuitPython_NeoPixel_RGBW.py | 4 +- .../CircuitPython_PWM.py | 3 +- .../CircuitPython_PWM_Piezo.py | 10 +- .../CircuitPython_PWM_Piezo_simpleio.py | 3 +- .../CircuitPython_Servo.py | 3 +- .../CircuitPython_UART.py | 5 +- CircuitPython_Quick_Starts/SPI_Test_Script.py | 3 +- CircuitPython_TVBGone/cpx_main.py | 25 +- CircuitPython_TVBGone/gemma_main.py | 22 +- Close_Encounters_Hat/Close_Encounters_Hat.py | 79 +++--- Combo_Dial_Safe/main.py | 9 +- Crickits/bubble_machine/main.py | 29 +- Crickits/feynman_bot/code.py | 61 +++-- Cyber_Flower/main.py | 91 +++---- Cyber_Flower/main_simple.py | 102 +++---- Cyberpunk_Spikes/Cyberpunk_Spikes.py | 81 +++--- .../DataLogger.py | 7 +- .../digitalsand.py | 140 +++++----- EPROM_Emulator/debouncer.py | 14 +- EPROM_Emulator/directory_node.py | 26 +- EPROM_Emulator/emulator.py | 13 +- EPROM_Emulator/main.py | 28 +- Foul_Fowl/main.py | 40 ++- FruitBox_Sequencer/main.py | 4 +- .../gemma_m0_clockwork_goggles.py | 58 ++-- GemmaM0_Password_Vault/main.py | 8 +- GemmaM0_Radio_Tuning_Knob/main.py | 12 +- GemmaM0_Vibration_Switch_Motion_Alarm/main.py | 7 +- .../Gemma_3D_Printed_Tree_Topper.py | 73 +++--- .../Gemma_Firewalker_Lite_Sneakers.py | 248 +++++++++--------- Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py | 103 ++++---- Gemma_LightTouch/gemma_lighttouch.py | 4 +- Gemma_LightTouch/red_green_blue.py | 3 +- Giant_Mechanical_Keyboard/code.py | 52 ++-- Hacking_Ikea_Lamps_With_CPX/CPX_Blink.py | 1 + .../CPX_Blink_Monotonic.py | 1 + .../CPX_Blink_NeoPixel.py | 1 + .../CPX_Left_Rotation_State_Machine.py | 3 + .../CPX_Sjopenna_Remote_Lamp.py | 22 +- .../CPX_Spoka_Generators.py | 23 +- .../CPX_Spoka_Motion_Lamp.py | 23 +- .../CPX_Touch_NeoPixel_Dictionary.py | 10 +- .../CPX_Touch_NeoPixel_if_elif.py | 10 +- Interior_Purse_Light/Interior_Purse_Light.py | 11 +- .../CircuitPlaygroundExpress_AnalogIn.py | 11 +- .../CircuitPlaygroundExpress_AudioFiles.py | 6 +- .../CircuitPlaygroundExpress_AudioSine.py | 15 +- .../CircuitPlaygroundExpress_Blinky.py | 19 +- .../CircuitPlaygroundExpress_Blinky_cpx.py | 3 +- .../CircuitPlaygroundExpress_CapTouch.py | 8 +- .../CircuitPlaygroundExpress_DigitalIO.py | 5 +- .../CircuitPlaygroundExpress_HIDKeyboard.py | 18 +- .../CircuitPlaygroundExpress_LightSensor.py | 21 +- ...ircuitPlaygroundExpress_LightSensor_cpx.py | 5 +- .../CircuitPlaygroundExpress_NeoPixel.py | 27 +- .../CircuitPlaygroundExpress_Neopixel_cpx.py | 14 +- .../CircuitPlaygroundExpress_SoundMeter.py | 36 ++- .../CircuitPlaygroundExpress_Temperature.py | 9 +- ...ircuitPlaygroundExpress_Temperature_cpx.py | 3 +- .../Playground_808.py | 21 +- Introducing_Gemma_M0/Gemma_AnalogIn.py | 9 +- Introducing_Gemma_M0/Gemma_AnalogOut.py | 17 +- Introducing_Gemma_M0/Gemma_CapTouch.py | 5 +- Introducing_Gemma_M0/Gemma_DigitalIO.py | 11 +- Introducing_Gemma_M0/Gemma_DotStar.py | 18 +- Introducing_Gemma_M0/Gemma_HIDkeyboard.py | 22 +- Introducing_Gemma_M0/Gemma_I2CScan.py | 3 +- Introducing_Gemma_M0/Gemma_I2Csi7021.py | 9 +- Introducing_Gemma_M0/Gemma_Logger.py | 3 +- Introducing_Gemma_M0/Gemma_Logger_boot.py | 2 +- Introducing_Gemma_M0/Gemma_NeoPixel.py | 15 +- Introducing_Gemma_M0/Gemma_Touch_DotStar.py | 15 +- Introducing_Gemma_M0/Gemma_UART.py | 12 +- Introducing_Gemma_M0/dht22.py | 8 +- Introducing_Gemma_M0/piezo_manual.py | 18 +- Introducing_Gemma_M0/piezo_simpleio.py | 6 +- Introducing_Gemma_M0/servosweep.py | 13 +- Introducing_Trinket_M0/Trinket_AnalogIn.py | 9 +- Introducing_Trinket_M0/Trinket_AnalogOut.py | 13 +- Introducing_Trinket_M0/Trinket_CapTouch.py | 5 +- Introducing_Trinket_M0/Trinket_SDCardList.py | 24 +- Introducing_Trinket_M0/Trinket_SDlogger.py | 12 +- Introducing_Trinket_M0/Trinket_TouchStar.py | 23 +- Introducing_Trinket_M0/Trinket_UART.py | 10 +- Jewel_Hair_Stick/Jewel_Hair_Stick.py | 86 +++--- .../Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py | 54 ++-- LED_Candles/LED_Candles.py | 119 +++++---- LED_Masquerade_Masks/Audio_Reactive.py | 43 +-- LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py | 40 +-- LED_Trampoline/LED_Trampoline.py | 15 +- Labo_Piano_Light_FX/code.py | 55 ++-- Labo_RC_Car_Light_FX/code.py | 13 +- .../Larson_Scanner_Shades.py | 38 +-- .../Light_Activated_Pixel_Heart.py | 37 +-- .../Logans_Run_Hand_Jewel_LED.py | 42 +-- Minecraft_Gesture_Controller/main.py | 91 ++++--- Morse_Code_Flasher/main.py | 34 ++- Motorized_Turntable/turntable.py | 6 +- .../Mystical_LED_Halloween_Hood.py | 42 +-- NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py | 102 +++---- .../NeoPixel_GoPro_Lens_Light.py | 8 +- .../NeoPixel_Jewel_10_Minute_Necklace.py | 50 ++-- NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py | 21 +- NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py | 32 +-- NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py | 32 +-- NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py | 28 +- NeoPixel_Tiara/NeoPixel_Tiara.py | 49 ++-- NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py | 97 +++---- .../PMS5003_CircuitPython/main.py | 11 +- Pi_Hole_Ad_Blocker/stats.py | 59 +++-- .../Sound_Reactive_NeoPixel_Peace_Pendant.py | 9 +- raver_bandolier/raver_bandolier.py | 77 +++--- 161 files changed, 2250 insertions(+), 1894 deletions(-) diff --git a/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py b/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py index 8a9b15f7c..661532352 100644 --- a/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py +++ b/3D_Printed_Guardian_Sword/3D_Printed_Guardian_Sword.py @@ -1,17 +1,18 @@ # 3D_Printed_Guardian_Sword # https://learn.adafruit.com/breath-of-the-wild-guardian-sword-led-3d-printed -import board -import neopixel import time -pin = board.D4 # DIGITAL IO pin for NeoPixel OUTPUT from GEMMA -pixel_count = 93 # number of neopixels -delayval = .01 # 10 ms delay +import board +import neopixel -APIXELS = 14 # number of first orange pixels -BPIXELS = 84 # number of blue pixels -CPIXELS = 93 # second orange pixels +pin = board.D4 # DIGITAL IO pin for NeoPixel OUTPUT from GEMMA +pixel_count = 93 # number of neopixels +delayval = .01 # 10 ms delay + +APIXELS = 14 # number of first orange pixels +BPIXELS = 84 # number of blue pixels +CPIXELS = 93 # second orange pixels # initialize neopixels pixels = neopixel.NeoPixel(pin, pixel_count, brightness=1, auto_write=False) diff --git a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py index 61dc57bd3..f6b3ab4c2 100644 --- a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py +++ b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py @@ -27,27 +27,27 @@ # Modified fromhere code by Greg Shakar # Ported to Circuit Python by Mikey Sklar +import time + import board import neopixel -import time from analogio import AnalogIn -import array -n_pixels = 16 # Number of pixels you are using -mic_pin = AnalogIn(board.A1) # Microphone is attached to this analog pin -led_pin = board.D1 # NeoPixel LED strand is connected to this pin -sample_window = .1 # Sample window for average level -peak_hang = 24 # Time of pause before peak dot falls -peak_fall = 4 # Rate of falling peak dot -input_floor = 10 # Lower range of analogRead input +n_pixels = 16 # Number of pixels you are using +mic_pin = AnalogIn(board.A1) # Microphone is attached to this analog pin +led_pin = board.D1 # NeoPixel LED strand is connected to this pin +sample_window = .1 # Sample window for average level +peak_hang = 24 # Time of pause before peak dot falls +peak_fall = 4 # Rate of falling peak dot +input_floor = 10 # Lower range of analogRead input # Max range of analogRead input, the lower the value the more sensitive (1023 = max) input_ceiling = 300 -peak = 16 # Peak level of column; used for falling dots +peak = 16 # Peak level of column; used for falling dots sample = 0 -dotcount = 0 # Frame counter for peak dot -dothangcount = 0 # Frame counter for holding peak dot +dotcount = 0 # Frame counter for peak dot +dothangcount = 0 # Frame counter for holding peak dot strip = neopixel.NeoPixel(led_pin, n_pixels, brightness=1, auto_write=False) @@ -58,13 +58,13 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) def remapRange(value, leftMin, leftMax, rightMin, rightMax): @@ -125,18 +125,17 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): # -the math for all other cases # i.e. negative numbers seems to work out fine if (originalmin > originalmax): - return(0) + return (0) if (invflag == 0): rangedvalue = (pow(normalizedcurval, curve) * newrange) + newbegin - else: # invert the ranges + else: # invert the ranges rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange) - return(rangedvalue) + return (rangedvalue) def drawLine(fromhere, to): - fromheretemp = 0 if (fromhere > to): @@ -150,8 +149,8 @@ def drawLine(fromhere, to): while True: - time_start = time.monotonic() # current time used for sample window - peaktopeak = 0 # peak-to-peak level + time_start = time.monotonic() # current time used for sample window + peaktopeak = 0 # peak-to-peak level signalmax = 0 signalmin = 1023 c = 0 @@ -163,12 +162,12 @@ while True: # convert to arduino 10-bit [1024] fromhere 16-bit [65536] sample = mic_pin.value / 64 - if (sample < 1024): # toss out spurious readings + if (sample < 1024): # toss out spurious readings if (sample > signalmax): - signalmax = sample # save just the max levels + signalmax = sample # save just the max levels elif (sample < signalmin): - signalmin = sample # save just the min levels + signalmin = sample # save just the min levels peaktopeak = signalmax - signalmin # max - min = peak-peak amplitude @@ -180,10 +179,10 @@ while True: c = fscale(input_floor, input_ceiling, (n_pixels - 1), 0, peaktopeak, 2) if (c < peak): - peak = c # keep dot on top - dothangcount = 0 # make the dot hang before falling + peak = c # keep dot on top + dothangcount = 0 # make the dot hang before falling - if (c <= n_pixels): # fill partial column with off pixels + if (c <= n_pixels): # fill partial column with off pixels drawLine(n_pixels, n_pixels - int(c)) # Set the peak dot to match the rainbow gradient @@ -192,8 +191,8 @@ while True: strip.write() # Frame based peak dot animation - if(dothangcount > peak_hang): # Peak pause length - if(++dotcount >= peak_fall): # Fall rate + if (dothangcount > peak_hang): # Peak pause length + if (++dotcount >= peak_fall): # Fall rate peak += 1 dotcount = 0 else: diff --git a/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py b/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py index aae389c44..d5d8bb166 100644 --- a/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py +++ b/3D_Printed_NeoPixel_Gas_Mask/3D_Printed_NeoPixel_Gas_Mask.py @@ -1,26 +1,28 @@ +import time + import board import neopixel -import time + try: import urandom as random # for v1.0 API support except ImportError: import random -numpix = 24 # Number of NeoPixels +numpix = 24 # Number of NeoPixels pixpin = board.D0 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.3) mode = 0 # Current animation effect offset = 0 # Position of spinner animation -color = [255, 0, 0] # RGB color - red +color = [255, 0, 0] # RGB color - red prevtime = time.monotonic() # Time of last animation mode switch while True: # Loop forever... if mode == 0: # Random sparkles - lights just one LED at a time i = random.randint(0, numpix - 1) # Choose random pixel - strip[i] = color # Set it to current color - strip.write() # Refresh LED states + strip[i] = color # Set it to current color + strip.write() # Refresh LED states # Set same pixel to "off" color now but DON'T refresh... # it stays on for now...bot this and the next random # pixel will be refreshed on the next pass. @@ -35,22 +37,22 @@ while True: # Loop forever... # types, so we get the reversed motion on #2 for free). for i in range(numpix): # For each LED... if ((offset + i) & 7) < 2: # 2 pixels out of 8... - strip[i] = color # are set to current color + strip[i] = color # are set to current color else: strip[i] = [0, 0, 0] # other pixels are off - strip.write() # Refresh LED states + strip.write() # Refresh LED states time.sleep(0.04) # 40 millisecond delay - offset += 1 # Shift animation by 1 pixel on next frame + offset += 1 # Shift animation by 1 pixel on next frame if offset >= 8: offset = 0 # Additional animation modes could be added here! - t = time.monotonic() # Current time in seconds - if (t - prevtime) >= 8: # Every 8 seconds... - mode += 1 # Advance to next mode - if mode > 1: # End of modes? - mode = 0 # Start over from beginning + t = time.monotonic() # Current time in seconds + if (t - prevtime) >= 8: # Every 8 seconds... + mode += 1 # Advance to next mode + if mode > 1: # End of modes? + mode = 0 # Start over from beginning # Rotate color R->G->B color = [color[2], color[0], color[1]] strip.fill([0, 0, 0]) # Turn off all pixels - prevtime = t # Record time of last mode change + prevtime = t # Record time of last mode change diff --git a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py index 96a04c8f0..62142e369 100644 --- a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py +++ b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py @@ -8,9 +8,11 @@ # unless you # don't like the preset animations or find a # major bug, you don't need tochange anything here # +import time + import board import neopixel -import time + try: import urandom as random # for v1.0 API support except ImportError: @@ -18,37 +20,37 @@ except ImportError: from analogio import AnalogIn # available actions -ACT_NOP = 0x00 # all leds off, do nothing -ACT_SIMPLE_RING = 0x01 # all leds on -ACT_CYCLING_RING_ACLK = 0x02 # anti clockwise cycling colors -ACT_CYCLING_RING_CLKW = 0x04 # clockwise cycling colors -ACT_WHEEL_ACLK = 0x08 # anti clockwise spinning wheel -ACT_WHEEL_CLKW = 0x10 # clockwise spinning wheel -ACT_SPARKLING_RING = 0x20 # sparkling effect +ACT_NOP = 0x00 # all leds off, do nothing +ACT_SIMPLE_RING = 0x01 # all leds on +ACT_CYCLING_RING_ACLK = 0x02 # anti clockwise cycling colors +ACT_CYCLING_RING_CLKW = 0x04 # clockwise cycling colors +ACT_WHEEL_ACLK = 0x08 # anti clockwise spinning wheel +ACT_WHEEL_CLKW = 0x10 # clockwise spinning wheel +ACT_SPARKLING_RING = 0x20 # sparkling effect -numpix = 16 # total number of NeoPixels -pixel_output = board.D0 # pin where NeoPixels are connected -analog_input = board.A0 # needed to seed the random generator +numpix = 16 # total number of NeoPixels +pixel_output = board.D0 # pin where NeoPixels are connected +analog_input = board.A0 # needed to seed the random generator strip = neopixel.NeoPixel(pixel_output, numpix, brightness=.3, auto_write=False) # available color generation methods -COL_RANDOM = 0x40 # colors will be generated randomly -COL_SPECTRUM = 0x80 # colors will be set as cyclic spectral wipe +COL_RANDOM = 0x40 # colors will be generated randomly +COL_SPECTRUM = 0x80 # colors will be set as cyclic spectral wipe # specifiyng the action list # the action's overall duration in milliseconds (be careful not action_duration = 0 # to use values > 2^16-1 - roughly one minute :-) -action_and_color_gen = 1 # the color generation method +action_and_color_gen = 1 # the color generation method # the duration of each action step rsp. the delay of the main action_step_duration = 2 # loop in milliseconds - thus, controls the action speed (be # careful not to use values > 2^16-1 - roughly one minute :-) -color_granularity = 3 # controls the increment of the R, G, and B portions of the +color_granularity = 3 # controls the increment of the R, G, and B portions of the # rsp. color. 1 means the increment is 0,1,2,3,..., 10 means # the increment is 0,10,20,... don't use values > 255, and note # that even values > 127 wouldn't make much sense... @@ -96,63 +98,63 @@ spectrum_part = 0 # action action name & action step color color change # duration color generation method duration granularity interval theactionlist = [ - [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], - [2, ACT_CYCLING_RING_CLKW | COL_RANDOM, - 0.02, 1, 0.005], - [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], - [2, ACT_CYCLING_RING_ACLK | COL_RANDOM, - 0.02, 1, 0.005], - [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], - [2.5, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.25, 20, 0.020], - [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.50, 1, 0.020], - [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.075, 1, 0.020], - [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.100, 1, 0.020], - [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.125, 1, 0.020], - [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.150, 1, 0.050], - [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.175, 1, 0.100], - [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.200, 1, 0.200], - [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.225, 1, 0.250], - [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, - 0.250, 1, 0.350], - [30, ACT_SIMPLE_RING | COL_SPECTRUM, - 0.050, 1, 0.010], - [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.010, 1, 0.010], - [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.015, 1, 0.020], - [2, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.025, 1, 0.030], - [1, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.050, 1, 0.040], - [1, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.075, 1, 0.040], - [1, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.100, 1, 0.050], - [.500, ACT_WHEEL_ACLK | COL_SPECTRUM, - 0.125, 1, 0.060], - [.500, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.125, 5, 0.050], - [1, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.100, 10, 0.040], - [1.5, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.075, 15, 0.030], - [2, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.050, 20, 0.020], - [2.5, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.025, 25, 0.010], - [3, ACT_WHEEL_CLKW | COL_SPECTRUM, - 0.010, 30, 0.005], - [5, ACT_SPARKLING_RING | COL_RANDOM, 0.010, 25, 1], - [5, ACT_NOP, 0, 0, 0] + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2, ACT_CYCLING_RING_CLKW | COL_RANDOM, + 0.02, 1, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2, ACT_CYCLING_RING_ACLK | COL_RANDOM, + 0.02, 1, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], + [2.5, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.25, 20, 0.020], + [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.50, 1, 0.020], + [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.075, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.100, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.125, 1, 0.020], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.150, 1, 0.050], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.175, 1, 0.100], + [.500, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.200, 1, 0.200], + [.750, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.225, 1, 0.250], + [1, ACT_CYCLING_RING_CLKW | COL_SPECTRUM, + 0.250, 1, 0.350], + [30, ACT_SIMPLE_RING | COL_SPECTRUM, + 0.050, 1, 0.010], + [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.010, 1, 0.010], + [2.5, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.015, 1, 0.020], + [2, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.025, 1, 0.030], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.050, 1, 0.040], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.075, 1, 0.040], + [1, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.100, 1, 0.050], + [.500, ACT_WHEEL_ACLK | COL_SPECTRUM, + 0.125, 1, 0.060], + [.500, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.125, 5, 0.050], + [1, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.100, 10, 0.040], + [1.5, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.075, 15, 0.030], + [2, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.050, 20, 0.020], + [2.5, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.025, 25, 0.010], + [3, ACT_WHEEL_CLKW | COL_SPECTRUM, + 0.010, 30, 0.005], + [5, ACT_SPARKLING_RING | COL_RANDOM, 0.010, 25, 1], + [5, ACT_NOP, 0, 0, 0] ] @@ -161,7 +163,7 @@ def nextspectrumcolor(): # spectral wipe from green to red if (spectrum_part == 2): - color = (color_idx, 0, 255-color_idx) + color = (color_idx, 0, 255 - color_idx) color_idx += curr_color_granularity if (color_idx > 255): spectrum_part = 0 @@ -211,7 +213,6 @@ def nextcolor(): def setup(): - # fingers corssed, the seeding makes sense to really get random colors... apin = AnalogIn(analog_input) random.seed(apin.value) diff --git a/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py b/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py index 37ec34dd1..33efcf821 100644 --- a/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py +++ b/3D_Printed_Unicorn_Horn/3D_Printed_Unicorn_Horn.py @@ -1,7 +1,8 @@ -from digitalio import DigitalInOut, Direction +import time + import board import neopixel -import time +from digitalio import DigitalInOut, Direction pixpin = board.D1 numpix = 8 @@ -18,17 +19,17 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): - for j in range(255*5): + for j in range(255 * 5): for i in range(len(strip)): idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) @@ -38,7 +39,7 @@ def rainbow_cycle(wait): def rainbow(wait): for j in range(255): for i in range(len(strip)): - idx = int(i+j) + idx = int(i + j) strip[i] = wheel(idx & 255) diff --git a/Adafruit_LED_Sequins/Adafruit_LED_Sequins.py b/Adafruit_LED_Sequins/Adafruit_LED_Sequins.py index 3eb9f9ff2..2be02d9a7 100644 --- a/Adafruit_LED_Sequins/Adafruit_LED_Sequins.py +++ b/Adafruit_LED_Sequins/Adafruit_LED_Sequins.py @@ -1,24 +1,24 @@ +import time + import board import pulseio -import time from digitalio import DigitalInOut, Direction # PWM (fading) LEDs are connected on D0 (PWM not avail on D1) -pwm_leds = board.D0 +pwm_leds = board.D0 pwm = pulseio.PWMOut(pwm_leds, frequency=1000, duty_cycle=0) # digital LEDs connected on D2 digital_leds = DigitalInOut(board.D2) digital_leds.direction = Direction.OUTPUT - -brightness = 0 # how bright the LED is -fade_amount = 1285 # 2% steping of 2^16 -counter = 0 # counter to keep track of cycles +brightness = 0 # how bright the LED is +fade_amount = 1285 # 2% steping of 2^16 +counter = 0 # counter to keep track of cycles while True: # And send to LED as PWM level - pwm.duty_cycle = brightness + pwm.duty_cycle = brightness # change the brightness for next time through the loop: brightness = brightness + fade_amount @@ -26,10 +26,10 @@ while True: print(brightness) # reverse the direction of the fading at the ends of the fade: - if ( brightness <= 0 ): + if brightness <= 0: fade_amount = -fade_amount counter += 1 - elif ( brightness >= 65535 ): + elif brightness >= 65535: fade_amount = -fade_amount counter += 1 @@ -40,7 +40,7 @@ while True: # checking the modulo of the counter. # the modulo function gives you the remainder of # the division of two numbers: - if ( counter % 4 == 0 ): - digital_leds.value = True + if counter % 4 == 0: + digital_leds.value = True else: digital_leds.value = False diff --git a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py index 55c10edb3..c15318bf8 100644 --- a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py +++ b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py @@ -1,24 +1,23 @@ +import adafruit_fancyled.adafruit_fancyled as fancy import board import neopixel -import time -from digitalio import DigitalInOut, Direction, Pull -import adafruit_fancyled.adafruit_fancyled as fancy +from digitalio import DigitalInOut, Direction, Pull -led_pin = board.D1 # which pin your pixels are connected to -num_leds = 78 # how many LEDs you have -brightness = 1.0 # 0-1, higher number is brighter -saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color -steps = 0.01 # how wide the bands of color are. -offset = 0 # cummulative steps -fadeup = True # start with fading up - increase steps until offset reaches 1 -index = 8 # midway color selection -blend = True # color blending between palette indices +led_pin = board.D1 # which pin your pixels are connected to +num_leds = 78 # how many LEDs you have +brightness = 1.0 # 0-1, higher number is brighter +saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color +steps = 0.01 # how wide the bands of color are. +offset = 0 # cummulative steps +fadeup = True # start with fading up - increase steps until offset reaches 1 +index = 8 # midway color selection +blend = True # color blending between palette indices # initialize list with all pixels off -palette = [ 0 ] * num_leds +palette = [0] * num_leds # Declare a NeoPixel object on led_pin with num_leds as pixels -# No auto-write. +# No auto-write. # Set brightness to max. # We will be using FancyLED's brightness control. strip = neopixel.NeoPixel(led_pin, num_leds, brightness=1, auto_write=False) @@ -28,59 +27,58 @@ button = DigitalInOut(board.D2) button.direction = Direction.INPUT button.pull = Pull.UP prevkeystate = False -ledmode = 0 # button press counter, switch color palettes +ledmode = 0 # button press counter, switch color palettes # FancyLED allows for assigning a color palette using these formats: # * The first (5) palettes here are mixing between 2-elements # * The last (3) palettes use a format identical to the FastLED Arduino Library # see FastLED - colorpalettes.cpp -forest = [ fancy.CRGB( 0, 255, 0 ), # green - fancy.CRGB( 255, 255, 0) ] # yellow +forest = [fancy.CRGB(0, 255, 0), # green + fancy.CRGB(255, 255, 0)] # yellow -ocean = [ fancy.CRGB( 0, 0, 255 ), # blue - fancy.CRGB( 0, 255, 0 ) ] # green +ocean = [fancy.CRGB(0, 0, 255), # blue + fancy.CRGB(0, 255, 0)] # green -purple = [ fancy.CRGB( 160, 32, 240 ), # purple - fancy.CRGB( 238, 130, 238 ) ] # violet +purple = [fancy.CRGB(160, 32, 240), # purple + fancy.CRGB(238, 130, 238)] # violet -all_colors = [ fancy.CRGB( 0, 0, 0 ), # black - fancy.CRGB( 255, 255, 255 ) ] # white +all_colors = [fancy.CRGB(0, 0, 0), # black + fancy.CRGB(255, 255, 255)] # white -washed_out = [ fancy.CRGB( 0, 0, 0 ), # black - fancy.CRGB( 255, 0, 255 ) ] # purple +washed_out = [fancy.CRGB(0, 0, 0), # black + fancy.CRGB(255, 0, 255)] # purple -rainbow = [ 0xFF0000, 0xD52A00, 0xAB5500, 0xAB7F00, - 0xABAB00, 0x56D500, 0x00FF00, 0x00D52A, - 0x00AB55, 0x0056AA, 0x0000FF, 0x2A00D5, - 0x5500AB, 0x7F0081, 0xAB0055, 0xD5002B ] +rainbow = [0xFF0000, 0xD52A00, 0xAB5500, 0xAB7F00, + 0xABAB00, 0x56D500, 0x00FF00, 0x00D52A, + 0x00AB55, 0x0056AA, 0x0000FF, 0x2A00D5, + 0x5500AB, 0x7F0081, 0xAB0055, 0xD5002B] -rainbow_stripe= [ 0xFF0000, 0x000000, 0xAB5500, 0x000000, - 0xABAB00, 0x000000, 0x00FF00, 0x000000, - 0x00AB55, 0x000000, 0x0000FF, 0x000000, - 0x5500AB, 0x000000, 0xAB0055, 0x000000 ] +rainbow_stripe = [0xFF0000, 0x000000, 0xAB5500, 0x000000, + 0xABAB00, 0x000000, 0x00FF00, 0x000000, + 0x00AB55, 0x000000, 0x0000FF, 0x000000, + 0x5500AB, 0x000000, 0xAB0055, 0x000000] -heat_colors = [ 0x330000, 0x660000, 0x990000, 0xCC0000, 0xFF0000, - 0xFF3300, 0xFF6600, 0xFF9900, 0xFFCC00, 0xFFFF00, - 0xFFFF33, 0xFFFF66, 0xFFFF99, 0xFFFFCC ] +heat_colors = [0x330000, 0x660000, 0x990000, 0xCC0000, 0xFF0000, + 0xFF3300, 0xFF6600, 0xFF9900, 0xFFCC00, 0xFFFF00, + 0xFFFF33, 0xFFFF66, 0xFFFF99, 0xFFFFCC] def wheel(pos): - # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) + def remapRange(value, leftMin, leftMax, rightMin, rightMax): - # this remaps a value from original (left) range to new (right) range # Figure out how 'wide' each range is leftSpan = leftMax - leftMin @@ -89,66 +87,67 @@ def remapRange(value, leftMin, leftMax, rightMin, rightMax): # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) -def shortkeypress(color_palette): +def shortkeypress(color_palette): color_palette += 1 - if ( color_palette > 6): + if (color_palette > 6): color_palette = 1 - return ( color_palette ) + return (color_palette) -while True: + +while True: # check for button press currkeystate = button.value # button press, move to next pattern - if ( ( prevkeystate == False ) and ( currkeystate == True ) ): + if ((prevkeystate == False) and (currkeystate == True)): ledmode = shortkeypress(ledmode) # save button press state prevkeystate = currkeystate # Fire Colors [ HEAT ] - if ( ledmode == 1 ): + if (ledmode == 1): palette = heat_colors # Forest - elif ( ledmode == 2 ): + elif (ledmode == 2): palette = forest # Ocean - elif ( ledmode == 3 ): + elif (ledmode == 3): palette = ocean # Purple Lovers - elif ( ledmode == 4 ): + elif (ledmode == 4): palette = purple - + # All the colors! - elif ( ledmode == 5 ): + elif (ledmode == 5): palette = rainbow # Rainbow stripes - elif ( ledmode == 6 ): + elif (ledmode == 6): palette = rainbow_stripe # All the colors except the greens, washed out - elif ( ledmode == 7 ): + elif (ledmode == 7): palette = washed_out - + for i in range(num_leds): color = fancy.palette_lookup(palette, offset + i / num_leds) color = fancy.gamma_adjust(color, brightness=brightness) strip[i] = color.pack() strip.show() - if ( fadeup ): + if (fadeup): offset += steps - if ( offset >= 1 ): + if (offset >= 1): fadeup = False - else: + else: offset -= steps - if ( offset <= 0 ): + if (offset <= 0): fadeup = True diff --git a/Annoy_O_Matic/main.py b/Annoy_O_Matic/main.py index c543f12fa..7914fd5e7 100644 --- a/Annoy_O_Matic/main.py +++ b/Annoy_O_Matic/main.py @@ -1,9 +1,10 @@ # Annoy-O-Matic Sound Prank Device # choose from a variety of sounds and timings to drive your victim bonkers -import pulseio -import board import time +import board +import pulseio + piezo = pulseio.PWMOut(board.D0, duty_cycle=0, frequency=440, variable_frequency=True) @@ -35,24 +36,26 @@ ringtone_tempo = 1.6 # suggested Nokia 0.9 , iPhone 1.3 , Rickroll 2.0 def annoy_beep(frequency, length, repeat, rest, interval): for r in range(repeat): piezo.frequency = frequency # 2600 is a nice choice - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(length) # sound on piezo.duty_cycle = 0 # off time.sleep(rest) time.sleep(interval) # wait time until next beep + def annoy_doorbell(interval): piezo.frequency = 740 - piezo.duty_cycle = 65536//2 + piezo.duty_cycle = 65536 // 2 time.sleep(0.85) piezo.duty_cycle = 0 time.sleep(0.05) piezo.frequency = 588 - piezo.duty_cycle = 65536//2 + piezo.duty_cycle = 65536 // 2 time.sleep(1.25) piezo.duty_cycle = 0 time.sleep(interval) + def annoy_ringtone(ringtone, tempo, interval): # ringtone 1: Nokia # ringtone 2: Apple iPhone @@ -135,7 +138,7 @@ def annoy_ringtone(ringtone, tempo, interval): C6 = C5 * 2 Cs6 = Cs5 * 2 Db6 = Db5 * 2 - D6 = D5 * 2 + D6 = D5 * 2 Ds6 = Ds5 * 2 Eb6 = Eb5 * 2 E6 = E5 * 2 @@ -162,7 +165,7 @@ def annoy_ringtone(ringtone, tempo, interval): for n in range(len(nokia_ringtone)): piezo.frequency = (nokia_ringtone[n][0]) - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(nokia_ringtone[n][1]) # note duration piezo.duty_cycle = 0 # off time.sleep(0.01) @@ -178,52 +181,55 @@ def annoy_ringtone(ringtone, tempo, interval): for n in range(len(iPhone_ringtone)): piezo.frequency = (iPhone_ringtone[n][0]) - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(iPhone_ringtone[n][1]) # note duration piezo.duty_cycle = 0 # off time.sleep(0.01) if ringtone == 3: # Rickroll - rick_ringtone = [[A3, sixteenth_note], [B3, sixteenth_note], - [D4, sixteenth_note], [B3, sixteenth_note], - [Fs4, dotted_eighth_note], [Fs4, sixteenth_note], - [Fs4, eighth_note], [E4, eighth_note], - [E4, quarter_note], - [A3, sixteenth_note], [B3, sixteenth_note], - [Cs4, sixteenth_note], [A3, sixteenth_note], - [E4, dotted_eighth_note], [E4, sixteenth_note], - [E4, eighth_note], [D4, eighth_note], - [D4, sixteenth_note], [Cs4, sixteenth_note], - [B3, eighth_note]] + rick_ringtone = [[A3, sixteenth_note], [B3, sixteenth_note], + [D4, sixteenth_note], [B3, sixteenth_note], + [Fs4, dotted_eighth_note], [Fs4, sixteenth_note], + [Fs4, eighth_note], [E4, eighth_note], + [E4, quarter_note], + [A3, sixteenth_note], [B3, sixteenth_note], + [Cs4, sixteenth_note], [A3, sixteenth_note], + [E4, dotted_eighth_note], [E4, sixteenth_note], + [E4, eighth_note], [D4, eighth_note], + [D4, sixteenth_note], [Cs4, sixteenth_note], + [B3, eighth_note]] for n in range(len(rick_ringtone)): piezo.frequency = (rick_ringtone[n][0]) - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(rick_ringtone[n][1]) # note duration piezo.duty_cycle = 0 # off time.sleep(0.035) time.sleep(interval) + def annoy_crickets(repeat, interval): for i in range(repeat): for r in range(6): piezo.frequency = 8000 # 2600 is a nice choice - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(0.02) # sound on piezo.duty_cycle = 0 # off time.sleep(0.05) time.sleep(0.2) time.sleep(interval) # wait time until next beep + def annoy_teen_tone(interval): piezo.frequency = 17400 - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(10) piezo.duty_cycle = 0 time.sleep(interval) + while True: if annoy_mode is 1: annoy_beep(frequency, length, repeat, rest, interval) diff --git a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py index dd6fcb61d..a0d2e53f5 100644 --- a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py +++ b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py @@ -1,8 +1,9 @@ -import digitalio -from board import * import time + +import digitalio from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode +from board import * # A simple neat keyboard demo in circuitpython diff --git a/Breath_Mask/Breath_Mask.py b/Breath_Mask/Breath_Mask.py index 205cae909..052a5c4d4 100644 --- a/Breath_Mask/Breath_Mask.py +++ b/Breath_Mask/Breath_Mask.py @@ -1,8 +1,8 @@ import time -import board -import busio import adafruit_CCS811 +import board +import busio import neopixel # i2c interface for the gas sensor @@ -13,11 +13,11 @@ ccs = adafruit_CCS811.CCS811(i2c_bus) # 1 - Temperature - Circuit Playground Built-In LEDs # 2 - Total Volatile Organic Compounds [strip] # 3 - Co2 Output - NeoPixel [strip] -num_leds = 8 +num_leds = 8 temperature_pix = neopixel.NeoPixel(board.NEOPIXEL, num_leds, brightness=.1) tvoc_pix = neopixel.NeoPixel(board.A1, num_leds, bpp=4, brightness=.1) co2_pix = neopixel.NeoPixel(board.A2, num_leds, bpp=4, brightness=.1) -led_draw = .05 # delay for LED pixel turn on/off +led_draw = .05 # delay for LED pixel turn on/off # wait for the sensor to be ready and calibrate the thermistor while not ccs.data_ready: @@ -25,63 +25,76 @@ while not ccs.data_ready: temp = ccs.temperature ccs.temp_offset = temp - 25.0 -# clear all LEDs for breathing effect + +# clear all LEDs for breathing effect + + def clear_pix(delay): for i in range(0, num_leds): - temperature_pix[i] = (0,0,0) - co2_pix[i] = (0,0,0,0) - tvoc_pix[i] = (0,0,0,0) + temperature_pix[i] = (0, 0, 0) + co2_pix[i] = (0, 0, 0, 0) + tvoc_pix[i] = (0, 0, 0, 0) time.sleep(delay) - + + # Show Carbon Dioxide on a NeoPixel Strip + + def co2_led_meter(): co2_floor = 400 co2_ceiling = 8192 - + # Map CO2 range to 8 LED NeoPixel Stick - co2_range = co2_ceiling - co2_floor + co2_range = co2_ceiling - co2_floor co2_led_steps = co2_range / num_leds - co2_leds = int( (ccs.eCO2 - co2_floor ) / co2_led_steps) + co2_leds = int((ccs.eCO2 - co2_floor) / co2_led_steps) # Insert Colors - for i in range(0, (co2_leds - 1) ): - co2_pix[i] = (255,0,255,0) + for i in range(0, (co2_leds - 1)): + co2_pix[i] = (255, 0, 255, 0) time.sleep(led_draw) + # Show Total Volatile Organic Compounds on a NeoPixel Strip + + def tvoc_led_meter(): tvoc_floor = 0 tvoc_ceiling = 1187 - + # Map CO2 range to 8 LED NeoPixel Stick - tvoc_range = tvoc_ceiling - tvoc_floor + tvoc_range = tvoc_ceiling - tvoc_floor tvoc_led_steps = tvoc_range / num_leds tvoc_leds = int(ccs.TVOC / tvoc_led_steps) # Insert Colors - for i in range(0, (tvoc_leds - 1) ): - tvoc_pix[i] = (0,0,255,0) + for i in range(0, (tvoc_leds - 1)): + tvoc_pix[i] = (0, 0, 255, 0) time.sleep(led_draw) + # Show Temperature on Circuit Playground built-in NeoPixels + + def temp_led_meter(): temp_floor = 23 temp_ceiling = 36 - + # Map temperature range to 8 LEDs on Circuit Playground - temp_range = temp_ceiling - temp_floor + temp_range = temp_ceiling - temp_floor temp_led_steps = temp_range / num_leds - temp_leds = int( (ccs.temperature - temp_floor ) / temp_led_steps) + temp_leds = int((ccs.temperature - temp_floor) / temp_led_steps) # Insert Colors - for i in range(0, (temp_leds - 1) ): - temperature_pix[i] = (255,255,0) + for i in range(0, (temp_leds - 1)): + temperature_pix[i] = (255, 255, 0) time.sleep(led_draw) + while True: # print to console # - co2 - # - total voltatile organic compounds + # - total voltatile organic compounds # - temperature in celsius print("CO2: ", ccs.eCO2, " TVOC:", ccs.TVOC, " temp:", ccs.temperature) diff --git a/Breath_Tester/Breath_Tester.py b/Breath_Tester/Breath_Tester.py index ce31ad816..d0855a0af 100644 --- a/Breath_Tester/Breath_Tester.py +++ b/Breath_Tester/Breath_Tester.py @@ -1,7 +1,8 @@ import time + +import adafruit_sgp30 import board import busio -import adafruit_sgp30 i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) @@ -13,26 +14,29 @@ sgp30.set_iaq_baseline(0x8973, 0x8aae) # highest tVOC recorded in 30 seconds highest_breath_result = 0 -def warmup_message(): - warmup_time = 20 +def warmup_message(): + warmup_time = 20 warmup_counter = 0 - co2eq, tvoc = sgp30.iaq_measure() # initial read required to get sensor going + # initial read required to get sensor going + co2eq, tvoc = sgp30.iaq_measure() print() print("Warming Up [%d seconds]..." % warmup_time) - while ( warmup_counter <= 20 ): + while (warmup_counter <= 20): print('.', end='') time.sleep(1) warmup_counter += 1 -def get_breath_reading(): - breath_time = 30 # seconds to record breath reading - breath_counter = 0 # one second count up to breath_time value - breath_saves = [0] * ( breath_time + 1 ) # initialize list with empty values +def get_breath_reading(): + breath_time = 30 # seconds to record breath reading + # one second count up to breath_time value + breath_counter = 0 + # initialize list with empty values + breath_saves = [0] * (breath_time + 1) print() print("We will collect breath samples for 30 seconds.") @@ -40,7 +44,7 @@ def get_breath_reading(): input(" *** Press a key when ready. *** ") print() - while ( breath_counter <= breath_time ): + while (breath_counter <= breath_time): co2eq, tvoc = sgp30.iaq_measure() breath_saves[breath_counter] = tvoc print(tvoc, ', ', end='') @@ -48,11 +52,14 @@ def get_breath_reading(): breath_counter += 1 breath_saves = sorted(breath_saves) - highest_breath_result = breath_saves[breath_counter - 1] + highest_breath_result = breath_saves[breath_counter - 1] + + return (highest_breath_result) - return(highest_breath_result) # show the highest reading recorded + + def show_results(highest_breath_result): print() print() @@ -61,6 +68,7 @@ def show_results(highest_breath_result): input("Press any key to test again") print() + # main while True: warmup_message() diff --git a/Chilled_Drinkibot/main.py b/Chilled_Drinkibot/main.py index 5e88f47e4..11972e06a 100644 --- a/Chilled_Drinkibot/main.py +++ b/Chilled_Drinkibot/main.py @@ -1,9 +1,10 @@ # Chilled Drinkibot -from digitalio import DigitalInOut, Direction, Pull -import board import time +import board +from digitalio import DigitalInOut, Direction, Pull + led = DigitalInOut(board.D2) # Button LED led.direction = Direction.OUTPUT @@ -17,7 +18,6 @@ chiller.direction = Direction.OUTPUT pump = DigitalInOut(board.D4) # Pin to control the pump pump.direction = Direction.OUTPUT - chillTime = 5 # How many _minutes_ of cooling pumpTime = 35 # How many seconds of pumping @@ -26,18 +26,18 @@ while True: # we could also just do "led.value = not button.value" ! if button.value: print('not') - led.value = False # turn OFF LED + led.value = False # turn OFF LED chiller.value = False # turn OFF chiller - pump.value = False # turn OFF pump + pump.value = False # turn OFF pump else: print('pressed') - led.value = True # turn ON LED - chiller.value = True # turn ON chiller + led.value = True # turn ON LED + chiller.value = True # turn ON chiller time.sleep(chillTime * 60) # wait chiller time (in seconds) chiller.value = False # turn OFF chiller - pump.value = True # turn ON pump - time.sleep(pumpTime) # wait pump time - pump.value = False # turn OFF pump - led.value = False # turn OFF LED + pump.value = True # turn ON pump + time.sleep(pumpTime) # wait pump time + pump.value = False # turn OFF pump + led.value = False # turn OFF LED time.sleep(0.01) # debounce delay diff --git a/CircuitPy_OTP/main.py b/CircuitPy_OTP/main.py index e596f243b..1b556ed15 100644 --- a/CircuitPy_OTP/main.py +++ b/CircuitPy_OTP/main.py @@ -1,23 +1,22 @@ import time -import machine + +import adafruit_ssd1306 +import bitbangio as io +import board import network import ntptime -import uhashlib import ubinascii -import board -import bitbangio as io -import adafruit_ssd1306 +import uhashlib - -totp = [("Discord ", 'JBSWY3DPEHPK3PXP'), # https://github.com/pyotp/pyotp exmple +totp = [("Discord ", 'JBSWY3DPEHPK3PXP'), # https://github.com/pyotp/pyotp exmple ("Gmail ", 'abcdefghijklmnopqrstuvwxyz234567'), ("Accounts", 'asfdkwefoaiwejfa323nfjkl')] -ssid = 'my_wifi_ssid' +ssid = 'my_wifi_ssid' password = 'my_wifi_password' -TEST = False # if you want to print out the tests the hashers +TEST = False # if you want to print out the tests the hashers ALWAYS_ON = False # Set to true if you never want to go to sleep! -ON_SECONDS = 60 # how long to stay on if not in always_on mode +ON_SECONDS = 60 # how long to stay on if not in always_on mode i2c = io.I2C(board.SCL, board.SDA) oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c) @@ -29,7 +28,7 @@ oled.text('PyTOTP Pal!', 0, 10) oled.text(' <3 adafruit <3 ', 0, 20) oled.show() time.sleep(0.25) - + EPOCH_DELTA = 946684800 # seconds between year 2000 and year 1970 SECS_DAY = 86400 @@ -52,6 +51,7 @@ def HMAC(k, m): outer_message = KEY_OUTER + SHA1(inner_message).digest() return SHA1(outer_message) + if TEST: KEY = b'abcd' MESSAGE = b'efgh' @@ -59,13 +59,16 @@ if TEST: print("HMAC test: ", ubinascii.hexlify(HMAC(KEY, MESSAGE).digest())) # should be e5dbcf9263188f9fce90df572afeb39b66b27198 + # Base32 decoder, since base64 lib wouldnt fit + + def base32_decode(encoded): missing_padding = len(encoded) % 8 if missing_padding != 0: encoded += '=' * (8 - missing_padding) encoded = encoded.upper() - chunks = [encoded[i:i+8] for i in range(0, len(encoded), 8)] + chunks = [encoded[i:i + 8] for i in range(0, len(encoded), 8)] out = [] for chunk in chunks: @@ -88,17 +91,21 @@ def base32_decode(encoded): # great! we have enough to extract a byte if bits >= 8: bits -= 8 - byte = bitbuff >> bits # grab top 8 bits - bitbuff &= ~(0xFF << bits) # and clear them - out.append(byte) # store what we got + byte = bitbuff >> bits # grab top 8 bits + bitbuff &= ~(0xFF << bits) # and clear them + out.append(byte) # store what we got return out + if TEST: print("===========================================") print("Base32 test: ", bytes(base32_decode("IFSGCZTSOVUXIIJB"))) # should be "Adafruit!!" + # Turns an integer into a padded-with-0x0 bytestr + + def int_to_bytestring(i, padding=8): result = [] while i != 0: @@ -107,12 +114,16 @@ def int_to_bytestring(i, padding=8): result = [0] * (padding - len(result)) + result return bytes(result) + # HMAC -> OTP generator, pretty much same as # https://github.com/pyotp/pyotp/blob/master/src/pyotp/otp.py + + def generate_otp(input, secret, digits=6): if input < 0: raise ValueError('input must be positive integer') - hmac_hash = bytearray(HMAC(bytes(base32_decode(secret)), int_to_bytestring(input)).digest()) + hmac_hash = bytearray( + HMAC(bytes(base32_decode(secret)), int_to_bytestring(input)).digest()) offset = hmac_hash[-1] & 0xf code = ((hmac_hash[offset] & 0x7f) << 24 | (hmac_hash[offset + 1] & 0xff) << 16 | @@ -121,9 +132,10 @@ def generate_otp(input, secret, digits=6): str_code = str(code % 10 ** digits) while len(str_code) < digits: str_code = '0' + str_code - + return str_code + print("===========================================") # Set up networking @@ -168,23 +180,23 @@ print("Unix time: ", t) mono_time = int(time.monotonic()) print("Monotonic time", mono_time) -countdown = ON_SECONDS # how long to stay on if not in always_on mode +countdown = ON_SECONDS # how long to stay on if not in always_on mode while ALWAYS_ON or (countdown > 0): # Calculate current time based on NTP + monotonic - unix_time = t - mono_time + int(time.monotonic()) + unix_time = t - mono_time + int(time.monotonic()) print("Unix time: ", unix_time) # Clear the screen oled.fill(0) y = 0 # We can do up to 3 per line on the Feather OLED - for name,secret in totp: - otp = generate_otp(unix_time//30, secret) - print(name + " OTP output: ", otp) # serial debugging output - oled.text(name + ": "+ str(otp), 0, y) # display name & OTP on OLED - y += 10 # Go to next line on OLED + for name, secret in totp: + otp = generate_otp(unix_time // 30, secret) + print(name + " OTP output: ", otp) # serial debugging output + oled.text(name + ": " + str(otp), 0, y) # display name & OTP on OLED + y += 10 # Go to next line on OLED # We'll display a little bar that 'counts down' how many seconds you have left - oled.framebuf.line(0,31, 128 - (unix_time % 30)*4,31, True) + oled.framebuf.line(0, 31, 128 - (unix_time % 30) * 4, 31, True) oled.show() # We'll update every 1/4 second, we can hash very fast so its no biggie! countdown -= 0.25 diff --git a/CircuitPython_Essentials/CircuitPython_AnalogIn.py b/CircuitPython_Essentials/CircuitPython_AnalogIn.py index 8cbd78d86..4a1418ed3 100644 --- a/CircuitPython_Essentials/CircuitPython_AnalogIn.py +++ b/CircuitPython_Essentials/CircuitPython_AnalogIn.py @@ -1,8 +1,9 @@ # CircuitPython AnalogIn Demo import time -from analogio import AnalogIn + import board +from analogio import AnalogIn analog_in = AnalogIn(board.A1) diff --git a/CircuitPython_Essentials/CircuitPython_AnalogOut.py b/CircuitPython_Essentials/CircuitPython_AnalogOut.py index 45368fa67..43f74338b 100644 --- a/CircuitPython_Essentials/CircuitPython_AnalogOut.py +++ b/CircuitPython_Essentials/CircuitPython_AnalogOut.py @@ -1,7 +1,7 @@ # CircuitPython IO demo - analog output -from analogio import AnalogOut import board +from analogio import AnalogOut analog_out = AnalogOut(board.A0) diff --git a/CircuitPython_Essentials/CircuitPython_CapTouch.py b/CircuitPython_Essentials/CircuitPython_CapTouch.py index e93f2ded9..feaec0e20 100644 --- a/CircuitPython_Essentials/CircuitPython_CapTouch.py +++ b/CircuitPython_Essentials/CircuitPython_CapTouch.py @@ -1,4 +1,5 @@ import time + import board import touchio diff --git a/CircuitPython_Essentials/CircuitPython_CapTouch_2Pins.py b/CircuitPython_Essentials/CircuitPython_CapTouch_2Pins.py index ca62a578b..fc9eafa67 100644 --- a/CircuitPython_Essentials/CircuitPython_CapTouch_2Pins.py +++ b/CircuitPython_Essentials/CircuitPython_CapTouch_2Pins.py @@ -2,6 +2,7 @@ # Example does NOT work with Trinket M0! import time + import board import touchio diff --git a/CircuitPython_Essentials/CircuitPython_Digital_In_Out.py b/CircuitPython_Essentials/CircuitPython_Digital_In_Out.py index d45221dc2..e3e967408 100644 --- a/CircuitPython_Essentials/CircuitPython_Digital_In_Out.py +++ b/CircuitPython_Essentials/CircuitPython_Digital_In_Out.py @@ -1,19 +1,20 @@ # CircuitPython IO demo #1 - General Purpose I/O import time -from digitalio import DigitalInOut, Direction, Pull + import board +from digitalio import DigitalInOut, Direction, Pull led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT -switch = DigitalInOut(board.D2) # For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express +# For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express +switch = DigitalInOut(board.D2) # switch = DigitalInOut(board.D5) # For Feather M0 Express # switch = DigitalInOut(board.D7) # For Circuit Playground Express switch.direction = Direction.INPUT switch.pull = Pull.UP - while True: # We could also just do "led.value = not switch.value"! if switch.value: diff --git a/CircuitPython_Essentials/CircuitPython_DotStar.py b/CircuitPython_Essentials/CircuitPython_DotStar.py index 9c4e1c94c..6d47f3254 100644 --- a/CircuitPython_Essentials/CircuitPython_DotStar.py +++ b/CircuitPython_Essentials/CircuitPython_DotStar.py @@ -1,11 +1,13 @@ # CircuitPython demo - Dotstar import time -import board + import adafruit_dotstar +import board num_pixels = 30 -pixels = adafruit_dotstar.DotStar(board.A1, board.A2, num_pixels, brightness=0.1, auto_write=False) +pixels = adafruit_dotstar.DotStar( + board.A1, board.A2, num_pixels, brightness=0.1, auto_write=False) def wheel(pos): @@ -103,7 +105,8 @@ MAGENTA = (255, 0, 20) WHITE = (255, 255, 255) while True: - color_fill(RED, 0.5) # Change this number to change how long it stays on each solid color. + # Change this number to change how long it stays on each solid color. + color_fill(RED, 0.5) color_fill(YELLOW, 0.5) color_fill(ORANGE, 0.5) color_fill(GREEN, 0.5) @@ -114,12 +117,15 @@ while True: color_fill(MAGENTA, 0.5) color_fill(WHITE, 0.5) - slice_alternating(0.1) # Increase or decrease this to speed up or slow down the animation. + # Increase or decrease this to speed up or slow down the animation. + slice_alternating(0.1) color_fill(WHITE, 0.5) - slice_rainbow(0.1) # Increase or decrease this to speed up or slow down the animation. + # Increase or decrease this to speed up or slow down the animation. + slice_rainbow(0.1) time.sleep(0.5) - rainbow_cycle(0) # Increase this number to slow down the rainbow animation. + # Increase this number to slow down the rainbow animation. + rainbow_cycle(0) diff --git a/CircuitPython_Essentials/CircuitPython_HID_Keyboard.py b/CircuitPython_Essentials/CircuitPython_HID_Keyboard.py index 2b53b29f7..96a4537be 100644 --- a/CircuitPython_Essentials/CircuitPython_HID_Keyboard.py +++ b/CircuitPython_Essentials/CircuitPython_HID_Keyboard.py @@ -1,11 +1,12 @@ # CircuitPython demo - Keyboard emulator import time -import digitalio + import board +import digitalio from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode # A simple neat keyboard demo in CircuitPython diff --git a/CircuitPython_Essentials/CircuitPython_HID_Mouse.py b/CircuitPython_Essentials/CircuitPython_HID_Mouse.py index 3c3d566e3..671170a4e 100644 --- a/CircuitPython_Essentials/CircuitPython_HID_Mouse.py +++ b/CircuitPython_Essentials/CircuitPython_HID_Mouse.py @@ -1,4 +1,5 @@ import time + import analogio import board import digitalio diff --git a/CircuitPython_Essentials/CircuitPython_I2C_Scan.py b/CircuitPython_Essentials/CircuitPython_I2C_Scan.py index 6617a08d9..b980bea51 100644 --- a/CircuitPython_Essentials/CircuitPython_I2C_Scan.py +++ b/CircuitPython_Essentials/CircuitPython_I2C_Scan.py @@ -1,8 +1,9 @@ # CircuitPython demo - I2C scan +import time + import board import busio -import time i2c = busio.I2C(board.SCL, board.SDA) @@ -10,5 +11,6 @@ while not i2c.try_lock(): pass while True: - print("I2C addresses found:", [hex(device_address) for device_address in i2c.scan()]) + print("I2C addresses found:", [hex(device_address) + for device_address in i2c.scan()]) time.sleep(2) diff --git a/CircuitPython_Essentials/CircuitPython_I2C_TSL2561.py b/CircuitPython_Essentials/CircuitPython_I2C_TSL2561.py index f8275b739..0060dff72 100644 --- a/CircuitPython_Essentials/CircuitPython_I2C_TSL2561.py +++ b/CircuitPython_Essentials/CircuitPython_I2C_TSL2561.py @@ -1,9 +1,10 @@ # CircuitPython Demo - I2C sensor +import time + +import adafruit_tsl2561 import board import busio -import adafruit_tsl2561 -import time i2c = busio.I2C(board.SCL, board.SDA) @@ -11,7 +12,8 @@ i2c = busio.I2C(board.SCL, board.SDA) while not i2c.try_lock(): pass # Print the addresses found once -print("I2C addresses found:", [hex(device_address) for device_address in i2c.scan()]) +print("I2C addresses found:", [hex(device_address) + for device_address in i2c.scan()]) # Unlock I2C now that we're done scanning. i2c.unlock() diff --git a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py index 8e783bce8..f3534f272 100644 --- a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py +++ b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py @@ -1,7 +1,7 @@ import time -import board -import neopixel + import adafruit_dotstar +import board # For Trinket M0, Gemma M0, and ItsyBitsy M0 Express led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) diff --git a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py index ec95e031d..a22dd1af8 100644 --- a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py +++ b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py @@ -1,10 +1,12 @@ import time -import board -import neopixel + import adafruit_dotstar +import board # For Trinket M0, Gemma M0, and ItsyBitsy M0 Express led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) + + # For Feather M0 Express, Metro M0 Express, Metro M4 Express and Circuit Playground Express # led = neopixel.NeoPixel(board.NEOPIXEL, 1) @@ -15,12 +17,12 @@ def wheel(pos): if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: - return int(255 - pos*3), int(pos*3), 0 + return int(255 - pos * 3), int(pos * 3), 0 if pos < 170: pos -= 85 - return 0, int(255 - pos*3), int(pos*3) + return 0, int(255 - pos * 3), int(pos * 3) pos -= 170 - return int(pos * 3), 0, int(255 - (pos*3)) + return int(pos * 3), 0, int(255 - (pos * 3)) led.brightness = 0.3 diff --git a/CircuitPython_Essentials/CircuitPython_Logger.py b/CircuitPython_Essentials/CircuitPython_Logger.py index a8fa70889..fe43400d7 100644 --- a/CircuitPython_Essentials/CircuitPython_Logger.py +++ b/CircuitPython_Essentials/CircuitPython_Logger.py @@ -1,7 +1,8 @@ +import time + import board import digitalio import microcontroller -import time led = digitalio.DigitalInOut(board.D13) led.switch_to_output() diff --git a/CircuitPython_Essentials/CircuitPython_Logger_Boot.py b/CircuitPython_Essentials/CircuitPython_Logger_Boot.py index b3c978044..5acbe20f9 100644 --- a/CircuitPython_Essentials/CircuitPython_Logger_Boot.py +++ b/CircuitPython_Essentials/CircuitPython_Logger_Boot.py @@ -1,5 +1,5 @@ -import digitalio import board +import digitalio import storage # For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express diff --git a/CircuitPython_Essentials/CircuitPython_NeoPixel.py b/CircuitPython_Essentials/CircuitPython_NeoPixel.py index 3fb89c490..4c05e53b0 100644 --- a/CircuitPython_Essentials/CircuitPython_NeoPixel.py +++ b/CircuitPython_Essentials/CircuitPython_NeoPixel.py @@ -1,13 +1,15 @@ # CircuitPython demo - NeoPixel import time + import board import neopixel pixel_pin = board.A1 num_pixels = 8 -pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False) +pixels = neopixel.NeoPixel(pixel_pin, num_pixels, + brightness=0.3, auto_write=False) def wheel(pos): @@ -51,7 +53,8 @@ PURPLE = (180, 0, 255) while True: pixels.fill(RED) pixels.show() - time.sleep(1) # Increase or decrease to change the speed of the solid color change. + # Increase or decrease to change the speed of the solid color change. + time.sleep(1) pixels.fill(GREEN) pixels.show() time.sleep(1) diff --git a/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py b/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py index 41ac8a443..8347e62f7 100644 --- a/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py +++ b/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py @@ -52,7 +52,8 @@ PURPLE = (180, 0, 255, 0) while True: pixels.fill(RED) pixels.show() - time.sleep(1) # Increase or decrease to change the speed of the solid color change. + # Increase or decrease to change the speed of the solid color change. + time.sleep(1) pixels.fill(GREEN) pixels.show() time.sleep(1) diff --git a/CircuitPython_Essentials/CircuitPython_PWM.py b/CircuitPython_Essentials/CircuitPython_PWM.py index 368e55b88..d36ea63be 100644 --- a/CircuitPython_Essentials/CircuitPython_PWM.py +++ b/CircuitPython_Essentials/CircuitPython_PWM.py @@ -1,6 +1,7 @@ import time -import pulseio + import board +import pulseio led = pulseio.PWMOut(board.D13, frequency=5000, duty_cycle=0) diff --git a/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py b/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py index 1a04af064..6061d1a69 100644 --- a/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py +++ b/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py @@ -1,9 +1,11 @@ import time -import pulseio + import board +import pulseio # For the M0 boards: -piezo = pulseio.PWMOut(board.A2, duty_cycle=0, frequency=440, variable_frequency=True) +piezo = pulseio.PWMOut(board.A2, duty_cycle=0, + frequency=440, variable_frequency=True) # For Metro M4 Express: # piezo = pulseio.PWMOut(board.A1, duty_cycle=0, frequency=440, variable_frequency=True) @@ -12,6 +14,6 @@ while True: piezo.frequency = f piezo.duty_cycle = 65536 // 2 # On 50% time.sleep(0.25) # On for 1/4 second - piezo.duty_cycle = 0 # Off + piezo.duty_cycle = 0 # Off time.sleep(0.05) # Pause between notes time.sleep(0.5) diff --git a/CircuitPython_Essentials/CircuitPython_PWM_Piezo_simpleio.py b/CircuitPython_Essentials/CircuitPython_PWM_Piezo_simpleio.py index 24aeaaa65..08d2bb47b 100644 --- a/CircuitPython_Essentials/CircuitPython_PWM_Piezo_simpleio.py +++ b/CircuitPython_Essentials/CircuitPython_PWM_Piezo_simpleio.py @@ -1,4 +1,5 @@ import time + import board import simpleio @@ -8,5 +9,5 @@ while True: simpleio.tone(board.A2, f, 0.25) # on for 1/4 second # For the Metro M4 Express: # simpleio.tone(board.A1, f, 0.25) # on for 1/4 second - time.sleep(0.05) # pause between notes + time.sleep(0.05) # pause between notes time.sleep(0.5) diff --git a/CircuitPython_Essentials/CircuitPython_Servo.py b/CircuitPython_Essentials/CircuitPython_Servo.py index 9264a340d..24933ac2e 100644 --- a/CircuitPython_Essentials/CircuitPython_Servo.py +++ b/CircuitPython_Essentials/CircuitPython_Servo.py @@ -1,6 +1,7 @@ import time -import simpleio + import board +import simpleio # For the M0 boards: servo = simpleio.Servo(board.A2) diff --git a/CircuitPython_Essentials/CircuitPython_UART.py b/CircuitPython_Essentials/CircuitPython_UART.py index ddf3dc78b..c05e50dce 100644 --- a/CircuitPython_Essentials/CircuitPython_UART.py +++ b/CircuitPython_Essentials/CircuitPython_UART.py @@ -1,8 +1,8 @@ # CircuitPython Demo - USB/Serial echo -import digitalio import board import busio +import digitalio led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT @@ -16,7 +16,8 @@ while True: if data is not None: led.value = True - data_string = ''.join([chr(b) for b in data]) # convert bytearray to string + # convert bytearray to string + data_string = ''.join([chr(b) for b in data]) print(data_string, end="") led.value = False diff --git a/CircuitPython_Essentials/SPI_Test_Script.py b/CircuitPython_Essentials/SPI_Test_Script.py index 9d0de7859..8680629a7 100644 --- a/CircuitPython_Essentials/SPI_Test_Script.py +++ b/CircuitPython_Essentials/SPI_Test_Script.py @@ -2,7 +2,7 @@ import board import busio -def is_hardware_SPI(clock_pin, data_pin): +def is_hardware_spi(clock_pin, data_pin): try: p = busio.SPI(clock_pin, data_pin) p.deinit() @@ -11,7 +11,8 @@ def is_hardware_SPI(clock_pin, data_pin): return False -if is_hardware_SPI(board.A1, board.A2): # Provide the two pins you intend to use. +# Provide the two pins you intend to use. +if is_hardware_spi(board.A1, board.A2): print("This pin combination is hardware SPI!") else: print("This pin combination isn't hardware SPI.") diff --git a/CircuitPython_Essentials/UART_Test_Script.py b/CircuitPython_Essentials/UART_Test_Script.py index 5e3ebbf14..a3ae8cd21 100644 --- a/CircuitPython_Essentials/UART_Test_Script.py +++ b/CircuitPython_Essentials/UART_Test_Script.py @@ -2,7 +2,7 @@ import board import busio -def is_hardware_UART(tx, rx): +def is_hardware_uart(tx, rx): try: p = busio.UART(tx, rx) p.deinit() @@ -32,7 +32,7 @@ for tx_pin in get_unique_pins(): if rx_pin is tx_pin: continue else: - if is_hardware_UART(tx_pin, rx_pin): + if is_hardware_uart(tx_pin, rx_pin): print("RX pin:", rx_pin, "\t TX pin:", tx_pin) else: pass diff --git a/CircuitPython_Hardware_SD_Cards/hello.py b/CircuitPython_Hardware_SD_Cards/hello.py index d4d0a47c0..09907203e 100644 --- a/CircuitPython_Hardware_SD_Cards/hello.py +++ b/CircuitPython_Hardware_SD_Cards/hello.py @@ -1,2 +1 @@ print('Hello, World!') - diff --git a/CircuitPython_Hardware_SD_Cards/sdmount.py b/CircuitPython_Hardware_SD_Cards/sdmount.py index 183067345..bf995dba9 100644 --- a/CircuitPython_Hardware_SD_Cards/sdmount.py +++ b/CircuitPython_Hardware_SD_Cards/sdmount.py @@ -1,9 +1,11 @@ +import sys + import adafruit_sdcard +import board import busio import digitalio -import board import storage -import sys + # Connect to the card and mount the filesystem. spi = busio.SPI(board.SCK, board.MOSI, board.MISO) cs = digitalio.DigitalInOut(board.SD_CS) diff --git a/CircuitPython_Hardware_SD_Cards/sdmount_lib.py b/CircuitPython_Hardware_SD_Cards/sdmount_lib.py index 9e8c00916..a1cbcd479 100644 --- a/CircuitPython_Hardware_SD_Cards/sdmount_lib.py +++ b/CircuitPython_Hardware_SD_Cards/sdmount_lib.py @@ -1,9 +1,11 @@ +import sys + import adafruit_sdcard +import board import busio import digitalio -import board import storage -import sys + # Connect to the card and mount the filesystem. spi = busio.SPI(board.SCK, board.MOSI, board.MISO) cs = digitalio.DigitalInOut(board.SD_CS) diff --git a/CircuitPython_Painter/main.py b/CircuitPython_Painter/main.py index cb4467c11..fd6634c71 100644 --- a/CircuitPython_Painter/main.py +++ b/CircuitPython_Painter/main.py @@ -1,10 +1,11 @@ # Dotstar painter! Can handle up to ~2300 pixel size image (e.g. 36 x 64) -import board -import digitalio -import time import gc +import time + +import board import busio +import digitalio FILENAME = "blinka.bmp" IMAGE_DELAY = 0.2 @@ -23,6 +24,7 @@ databuf = bytearray(0) led = digitalio.DigitalInOut(board.D13) led.switch_to_output() + def read_le(s): # as of this writting, int.from_bytes does not have LE support, DIY! result = 0 @@ -32,32 +34,33 @@ def read_le(s): shift += 8 return result + class BMPError(Exception): pass try: - with open("/"+FILENAME, "rb") as f: + with open("/" + FILENAME, "rb") as f: print("File opened") if f.read(2) != b'BM': # check signature raise BMPError("Not BitMap file") - + bmpFileSize = read_le(f.read(4)) f.read(4) # Read & ignore creator bytes - bmpImageoffset = read_le(f.read(4)) # Start of image data + bmpImageoffset = read_le(f.read(4)) # Start of image data headerSize = read_le(f.read(4)) bmpWidth = read_le(f.read(4)) bmpHeight = read_le(f.read(4)) flip = True - + print("Size: %d\nImage offset: %d\nHeader size: %d" % (bmpFileSize, bmpImageoffset, headerSize)) print("Width: %d\nHeight: %d" % (bmpWidth, bmpHeight)) - + if read_le(f.read(2)) != 1: - raise BMPError("Not singleplane") - bmpDepth = read_le(f.read(2)) # bits per pixel + raise BMPError("Not singleplane") + bmpDepth = read_le(f.read(2)) # bits per pixel print("Bit depth: %d" % (bmpDepth)) if bmpDepth != 24: raise BMPError("Not 24-bit") @@ -66,27 +69,29 @@ try: print("Image OK!") - rowSize = (bmpWidth * 3 + 3) & ~3 # 32-bit line boundary + rowSize = (bmpWidth * 3 + 3) & ~3 # 32-bit line boundary - databuf = bytearray(bmpWidth * bmpHeight * 4) # its huge! but its also fast :) + # its huge! but its also fast :) + databuf = bytearray(bmpWidth * bmpHeight * 4) - for row in range(bmpHeight): # For each scanline... - if(flip): # Bitmap is stored bottom-to-top order (normal BMP) + for row in range(bmpHeight): # For each scanline... + if (flip): # Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize - else: # Bitmap is stored top-to-bottom - pos = bmpImageoffset + row * rowSize; - - #print ("seek to %d" % pos) + else: # Bitmap is stored top-to-bottom + pos = bmpImageoffset + row * rowSize + + # print ("seek to %d" % pos) f.seek(pos) for col in range(bmpWidth): - b,g,r = bytearray(f.read(3)) # BMP files store RGB in BGR + b, g, r = bytearray(f.read(3)) # BMP files store RGB in BGR # front load brightness, gamma and reordering here! order = [b, g, r] - idx = (col * bmpHeight + (bmpHeight - row - 1))*4 + idx = (col * bmpHeight + (bmpHeight - row - 1)) * 4 databuf[idx] = 0xFF # first byte is 'brightness' idx += 1 for color in order: - databuf[idx] = int(pow((color * BRIGHTNESS) / 255, 2.7) * 255 + 0.5) + databuf[idx] = int( + pow((color * BRIGHTNESS) / 255, 2.7) * 255 + 0.5) idx += 1 except OSError as e: @@ -95,7 +100,7 @@ except OSError as e: else: halt("OS Error ", 0.5) except BMPError as e: - print("Failed to parse BMP: "+e.args[0]) + print("Failed to parse BMP: " + e.args[0]) gc.collect() print(gc.mem_free()) @@ -105,13 +110,13 @@ while True: index = 0 for col in range(bmpWidth): - row = databuf[index:index+bmpHeight*4] - dotstar.write(bytearray([0x00, 0x00, 0x00, 0x00] )) + row = databuf[index:index + bmpHeight * 4] + dotstar.write(bytearray([0x00, 0x00, 0x00, 0x00])) dotstar.write(row) dotstar.write(bytearray([0x00, 0x00, 0x00, 0x00])) index += bmpHeight * 4 time.sleep(PIXEL_DELAY) - + # clear it out dotstar.write(bytearray([0x00, 0x00, 0x00, 0x00])) for r in range(bmpHeight * 5): diff --git a/CircuitPython_Quick_Starts/CircuitPython_AnalogIn.py b/CircuitPython_Quick_Starts/CircuitPython_AnalogIn.py index 8cbd78d86..4a1418ed3 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_AnalogIn.py +++ b/CircuitPython_Quick_Starts/CircuitPython_AnalogIn.py @@ -1,8 +1,9 @@ # CircuitPython AnalogIn Demo import time -from analogio import AnalogIn + import board +from analogio import AnalogIn analog_in = AnalogIn(board.A1) diff --git a/CircuitPython_Quick_Starts/CircuitPython_AnalogOut.py b/CircuitPython_Quick_Starts/CircuitPython_AnalogOut.py index 45368fa67..43f74338b 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_AnalogOut.py +++ b/CircuitPython_Quick_Starts/CircuitPython_AnalogOut.py @@ -1,7 +1,7 @@ # CircuitPython IO demo - analog output -from analogio import AnalogOut import board +from analogio import AnalogOut analog_out = AnalogOut(board.A0) diff --git a/CircuitPython_Quick_Starts/CircuitPython_CapTouch.py b/CircuitPython_Quick_Starts/CircuitPython_CapTouch.py index e93f2ded9..feaec0e20 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_CapTouch.py +++ b/CircuitPython_Quick_Starts/CircuitPython_CapTouch.py @@ -1,4 +1,5 @@ import time + import board import touchio diff --git a/CircuitPython_Quick_Starts/CircuitPython_CapTouch_2Pins.py b/CircuitPython_Quick_Starts/CircuitPython_CapTouch_2Pins.py index ca62a578b..fc9eafa67 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_CapTouch_2Pins.py +++ b/CircuitPython_Quick_Starts/CircuitPython_CapTouch_2Pins.py @@ -2,6 +2,7 @@ # Example does NOT work with Trinket M0! import time + import board import touchio diff --git a/CircuitPython_Quick_Starts/CircuitPython_Digital_In_Out.py b/CircuitPython_Quick_Starts/CircuitPython_Digital_In_Out.py index d45221dc2..e3e967408 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_Digital_In_Out.py +++ b/CircuitPython_Quick_Starts/CircuitPython_Digital_In_Out.py @@ -1,19 +1,20 @@ # CircuitPython IO demo #1 - General Purpose I/O import time -from digitalio import DigitalInOut, Direction, Pull + import board +from digitalio import DigitalInOut, Direction, Pull led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT -switch = DigitalInOut(board.D2) # For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express +# For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express +switch = DigitalInOut(board.D2) # switch = DigitalInOut(board.D5) # For Feather M0 Express # switch = DigitalInOut(board.D7) # For Circuit Playground Express switch.direction = Direction.INPUT switch.pull = Pull.UP - while True: # We could also just do "led.value = not switch.value"! if switch.value: diff --git a/CircuitPython_Quick_Starts/CircuitPython_DotStar.py b/CircuitPython_Quick_Starts/CircuitPython_DotStar.py index 9c4e1c94c..6d47f3254 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_DotStar.py +++ b/CircuitPython_Quick_Starts/CircuitPython_DotStar.py @@ -1,11 +1,13 @@ # CircuitPython demo - Dotstar import time -import board + import adafruit_dotstar +import board num_pixels = 30 -pixels = adafruit_dotstar.DotStar(board.A1, board.A2, num_pixels, brightness=0.1, auto_write=False) +pixels = adafruit_dotstar.DotStar( + board.A1, board.A2, num_pixels, brightness=0.1, auto_write=False) def wheel(pos): @@ -103,7 +105,8 @@ MAGENTA = (255, 0, 20) WHITE = (255, 255, 255) while True: - color_fill(RED, 0.5) # Change this number to change how long it stays on each solid color. + # Change this number to change how long it stays on each solid color. + color_fill(RED, 0.5) color_fill(YELLOW, 0.5) color_fill(ORANGE, 0.5) color_fill(GREEN, 0.5) @@ -114,12 +117,15 @@ while True: color_fill(MAGENTA, 0.5) color_fill(WHITE, 0.5) - slice_alternating(0.1) # Increase or decrease this to speed up or slow down the animation. + # Increase or decrease this to speed up or slow down the animation. + slice_alternating(0.1) color_fill(WHITE, 0.5) - slice_rainbow(0.1) # Increase or decrease this to speed up or slow down the animation. + # Increase or decrease this to speed up or slow down the animation. + slice_rainbow(0.1) time.sleep(0.5) - rainbow_cycle(0) # Increase this number to slow down the rainbow animation. + # Increase this number to slow down the rainbow animation. + rainbow_cycle(0) diff --git a/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_colors.py b/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_colors.py index b33d73ee9..a60f0a0a9 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_colors.py +++ b/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_colors.py @@ -1,7 +1,7 @@ import time -import board -import neopixel + import adafruit_dotstar +import board # For Trinket M0, Gemma M0, and ItsyBitsy M0 Express led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) diff --git a/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_rainbow.py b/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_rainbow.py index 0bd522be7..914dd4957 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_rainbow.py +++ b/CircuitPython_Quick_Starts/CircuitPython_Internal_RGB_LED_rainbow.py @@ -1,10 +1,12 @@ import time -import board -import neopixel + import adafruit_dotstar +import board # For Trinket M0, Gemma M0, and ItsyBitsy M0 Express led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) + + # For Feather M0 Express, Metro M0 Express, and Circuit Playground Express # led = neopixel.NeoPixel(board.NEOPIXEL, 1) @@ -15,12 +17,12 @@ def wheel(pos): if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: - return int(255 - pos*3), int(pos*3), 0 + return int(255 - pos * 3), int(pos * 3), 0 if pos < 170: pos -= 85 - return 0, int(255 - pos*3), int(pos*3) + return 0, int(255 - pos * 3), int(pos * 3) pos -= 170 - return int(pos * 3), 0, int(255 - (pos*3)) + return int(pos * 3), 0, int(255 - (pos * 3)) led.brightness = 0.3 diff --git a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel.py b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel.py index 3fb89c490..4c05e53b0 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel.py +++ b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel.py @@ -1,13 +1,15 @@ # CircuitPython demo - NeoPixel import time + import board import neopixel pixel_pin = board.A1 num_pixels = 8 -pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False) +pixels = neopixel.NeoPixel(pixel_pin, num_pixels, + brightness=0.3, auto_write=False) def wheel(pos): @@ -51,7 +53,8 @@ PURPLE = (180, 0, 255) while True: pixels.fill(RED) pixels.show() - time.sleep(1) # Increase or decrease to change the speed of the solid color change. + # Increase or decrease to change the speed of the solid color change. + time.sleep(1) pixels.fill(GREEN) pixels.show() time.sleep(1) diff --git a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py index 41ac8a443..ad88e5ef9 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py +++ b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py @@ -1,6 +1,7 @@ # CircuitPython demo - NeoPixel RGBW import time + import board import neopixel @@ -52,7 +53,8 @@ PURPLE = (180, 0, 255, 0) while True: pixels.fill(RED) pixels.show() - time.sleep(1) # Increase or decrease to change the speed of the solid color change. + # Increase or decrease to change the speed of the solid color change. + time.sleep(1) pixels.fill(GREEN) pixels.show() time.sleep(1) diff --git a/CircuitPython_Quick_Starts/CircuitPython_PWM.py b/CircuitPython_Quick_Starts/CircuitPython_PWM.py index 368e55b88..d36ea63be 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_PWM.py +++ b/CircuitPython_Quick_Starts/CircuitPython_PWM.py @@ -1,6 +1,7 @@ import time -import pulseio + import board +import pulseio led = pulseio.PWMOut(board.D13, frequency=5000, duty_cycle=0) diff --git a/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo.py b/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo.py index 8b101aadd..2925926ad 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo.py +++ b/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo.py @@ -1,14 +1,16 @@ import time -import pulseio -import board -piezo = pulseio.PWMOut(board.A2, duty_cycle=0, frequency=440, variable_frequency=True) +import board +import pulseio + +piezo = pulseio.PWMOut(board.A2, duty_cycle=0, + frequency=440, variable_frequency=True) while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): piezo.frequency = f piezo.duty_cycle = 65536 // 2 # On 50% time.sleep(0.25) # On for 1/4 second - piezo.duty_cycle = 0 # Off + piezo.duty_cycle = 0 # Off time.sleep(0.05) # Pause between notes time.sleep(0.5) diff --git a/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo_simpleio.py b/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo_simpleio.py index 8b445ab01..bc14792e7 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo_simpleio.py +++ b/CircuitPython_Quick_Starts/CircuitPython_PWM_Piezo_simpleio.py @@ -1,9 +1,10 @@ import time + import board import simpleio while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): simpleio.tone(board.A2, f, 0.25) # on for 1/4 second - time.sleep(0.05) # pause between notes + time.sleep(0.05) # pause between notes time.sleep(0.5) diff --git a/CircuitPython_Quick_Starts/CircuitPython_Servo.py b/CircuitPython_Quick_Starts/CircuitPython_Servo.py index 0ee456628..00c0bfed5 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_Servo.py +++ b/CircuitPython_Quick_Starts/CircuitPython_Servo.py @@ -1,6 +1,7 @@ import time -import simpleio + import board +import simpleio servo = simpleio.Servo(board.A2) diff --git a/CircuitPython_Quick_Starts/CircuitPython_UART.py b/CircuitPython_Quick_Starts/CircuitPython_UART.py index ddf3dc78b..c05e50dce 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_UART.py +++ b/CircuitPython_Quick_Starts/CircuitPython_UART.py @@ -1,8 +1,8 @@ # CircuitPython Demo - USB/Serial echo -import digitalio import board import busio +import digitalio led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT @@ -16,7 +16,8 @@ while True: if data is not None: led.value = True - data_string = ''.join([chr(b) for b in data]) # convert bytearray to string + # convert bytearray to string + data_string = ''.join([chr(b) for b in data]) print(data_string, end="") led.value = False diff --git a/CircuitPython_Quick_Starts/SPI_Test_Script.py b/CircuitPython_Quick_Starts/SPI_Test_Script.py index 9d0de7859..26969fe06 100644 --- a/CircuitPython_Quick_Starts/SPI_Test_Script.py +++ b/CircuitPython_Quick_Starts/SPI_Test_Script.py @@ -11,7 +11,8 @@ def is_hardware_SPI(clock_pin, data_pin): return False -if is_hardware_SPI(board.A1, board.A2): # Provide the two pins you intend to use. +# Provide the two pins you intend to use. +if is_hardware_SPI(board.A1, board.A2): print("This pin combination is hardware SPI!") else: print("This pin combination isn't hardware SPI.") diff --git a/CircuitPython_TVBGone/cpx_main.py b/CircuitPython_TVBGone/cpx_main.py index b0d8fbf87..144965eb8 100644 --- a/CircuitPython_TVBGone/cpx_main.py +++ b/CircuitPython_TVBGone/cpx_main.py @@ -1,10 +1,11 @@ -import board import array import time -from digitalio import DigitalInOut, Direction, Pull -import pulseio -############## Switch to select 'stealth-mode' +import board +import pulseio +from digitalio import DigitalInOut, Direction, Pull + +# Switch to select 'stealth-mode' switch = DigitalInOut(board.SLIDE_SWITCH) switch.direction = Direction.INPUT switch.pull = Pull.UP @@ -12,14 +13,14 @@ switch.pull = Pull.UP led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT -############## Speaker as haptic feedback +# Speaker as haptic feedback spkr_en = DigitalInOut(board.SPEAKER_ENABLE) spkr_en.direction = Direction.OUTPUT spkr_en.value = True spkr = DigitalInOut(board.SPEAKER) spkr.direction = Direction.OUTPUT -############## Allow any button to trigger activity! +# Allow any button to trigger activity! button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.DOWN @@ -27,8 +28,8 @@ button_b = DigitalInOut(board.BUTTON_B) button_b.direction = Direction.INPUT button_b.pull = Pull.DOWN - -pwm = pulseio.PWMOut(board.REMOTEOUT, frequency=38000, duty_cycle=2 ** 15, variable_frequency=True) +pwm = pulseio.PWMOut(board.REMOTEOUT, frequency=38000, + duty_cycle=2 ** 15, variable_frequency=True) pulse = pulseio.PulseOut(pwm) while True: @@ -36,7 +37,7 @@ while True: while not (button_a.value or button_b.value): pass time.sleep(0.5) # Give a half second before starting - + # gooooo! f = open("/codes.txt", "r") for line in f: @@ -50,7 +51,7 @@ while True: try: repeat = code['repeat'] delay = code['repeat_delay'] - except KeyError: # by default, repeat once only! + except KeyError: # by default, repeat once only! repeat = 1 delay = 0 # The table holds the on/off pairs @@ -65,9 +66,9 @@ while True: for i in range(repeat): pulse.send(array.array('H', pulses)) time.sleep(delay) - + led.value = False spkr.value = False time.sleep(code['delay']) - + f.close() diff --git a/CircuitPython_TVBGone/gemma_main.py b/CircuitPython_TVBGone/gemma_main.py index 073559c4a..0de9b963d 100644 --- a/CircuitPython_TVBGone/gemma_main.py +++ b/CircuitPython_TVBGone/gemma_main.py @@ -1,24 +1,26 @@ # Gemma M0 version of TVBgone! -import board import array import time -from digitalio import DigitalInOut, Direction, Pull -import pulseio -import adafruit_dotstar -pixel = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +import adafruit_dotstar +import board +import pulseio +from digitalio import DigitalInOut, Direction + +pixel = adafruit_dotstar.DotStar( + board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) pixel.fill((0, 0, 0)) # Button to see output debug led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT -pwm = pulseio.PWMOut(board.A1, frequency=38000, duty_cycle=2 ** 15, variable_frequency=True) +pwm = pulseio.PWMOut(board.A1, frequency=38000, + duty_cycle=2 ** 15, variable_frequency=True) pulse = pulseio.PulseOut(pwm) - time.sleep(0.5) # Give a half second before starting - + # gooooo! f = open("/codes.txt", "r") for line in f: @@ -30,7 +32,7 @@ for line in f: try: repeat = code['repeat'] delay = code['repeat_delay'] - except KeyError: # by default, repeat once only! + except KeyError: # by default, repeat once only! repeat = 1 delay = 0 # The table holds the on/off pairs @@ -46,5 +48,5 @@ for line in f: time.sleep(delay) led.value = False time.sleep(code['delay']) - + f.close() diff --git a/Close_Encounters_Hat/Close_Encounters_Hat.py b/Close_Encounters_Hat/Close_Encounters_Hat.py index 1d0ae033f..3945c0ab4 100644 --- a/Close_Encounters_Hat/Close_Encounters_Hat.py +++ b/Close_Encounters_Hat/Close_Encounters_Hat.py @@ -4,20 +4,21 @@ # Photocell voltage divider center wire to GPIO #2 (analog 1) # and output tone to GPIO #0 (digital 0) -import board -import analogio import time + +import analogio +import board import neopixel import simpleio # Initialize input/output pins -photocell_pin = board.A1 # cds photocell connected to this ANALOG pin -speaker_pin = board.D0 # speaker is connected to this DIGITAL pin -pixpin = board.D1 # pin where NeoPixels are connected -numpix = 10 # number of neopixels` -darkness_min = (2**16 / 2) # more dark than light > 32k out of 64k +photocell_pin = board.A1 # cds photocell connected to this ANALOG pin +speaker_pin = board.D0 # speaker is connected to this DIGITAL pin +pixpin = board.D1 # pin where NeoPixels are connected +numpix = 10 # number of neopixels` +darkness_min = (2 ** 16 / 2) # more dark than light > 32k out of 64k photocell = analogio.AnalogIn(photocell_pin) -strip = neopixel.NeoPixel(pixpin, numpix, brightness=.4) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=.4) # this section is Close Encounters Sounds toned = 294 @@ -26,66 +27,68 @@ tonec = 262 toneC = 130 toneg = 392 -def alien(): - strip[8] = (255, 255, 0) # yellow front - strip[3] = (255, 255, 0) # yellow back - simpleio.tone(speaker_pin, toned, 1) # play tone for 1 second + +def alien(): + strip[8] = (255, 255, 0) # yellow front + strip[3] = (255, 255, 0) # yellow back + simpleio.tone(speaker_pin, toned, 1) # play tone for 1 second time.sleep(.025) - strip[8] = (0, 0, 0) # clear front - strip[3] = (0, 0, 0) # clear back + strip[8] = (0, 0, 0) # clear front + strip[3] = (0, 0, 0) # clear back time.sleep(.025) - strip[7] = (255, 0, 255) # pink front - strip[2] = (255, 0, 255) # pink back - simpleio.tone(speaker_pin, tonee, 1) # play tone for 1 second + strip[7] = (255, 0, 255) # pink front + strip[2] = (255, 0, 255) # pink back + simpleio.tone(speaker_pin, tonee, 1) # play tone for 1 second time.sleep(.025) - strip[7] = (0, 0, 0) # clear front - strip[2] = (0, 0, 0) # clear back + strip[7] = (0, 0, 0) # clear front + strip[2] = (0, 0, 0) # clear back time.sleep(.025) - strip[4] = (128, 255, 0) # green front - strip[9] = (128, 255, 0) # green back - simpleio.tone(speaker_pin, tonec, 1) # play tone for 1 second + strip[4] = (128, 255, 0) # green front + strip[9] = (128, 255, 0) # green back + simpleio.tone(speaker_pin, tonec, 1) # play tone for 1 second time.sleep(.025) - strip[4] = (0, 0, 0) # clear front - strip[9] = (0, 0, 0) # clear back + strip[4] = (0, 0, 0) # clear front + strip[9] = (0, 0, 0) # clear back time.sleep(.025) - strip[5] = (0, 0, 255) # blue front - strip[0] = (0, 0, 255) # blue back - simpleio.tone(speaker_pin, toneC, 1) # play tone for 1 second + strip[5] = (0, 0, 255) # blue front + strip[0] = (0, 0, 255) # blue back + simpleio.tone(speaker_pin, toneC, 1) # play tone for 1 second time.sleep(.075) - strip[5] = (0, 0, 0) # clear front - strip[0] = (0, 0, 0) # clear back + strip[5] = (0, 0, 0) # clear front + strip[0] = (0, 0, 0) # clear back time.sleep(.1) - strip[6] = (255, 0, 0) # red front - strip[1] = (255, 0, 0) # red back - simpleio.tone(speaker_pin, toneg, 1) # play tone for 1 second + strip[6] = (255, 0, 0) # red front + strip[1] = (255, 0, 0) # red back + simpleio.tone(speaker_pin, toneg, 1) # play tone for 1 second time.sleep(.1) - strip[6] = (0, 0, 0) # clear front - strip[1] = (0, 0, 0) # clear back + strip[6] = (0, 0, 0) # clear front + strip[1] = (0, 0, 0) # clear back time.sleep(.1) + # Loop forever... -while True: +while True: - # turn lights and audio on when dark + # turn lights and audio on when dark # (less than 50% light on analog pin) - if ( photocell.value > darkness_min ): - alien() # close Encounters Loop + if (photocell.value > darkness_min): + alien() # close Encounters Loop diff --git a/Combo_Dial_Safe/main.py b/Combo_Dial_Safe/main.py index 1bc3603de..9a172d437 100644 --- a/Combo_Dial_Safe/main.py +++ b/Combo_Dial_Safe/main.py @@ -2,22 +2,26 @@ # for Adafruit Circuit Playground express # with CircuitPython -from adafruit_circuitplayground.express import cpx import time + import board import simpleio +from adafruit_circuitplayground.express import cpx # plug red servo wire to VOUT, brown to GND, yellow to A3 servo = simpleio.Servo(board.A3) cpx.pixels.brightness = 0.05 # set brightness value + def unlock_servo(): servo.angle = 180 + def lock_servo(): servo.angle = 90 + correct_combo = ['B', 'D', 'C'] # this is where to set the combo entered_combo = [] # this will be used to store attempts current_dial_position = 'X' @@ -74,7 +78,8 @@ while True: if cpx.button_a: # this means the button has been pressed # grab the current_dial_position value and add to the list entered_combo.append(current_dial_position) - dial_msg = 'Dial Position: ' + str(entered_combo[(len(entered_combo)-1)]) + dial_msg = 'Dial Position: ' + \ + str(entered_combo[(len(entered_combo) - 1)]) print(dial_msg) cpx.play_tone(320, 0.3) # beep time.sleep(1) # slow down button checks diff --git a/Crickits/bubble_machine/main.py b/Crickits/bubble_machine/main.py index 64c01e474..47596c275 100644 --- a/Crickits/bubble_machine/main.py +++ b/Crickits/bubble_machine/main.py @@ -1,11 +1,12 @@ # CircuitPython 3.0 CRICKIT demo -from adafruit_seesaw.seesaw import Seesaw -from adafruit_seesaw.pwmout import PWMOut -from adafruit_motor import servo, motor -from busio import I2C -import board import time +import board +from adafruit_motor import servo, motor +from adafruit_seesaw.pwmout import PWMOut +from adafruit_seesaw.seesaw import Seesaw +from busio import I2C + i2c = I2C(board.SCL, board.SDA) ss = Seesaw(i2c) @@ -14,22 +15,22 @@ print("Bubble machine!") SERVOS = True DCMOTORS = True -#################### Create 4 Servos +# Create 4 Servos servos = [] if SERVOS: - for ss_pin in (17, 16, 15, 14): + for ss_pin in (17, 16, 15, 14): pwm = PWMOut(ss, ss_pin) - pwm.frequency = 50 + pwm.frequency = 50 _servo = servo.Servo(pwm) - _servo.angle = 90 # starting angle, middle + _servo.angle = 90 # starting angle, middle servos.append(_servo) -#################### Create 2 DC motors +# Create 2 DC motors motors = [] if DCMOTORS: - for ss_pin in ((18, 19), (22, 23)): - pwm0 = PWMOut(ss, ss_pin[0]) - pwm1 = PWMOut(ss, ss_pin[1]) + for ss_pin in ((18, 19), (22, 23)): + pwm0 = PWMOut(ss, ss_pin[0]) + pwm1 = PWMOut(ss, ss_pin[1]) _motor = motor.DCMotor(pwm0, pwm1) motors.append(_motor) @@ -45,4 +46,4 @@ while True: motors[0].throttle = 0 print("servo up") servos[0].angle = 0 - time.sleep(1) + time.sleep(1) diff --git a/Crickits/feynman_bot/code.py b/Crickits/feynman_bot/code.py index 8f296f1c7..bc94d21ff 100644 --- a/Crickits/feynman_bot/code.py +++ b/Crickits/feynman_bot/code.py @@ -1,65 +1,68 @@ # CircuitPython 3.0 CRICKIT demo -from adafruit_seesaw.seesaw import Seesaw -from adafruit_seesaw.pwmout import PWMOut -from adafruit_motor import servo, motor -import audioio -from busio import I2C -import random -import board -import time import gc +import time + +import audioio +import board +from adafruit_motor import servo +from adafruit_seesaw.pwmout import PWMOut +from adafruit_seesaw.seesaw import Seesaw +from busio import I2C i2c = I2C(board.SCL, board.SDA) ss = Seesaw(i2c) print("Feynbot demo!") -#################### 1 Servo +# 1 Servo pwm = PWMOut(ss, 17) pwm.frequency = 50 myservo = servo.Servo(pwm) -myservo.angle = 180 # starting angle, highest +myservo.angle = 180 # starting angle, highest -#################### 2 Drivers +# 2 Drivers drives = [] for ss_pin in (13, 12): _pwm = PWMOut(ss, ss_pin) _pwm.frequency = 1000 drives.append(_pwm) -#################### Audio files +# Audio files wavfiles = ["01.wav", "02.wav", "03.wav", "04.wav", "05.wav"] a = audioio.AudioOut(board.A0) + # Start playing the file (in the background) def play_file(wavfile): f = open(wavfile, "rb") wav = audioio.WaveFile(f) a.play(wav) + # Tap the solenoids back and forth def bongo(t): for _ in range(t): - drives[0].duty_cycle = 0xFFFF - time.sleep(0.1) - drives[0].duty_cycle = 0 - time.sleep(0.1) - drives[1].duty_cycle = 0xFFFF - time.sleep(0.1) - drives[1].duty_cycle = 0 - time.sleep(0.1) + drives[0].duty_cycle = 0xFFFF + time.sleep(0.1) + drives[0].duty_cycle = 0 + time.sleep(0.1) + drives[1].duty_cycle = 0xFFFF + time.sleep(0.1) + drives[1].duty_cycle = 0 + time.sleep(0.1) + # Move mouth back and forth def talk(t): for _ in range(t): - myservo.angle = 150 - time.sleep(0.1) - myservo.angle = 180 - time.sleep(0.1) + myservo.angle = 150 + time.sleep(0.1) + myservo.angle = 180 + time.sleep(0.1) -filenum = 0 # counter to play all files +filenum = 0 # counter to play all files while True: gc.collect() @@ -73,13 +76,13 @@ while True: play_file(wavfiles[filenum]) # and move the mouth while it does while a.playing: - talk(1) + talk(1) # Done being insightful, take a break time.sleep(1) # If we went thru all the files, JAM OUT! - filenum += 1 + filenum += 1 if filenum >= len(wavfiles): - bongo(20) - filenum = 0 + bongo(20) + filenum = 0 diff --git a/Cyber_Flower/main.py b/Cyber_Flower/main.py index 74b0ed156..71fb90ecb 100644 --- a/Cyber_Flower/main.py +++ b/Cyber_Flower/main.py @@ -38,51 +38,49 @@ import math import time +import adafruit_dotstar +import adafruit_fancyled.adafruit_fancyled as fancy import board import digitalio import touchio -import adafruit_dotstar -import adafruit_fancyled.adafruit_fancyled as fancy - - # Variables that control the code. Try changing these to modify speed, color, # etc. -START_DELAY = 5.0 # How many seconds to wait after power up before - # jumping into the animation and initializing the - # touch input. This gives you time to take move your - # fingers off the flower so the capacitive touch - # sensing is better calibrated. During the delay - # the small red LED on the board will flash. +START_DELAY = 5.0 # How many seconds to wait after power up before +# jumping into the animation and initializing the +# touch input. This gives you time to take move your +# fingers off the flower so the capacitive touch +# sensing is better calibrated. During the delay +# the small red LED on the board will flash. -TOUCH_PIN = board.D0 # The board pin to listen for touches and trigger the - # heart beat animation. You can change this to any - # other pin like board.D2 or board.D1. Make sure not - # to touch this pin as the board powers on or the - # capacitive sensing will get confused (just reset - # the board and try again). +TOUCH_PIN = board.D0 # The board pin to listen for touches and trigger the +# heart beat animation. You can change this to any +# other pin like board.D2 or board.D1. Make sure not +# to touch this pin as the board powers on or the +# capacitive sensing will get confused (just reset +# the board and try again). -BRIGHTNESS = 1.0 # The brightness of the colors. Set this to a value - # anywhere within 0 and 1.0, where 1.0 is full bright. - # For example 0.5 would be half brightness. +BRIGHTNESS = 1.0 # The brightness of the colors. Set this to a value +# anywhere within 0 and 1.0, where 1.0 is full bright. +# For example 0.5 would be half brightness. -RAINBOW_PERIOD_S = 18.0 # How many seconds it takes for the default rainbow - # cycle animation to perform a full cycle. Increase - # this to slow down the animation or decrease to speed - # it up. +RAINBOW_PERIOD_S = 18.0 # How many seconds it takes for the default rainbow +# cycle animation to perform a full cycle. Increase +# this to slow down the animation or decrease to speed +# it up. -HEARTBEAT_BPM = 60.0 # Heartbeat animation beats per minute. Increase to - # speed up the heartbeat, and decrease to slow down. +HEARTBEAT_BPM = 60.0 # Heartbeat animation beats per minute. Increase to +# speed up the heartbeat, and decrease to slow down. -HEARTBEAT_HUE = 300.0 # The color hue to use when animating the heartbeat - # animation. Pick a value in the range of 0 to 359 - # degrees, see the hue spectrum here: - # https://en.wikipedia.org/wiki/Hue - # A value of 300 is a nice pink color. +HEARTBEAT_HUE = 300.0 # The color hue to use when animating the heartbeat +# animation. Pick a value in the range of 0 to 359 +# degrees, see the hue spectrum here: +# https://en.wikipedia.org/wiki/Hue +# A value of 300 is a nice pink color. # First initialize the DotStar LED and turn it off. dotstar = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) -dotstar[0] = (0,0,0) +dotstar[0] = (0, 0, 0) # Also make sure the on-board red LED is turned off. red_led = digitalio.DigitalInOut(board.L) @@ -103,24 +101,29 @@ while time.monotonic() - start <= START_DELAY: touch = touchio.TouchIn(TOUCH_PIN) # Convert periods to frequencies that are used later in animations. -rainbow_freq = 1.0/RAINBOW_PERIOD_S +rainbow_freq = 1.0 / RAINBOW_PERIOD_S # Calculcate periods and values used by the heartbeat animation. -beat_period = 60.0/HEARTBEAT_BPM -beat_quarter_period = beat_period/4.0 # Quarter period controls the speed of - # the heartbeat drop-off (using an - # exponential decay function). -beat_phase = beat_period/5.0 # Phase controls how long in-between - # the two parts of the heart beat - # (the 'ba-boom' of the beat). +beat_period = 60.0 / HEARTBEAT_BPM +beat_quarter_period = beat_period / 4.0 # Quarter period controls the speed of +# the heartbeat drop-off (using an +# exponential decay function). +beat_phase = beat_period / 5.0 # Phase controls how long in-between + + +# the two parts of the heart beat +# (the 'ba-boom' of the beat). # Handy function for linear interpolation of a value. Pass in a value # x that's within the range x0...x1 and a range y0...y1 to get an output value # y that's proportionally within y0...y1 based on x within x0...x1. Handy for # transforming a value in one range to a value in another (like Arduino's map # function). + + def lerp(x, x0, x1, y0, y1): - return y0+(x-x0)*((y1-y0)/(x1-x0)) + return y0 + (x - x0) * ((y1 - y0) / (x1 - x0)) + # Main loop below will run forever: while True: @@ -139,8 +142,8 @@ while True: # out of phase so one occurs a little bit after the other. t0 = current % beat_period t1 = (current + beat_phase) % beat_period - x0 = math.pow(math.e, -t0/beat_quarter_period) - x1 = math.pow(math.e, -t1/beat_quarter_period) + x0 = math.pow(math.e, -t0 / beat_quarter_period) + x1 = math.pow(math.e, -t1 / beat_quarter_period) # After calculating both exponential decay values pick the biggest one # as the secondary one will occur after the first. Scale each by # the global brightness and then convert to RGB color using the fixed @@ -149,14 +152,14 @@ while True: # like we expect for full bright to zero brightness with HSV color # (i.e. no interpolation is necessary). val = max(x0, x1) * BRIGHTNESS - color = fancy.gamma_adjust(fancy.CHSV(HEARTBEAT_HUE/359.0, 1.0, val)) + color = fancy.gamma_adjust(fancy.CHSV(HEARTBEAT_HUE / 359.0, 1.0, val)) dotstar[0] = color.pack() else: # The touch input is not being touched (touch.value is False) so # compute the hue with a smooth cycle over time. # First use the sine function to smoothly generate a value that goes # from -1.0 to 1.0 at a certain frequency to match the rainbow period. - x = math.sin(2.0*math.pi*rainbow_freq*current) + x = math.sin(2.0 * math.pi * rainbow_freq * current) # Then compute the hue by converting the sine wave value from something # that goes from -1.0 to 1.0 to instead go from 0 to 1.0 hue. hue = lerp(x, -1.0, 1.0, 0.0, 1.0) diff --git a/Cyber_Flower/main_simple.py b/Cyber_Flower/main_simple.py index 47b7ee649..22d3baf3a 100644 --- a/Cyber_Flower/main_simple.py +++ b/Cyber_Flower/main_simple.py @@ -34,40 +34,39 @@ import busio import digitalio import touchio - # Variables that control the code. Try changing these to modify speed, color, # etc. -START_DELAY = 5.0 # How many seconds to wait after power up before - # jumping into the animation and initializing the - # touch input. This gives you time to take move your - # fingers off the flower so the capacitive touch - # sensing is better calibrated. During the delay - # the small red LED on the board will flash. +START_DELAY = 5.0 # How many seconds to wait after power up before +# jumping into the animation and initializing the +# touch input. This gives you time to take move your +# fingers off the flower so the capacitive touch +# sensing is better calibrated. During the delay +# the small red LED on the board will flash. -TOUCH_PIN = board.D0 # The board pin to listen for touches and trigger the - # heart beat animation. You can change this to any - # other pin like board.D2 or board.D1. Make sure not - # to touch this pin as the board powers on or the - # capacitive sensing will get confused (just reset - # the board and try again). +TOUCH_PIN = board.D0 # The board pin to listen for touches and trigger the +# heart beat animation. You can change this to any +# other pin like board.D2 or board.D1. Make sure not +# to touch this pin as the board powers on or the +# capacitive sensing will get confused (just reset +# the board and try again). -BRIGHTNESS = 1.0 # The brightness of the colors. Set this to a value - # anywhere within 0 and 1.0, where 1.0 is full bright. - # For example 0.5 would be half brightness. +BRIGHTNESS = 1.0 # The brightness of the colors. Set this to a value +# anywhere within 0 and 1.0, where 1.0 is full bright. +# For example 0.5 would be half brightness. -RAINBOW_PERIOD_S = 18.0 # How many seconds it takes for the default rainbow - # cycle animation to perform a full cycle. Increase - # this to slow down the animation or decrease to speed - # it up. +RAINBOW_PERIOD_S = 18.0 # How many seconds it takes for the default rainbow +# cycle animation to perform a full cycle. Increase +# this to slow down the animation or decrease to speed +# it up. -HEARTBEAT_BPM = 60.0 # Heartbeat animation beats per minute. Increase to - # speed up the heartbeat, and decrease to slow down. +HEARTBEAT_BPM = 60.0 # Heartbeat animation beats per minute. Increase to +# speed up the heartbeat, and decrease to slow down. -HEARTBEAT_HUE = 300.0 # The color hue to use when animating the heartbeat - # animation. Pick a value in the range of 0 to 359 - # degrees, see the hue spectrum here: - # https://en.wikipedia.org/wiki/Hue - # A value of 300 is a nice pink color. +HEARTBEAT_HUE = 300.0 # The color hue to use when animating the heartbeat +# animation. Pick a value in the range of 0 to 359 +# degrees, see the hue spectrum here: +# https://en.wikipedia.org/wiki/Hue +# A value of 300 is a nice pink color. # First initialize the DotStar LED and turn it off. # We'll manually drive the dotstar instead of depending on the adafruit_dotstar @@ -78,7 +77,11 @@ dotstar_spi = busio.SPI(clock=board.APA102_SCK, MOSI=board.APA102_MOSI) # pixel data, followed by bytes of 0xFF tail (just one for 1 pixel). dotstar_data = bytearray([0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF]) + + # Define a function to simplify setting dotstar color. + + def dotstar_color(rgb_color): # Set the color of the dot star LED. This is barebones dotstar driving # code for simplicity and less dependency on other libraries. We're only @@ -93,6 +96,8 @@ def dotstar_color(rgb_color): dotstar_spi.write(dotstar_data) finally: dotstar_spi.unlock() + + # Call the function above to turn off the dotstar initially (set it to all 0). dotstar_color((0, 0, 0)) @@ -115,23 +120,24 @@ while time.monotonic() - start <= START_DELAY: touch = touchio.TouchIn(TOUCH_PIN) # Convert periods to frequencies that are used later in animations. -rainbow_freq = 1.0/RAINBOW_PERIOD_S +rainbow_freq = 1.0 / RAINBOW_PERIOD_S # Calculcate periods and values used by the heartbeat animation. -beat_period = 60.0/HEARTBEAT_BPM -beat_quarter_period = beat_period/4.0 # Quarter period controls the speed of - # the heartbeat drop-off (using an - # exponential decay function). -beat_phase = beat_period/5.0 # Phase controls how long in-between - # the two parts of the heart beat - # (the 'ba-boom' of the beat). +beat_period = 60.0 / HEARTBEAT_BPM +beat_quarter_period = beat_period / 4.0 # Quarter period controls the speed of +# the heartbeat drop-off (using an +# exponential decay function). +beat_phase = beat_period / 5.0 # Phase controls how long in-between +# the two parts of the heart beat +# (the 'ba-boom' of the beat). # Define a gamma correction lookup table to make colors more accurate. # See this guide for more background on gamma correction: # https://learn.adafruit.com/led-tricks-gamma-correction/ gamma8 = bytearray(256) for i in range(len(gamma8)): - gamma8[i] = int(math.pow(i/255.0, 2.8)*255.0+0.5) & 0xFF + gamma8[i] = int(math.pow(i / 255.0, 2.8) * 255.0 + 0.5) & 0xFF + # Define a function to convert from HSV (hue, saturation, value) color to # RGB colors that DotStar LEDs speak. The HSV color space is a nicer for @@ -140,6 +146,8 @@ for i in range(len(gamma8)): # value that range from 0 to 1.0. This will also use the gamma correction # table above to get the most accurate color. Adapted from C/C++ code here: # https://www.cs.rit.edu/~ncs/color/t_convert.html + + def HSV_to_RGB(h, s, v): r = 0 g = 0 @@ -149,9 +157,9 @@ def HSV_to_RGB(h, s, v): g = v b = v else: - h /= 60.0 # sector 0 to 5 + h /= 60.0 # sector 0 to 5 i = int(math.floor(h)) - f = h - i # factorial part of h + f = h - i # factorial part of h p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) @@ -179,18 +187,22 @@ def HSV_to_RGB(h, s, v): r = v g = p b = q - r = gamma8[int(255.0*r)] - g = gamma8[int(255.0*g)] - b = gamma8[int(255.0*b)] + r = gamma8[int(255.0 * r)] + g = gamma8[int(255.0 * g)] + b = gamma8[int(255.0 * b)] return (r, g, b) + # Another handy function for linear interpolation of a value. Pass in a value # x that's within the range x0...x1 and a range y0...y1 to get an output value # y that's proportionally within y0...y1 based on x within x0...x1. Handy for # transforming a value in one range to a value in another (like Arduino's map # function). + + def lerp(x, x0, x1, y0, y1): - return y0+(x-x0)*((y1-y0)/(x1-x0)) + return y0 + (x - x0) * ((y1 - y0) / (x1 - x0)) + # Main loop below will run forever: while True: @@ -209,8 +221,8 @@ while True: # out of phase so one occurs a little bit after the other. t0 = current % beat_period t1 = (current + beat_phase) % beat_period - x0 = math.pow(math.e, -t0/beat_quarter_period) - x1 = math.pow(math.e, -t1/beat_quarter_period) + x0 = math.pow(math.e, -t0 / beat_quarter_period) + x1 = math.pow(math.e, -t1 / beat_quarter_period) # After calculating both exponential decay values pick the biggest one # as the secondary one will occur after the first. Scale each by # the global brightness and then convert to RGB color using the fixed @@ -225,7 +237,7 @@ while True: # compute the hue with a smooth cycle over time. # First use the sine function to smoothly generate a value that goes # from -1.0 to 1.0 at a certain frequency to match the rainbow period. - x = math.sin(2.0*math.pi*rainbow_freq*current) + x = math.sin(2.0 * math.pi * rainbow_freq * current) # Then compute the hue by converting the sine wave value from something # that goes from -1.0 to 1.0 to instead go from 0 to 359 degrees. hue = lerp(x, -1.0, 1.0, 0.0, 359.0) diff --git a/Cyberpunk_Spikes/Cyberpunk_Spikes.py b/Cyberpunk_Spikes/Cyberpunk_Spikes.py index d7dc3dad5..5431af710 100644 --- a/Cyberpunk_Spikes/Cyberpunk_Spikes.py +++ b/Cyberpunk_Spikes/Cyberpunk_Spikes.py @@ -1,12 +1,13 @@ -from digitalio import DigitalInOut, Direction -import board -import neopixel import time -try: - import urandom as random -except ImportError: - import random +import board +import neopixel +from digitalio import DigitalInOut, Direction + +try: + import urandom as random +except ImportError: + import random pixpin = board.D1 numpix = 16 @@ -17,74 +18,84 @@ led.direction = Direction.OUTPUT strip = neopixel.NeoPixel(pixpin, numpix, brightness=.2, auto_write=True) colors = [ - [ 232, 100, 255 ], # Purple - [ 200, 200, 20 ], # Yellow - [ 30, 200, 200 ], # Blue + [232, 100, 255], # Purple + [200, 200, 20], # Yellow + [30, 200, 200], # Blue ] + # Fill the dots one after the other with a color + + def colorWipe(color, wait): for j in range(len(strip)): strip[j] = (color) time.sleep(wait) + def rainbow(wait): for j in range(255): for i in range(len(strip)): - idx = int (i+j) + idx = int(i + j) strip[i] = wheel(idx & 255) + # Slightly different, this makes the rainbow equally distributed throughout + + def rainbow_cycle(wait): - for j in range(255*5): + for j in range(255 * 5): for i in range(len(strip)): - idx = int ((i * 256 / len(strip)) + j) + idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) time.sleep(wait) + # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. + + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) -def flash_random(wait,howmany): +def flash_random(wait, howmany): + for k in range(howmany): - for k in range(howmany): + c = random.randint(0, len(colors) - 1) # Choose random color index + j = random.randint(0, numpix - 1) # Choose random pixel + strip[j] = colors[c] # Set pixel to color - c = random.randint(0, len(colors) - 1) # Choose random color index - j = random.randint(0, numpix - 1) # Choose random pixel - strip[j] = colors[c] # Set pixel to color + for i in range(1, 5): + strip.brightness = i / 5.0 # Ramp up brightness + time.sleep(wait) - for i in range(1, 5): - strip.brightness = i / 5.0 # Ramp up brightness - time.sleep(wait) - - - for i in range(5, 0, -1): - strip.brightness = i / 5.0 # Ramp down brightness - strip[j] = [0,0,0] # Set pixel to 'off' - time.sleep(wait) + for i in range(5, 0, -1): + strip.brightness = i / 5.0 # Ramp down brightness + strip[j] = [0, 0, 0] # Set pixel to 'off' + time.sleep(wait) while True: - flash_random(.01, 8) # first number is 'wait' delay, shorter num == shorter twinkle - flash_random(.01, 5) # second number is how many neopixels to simultaneously light up + # first number is 'wait' delay, shorter num == shorter twinkle + flash_random(.01, 8) + # second number is how many neopixels to simultaneously light up + flash_random(.01, 5) flash_random(.01, 11) - colorWipe( (232, 100, 255), .1 ) - colorWipe( (200, 200, 20), .1 ) - colorWipe( (30, 200, 200), .1) + colorWipe((232, 100, 255), .1) + colorWipe((200, 200, 20), .1) + colorWipe((30, 200, 200), .1) rainbow_cycle(0.05) diff --git a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py index 80c94cb47..2d3bd5c7d 100644 --- a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py +++ b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py @@ -1,9 +1,10 @@ import time -import adafruit_sdcard + import adafruit_am2320 +import adafruit_sdcard +import analogio import board import busio -import analogio import digitalio import storage @@ -42,7 +43,7 @@ while True: print("VBat voltage: {:.2f}".format(battery_voltage)) print() sdc.write("{}, {}, {}, {:.2f}\n".format(int(time_stamp), temperature, - humidity, battery_voltage)) + humidity, battery_voltage)) time.sleep(3) except OSError: pass diff --git a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py index 6067f008b..fa3ea8b1b 100644 --- a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py +++ b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py @@ -29,21 +29,21 @@ Explainatory comments are used verbatim from that code. import math import random +import adafruit_dotstar +import adafruit_lsm303 import board import busio -import adafruit_lsm303 -import adafruit_dotstar - -N_GRAINS = 10 # Number of grains of sand -WIDTH = 12 # Display width in pixels -HEIGHT = 6 # Display height in pixels +N_GRAINS = 10 # Number of grains of sand +WIDTH = 12 # Display width in pixels +HEIGHT = 6 # Display height in pixels NUMBER_PIXELS = WIDTH * HEIGHT MAX_FPS = 45 # Maximum redraw rate, frames/second GRAIN_COLOR = (0, 0, 16) MAX_X = WIDTH * 256 - 1 MAX_Y = HEIGHT * 256 - 1 + class Grain: """A simple struct to hold position and velocity information for a single grain.""" @@ -58,7 +58,8 @@ class Grain: grains = [Grain() for _ in range(N_GRAINS)] i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_lsm303.LSM303(i2c) -wing = adafruit_dotstar.DotStar(board.D13, board.D11, WIDTH * HEIGHT, 0.25, False) +wing = adafruit_dotstar.DotStar( + board.D13, board.D11, WIDTH * HEIGHT, 0.25, False) oldidx = 0 newidx = 0 @@ -68,13 +69,15 @@ newy = 0 occupied_bits = [False for _ in range(WIDTH * HEIGHT)] + def index_of_xy(x, y): """Convert an x/column and y/row into an index into a linear pixel array. :param int x: column value :param int y: row value """ - return (y >> 8) * WIDTH + (x >> 8) + return (y >> 8) * WIDTH + (x >> 8) + def already_present(limit, x, y): """Check if a pixel is already used. @@ -89,6 +92,7 @@ def already_present(limit, x, y): return True return False + for g in grains: placed = False while not placed: @@ -109,20 +113,20 @@ while True: # Read accelerometer... f_x, f_y, f_z = sensor.raw_acceleration - ax = f_x >> 8 # Transform accelerometer axes - ay = f_y >> 8 # to grain coordinate space - az = abs(f_z) >> 11 # Random motion factor - az = 1 if (az >= 3) else (4 - az) # Clip & invert - ax -= az # Subtract motion factor from X, Y + ax = f_x >> 8 # Transform accelerometer axes + ay = f_y >> 8 # to grain coordinate space + az = abs(f_z) >> 11 # Random motion factor + az = 1 if (az >= 3) else (4 - az) # Clip & invert + ax -= az # Subtract motion factor from X, Y ay -= az - az2 = (az << 1) + 1 # Range of random motion to add back in + az2 = (az << 1) + 1 # Range of random motion to add back in # ...and apply 2D accel vector to grain velocities... - v2 = 0 # Velocity squared - v = 0.0 # Absolute velociy + v2 = 0 # Velocity squared + v = 0.0 # Absolute velociy for g in grains: - g.vx += ax + random.randint(0, az2) # A little randomness makes - g.vy += ay + random.randint(0, az2) # tall stacks topple better! + g.vx += ax + random.randint(0, az2) # A little randomness makes + g.vy += ay + random.randint(0, az2) # tall stacks topple better! # Terminal velocity (in any direction) is 256 units -- equal to # 1 pixel -- which keeps moving grains from passing through each other @@ -131,10 +135,10 @@ while True: # diagonal movement isn't faster v2 = g.vx * g.vx + g.vy * g.vy - if v2 > 65536: # If v^2 > 65536, then v > 256 - v = math.floor(math.sqrt(v2)) # Velocity vector magnitude - g.vx = (g.vx // v) << 8 # Maintain heading - g.vy = (g.vy // v) << 8 # Limit magnitude + if v2 > 65536: # If v^2 > 65536, then v > 256 + v = math.floor(math.sqrt(v2)) # Velocity vector magnitude + g.vx = (g.vx // v) << 8 # Maintain heading + g.vy = (g.vy // v) << 8 # Limit magnitude # ...then update position of each grain, one at a time, checking for # collisions and having them react. This really seems like it shouldn't @@ -148,11 +152,11 @@ while True: # the tiny 8-bit AVR microcontroller and my tiny dinosaur brain.) for g in grains: - newx = g.x + g.vx # New position in grain space + newx = g.x + g.vx # New position in grain space newy = g.y + g.vy - if newx > MAX_X: # If grain would go out of bounds - newx = MAX_X # keep it inside, and - g.vx //= -2 # give a slight bounce off the wall + if newx > MAX_X: # If grain would go out of bounds + newx = MAX_X # keep it inside, and + g.vx //= -2 # give a slight bounce off the wall elif newx < 0: newx = 0 g.vx //= -2 @@ -163,56 +167,64 @@ while True: newy = 0 g.vy //= -2 - oldidx = index_of_xy(g.x, g.y) # prior pixel - newidx = index_of_xy(newx, newy) # new pixel - if oldidx != newidx and occupied_bits[newidx]: # If grain is moving to a new pixel... - # but if that pixel is already occupied... - delta = abs(newidx - oldidx) # What direction when blocked? - if delta == 1: # 1 pixel left or right - newx = g.x # cancel x motion - g.vx //= -2 # and bounce X velocity (Y is ok) - newidx = oldidx # no pixel change - elif delta == WIDTH: # 1 pixel up or down - newy = g.y # cancel Y motion - g.vy //= -2 # and bounce Y velocity (X is ok) - newidx = oldidx # no pixel change - else: # Diagonal intersection is more tricky... + oldidx = index_of_xy(g.x, g.y) # prior pixel + newidx = index_of_xy(newx, newy) # new pixel + # If grain is moving to a new pixel... + if oldidx != newidx and occupied_bits[newidx]: + # but if that pixel is already occupied... + # What direction when blocked? + delta = abs(newidx - oldidx) + if delta == 1: # 1 pixel left or right + newx = g.x # cancel x motion + # and bounce X velocity (Y is ok) + g.vx //= -2 + newidx = oldidx # no pixel change + elif delta == WIDTH: # 1 pixel up or down + newy = g.y # cancel Y motion + # and bounce Y velocity (X is ok) + g.vy //= -2 + newidx = oldidx # no pixel change + else: # Diagonal intersection is more tricky... # Try skidding along just one axis of motion if possible (start w/ # faster axis). Because we've already established that diagonal # (both-axis) motion is occurring, moving on either axis alone WILL # change the pixel index, no need to check that again. - if abs(g.vx) > abs(g.vy): # x axis is faster + if abs(g.vx) > abs(g.vy): # x axis is faster newidx = index_of_xy(newx, g.y) - if not occupied_bits[newidx]: # that pixel is free, take it! But... - newy = g.y # cancel Y motion - g.vy //= -2 # and bounce Y velocity - else: # X pixel is taken, so try Y... + # that pixel is free, take it! But... + if not occupied_bits[newidx]: + newy = g.y # cancel Y motion + g.vy //= -2 # and bounce Y velocity + else: # X pixel is taken, so try Y... newidx = index_of_xy(g.x, newy) - if not occupied_bits[newidx]: # Pixel is free, take it, but first... - newx = g.x # Cancel X motion - g.vx //= -2 # Bounce X velocity - else: # both spots are occupied - newx = g.x # Cancel X & Y motion + # Pixel is free, take it, but first... + if not occupied_bits[newidx]: + newx = g.x # Cancel X motion + g.vx //= -2 # Bounce X velocity + else: # both spots are occupied + newx = g.x # Cancel X & Y motion newy = g.y - g.vx //= -2 # Bounce X & Y velocity + g.vx //= -2 # Bounce X & Y velocity g.vy //= -2 - newidx = oldidx # Not moving - else: # y axis is faster. start there + newidx = oldidx # Not moving + else: # y axis is faster. start there newidx = index_of_xy(g.x, newy) - if not occupied_bits[newidx]: # Pixel's free! Take it! But... - newx = g.x # Cancel X motion - g.vx //= -2 # Bounce X velocity - else: # Y pixel is taken, so try X... + # Pixel's free! Take it! But... + if not occupied_bits[newidx]: + newx = g.x # Cancel X motion + g.vx //= -2 # Bounce X velocity + else: # Y pixel is taken, so try X... newidx = index_of_xy(newx, g.y) - if not occupied_bits[newidx]: # Pixel is free, take it, but first... - newy = g.y # cancel Y motion - g.vy //= -2 # and bounce Y velocity - else: # both spots are occupied - newx = g.x # Cancel X & Y motion + # Pixel is free, take it, but first... + if not occupied_bits[newidx]: + newy = g.y # cancel Y motion + g.vy //= -2 # and bounce Y velocity + else: # both spots are occupied + newx = g.x # Cancel X & Y motion newy = g.y - g.vx //= -2 # Bounce X & Y velocity + g.vx //= -2 # Bounce X & Y velocity g.vy //= -2 - newidx = oldidx # Not moving + newidx = oldidx # Not moving occupied_bits[oldidx] = False occupied_bits[newidx] = True g.x = newx diff --git a/EPROM_Emulator/debouncer.py b/EPROM_Emulator/debouncer.py index f9183968c..2f5b60322 100644 --- a/EPROM_Emulator/debouncer.py +++ b/EPROM_Emulator/debouncer.py @@ -26,8 +26,10 @@ Debounce an input pin. """ import time + import digitalio + class Debouncer(object): """Debounce an input pin""" @@ -35,7 +37,6 @@ class Debouncer(object): UNSTABLE_STATE = 0x02 CHANGED_STATE = 0x04 - def __init__(self, pin, mode=None, interval=0.010): """Make am instance. :param int pin: the pin (from board) to debounce @@ -48,30 +49,26 @@ class Debouncer(object): if mode != None: self.pin.pull = mode if self.pin.value: - self.__set_state(Debouncer.DEBOUNCED_STATE | Debouncer.UNSTABLE_STATE) + self.__set_state(Debouncer.DEBOUNCED_STATE | + Debouncer.UNSTABLE_STATE) self.previous_time = 0 if interval is None: self.interval = 0.010 else: self.interval = interval - def __set_state(self, bits): self.state |= bits - def __unset_state(self, bits): self.state &= ~bits - def __toggle_state(self, bits): self.state ^= bits - def __get_state(self, bits): return (self.state & bits) != 0 - def update(self): """Update the debouncer state. Must be called before using any of the properties below""" self.__unset_state(Debouncer.CHANGED_STATE) @@ -86,19 +83,16 @@ class Debouncer(object): self.__toggle_state(Debouncer.DEBOUNCED_STATE) self.__set_state(Debouncer.CHANGED_STATE) - @property def value(self): """Return the current debounced value of the input.""" return self.__get_state(Debouncer.DEBOUNCED_STATE) - @property def rose(self): """Return whether the debounced input went from low to high at the most recent update.""" return self.__get_state(self.DEBOUNCED_STATE) and self.__get_state(self.CHANGED_STATE) - @property def fell(self): """Return whether the debounced input went from high to low at the most recent update.""" diff --git a/EPROM_Emulator/directory_node.py b/EPROM_Emulator/directory_node.py index 7ecec3164..6664c67c5 100644 --- a/EPROM_Emulator/directory_node.py +++ b/EPROM_Emulator/directory_node.py @@ -28,6 +28,7 @@ Manage a directory in the file system. import os + class DirectoryNode(object): """Display and navigate the SD card contents""" @@ -46,7 +47,6 @@ class DirectoryNode(object): self.selected_offset = 0 self.old_selected_offset = -1 - def __cleanup(self): """Dereference things for speedy gc.""" self.display = None @@ -55,7 +55,6 @@ class DirectoryNode(object): self.files = None return self - def __is_dir(self, path): """Determine whether a path identifies a machine code bin file. :param string path: path of the file to check @@ -68,7 +67,6 @@ class DirectoryNode(object): except OSError: return False - def __sanitize(self, name): """Nondestructively strip off a trailing slash, if any, and return the result. :param string name: the filename @@ -77,7 +75,6 @@ class DirectoryNode(object): return name[:-1] return name - def __path(self): """Return the result of recursively follow the parent links, building a full path to this directory.""" @@ -85,21 +82,18 @@ class DirectoryNode(object): return self.parent.__path() + os.sep + self.__sanitize(self.name) return self.__sanitize(self.name) - def __make_path(self, filename): """Return a full path to the specified file in this directory. :param string filename: the name of the file in this directory """ return self.__path() + os.sep + filename - def __number_of_files(self): """The number of files in this directory, including the ".." for the parent directory if this isn't the top directory on the SD card.""" self.__get_files() return len(self.files) - def __get_files(self): """Return a list of the files in this directory. If this is not the top directory on the SD card, a ".." entry is the first element. @@ -113,7 +107,6 @@ class DirectoryNode(object): if self.__is_dir(self.__make_path(name)): self.files[index] = name + "/" - def __update_display(self): """Update the displayed list of files if required.""" if self.top_offset != self.old_top_offset: @@ -124,37 +117,34 @@ class DirectoryNode(object): self.display.show() self.old_top_offset = self.top_offset - def __update_selection(self): """Update the selected file lighlight if required.""" if self.selected_offset != self.old_selected_offset: if self.old_selected_offset > -1: - self.display.text(">", 0, (self.old_selected_offset - self.top_offset) * 8, 0) - self.display.text(">", 0, (self.selected_offset - self.top_offset) * 8, 1) + self.display.text( + ">", 0, (self.old_selected_offset - self.top_offset) * 8, 0) + self.display.text( + ">", 0, (self.selected_offset - self.top_offset) * 8, 1) self.display.show() self.old_selected_offset = self.selected_offset - def __is_directory_name(self, filename): """Is a filename the name of a directory. :param string filename: the name of the file """ return filename[-1] == '/' - @property def selected_filename(self): """The name of the currently selected file in this directory.""" self.__get_files() return self.files[self.selected_offset] - @property def selected_filepath(self): """The full path of the currently selected file in this directory.""" return self.__make_path(self.selected_filename) - def force_update(self): """Force an update of the file list and selected file highlight.""" self.old_selected_offset = -1 @@ -162,7 +152,6 @@ class DirectoryNode(object): self.__update_display() self.__update_selection() - def down(self): """Move down in the file list if possible, adjusting the selected file indicator and scrolling the display as required.""" @@ -173,7 +162,6 @@ class DirectoryNode(object): self.__update_display() self.__update_selection() - def up(self): """Move up in the file list if possible, adjusting the selected file indicator and scrolling the display as required.""" @@ -184,7 +172,6 @@ class DirectoryNode(object): self.__update_display() self.__update_selection() - def click(self): """Handle a selection and return the new current directory. If the selected file is the parent, i.e. "..", return to the parent directory. @@ -196,7 +183,8 @@ class DirectoryNode(object): self.__cleanup() return p elif self.__is_directory_name(self.selected_filename): - new_node = DirectoryNode(self.display, self, self.selected_filename) + new_node = DirectoryNode( + self.display, self, self.selected_filename) new_node.force_update() return new_node return self diff --git a/EPROM_Emulator/emulator.py b/EPROM_Emulator/emulator.py index bbe1c30e6..0bdf37a75 100644 --- a/EPROM_Emulator/emulator.py +++ b/EPROM_Emulator/emulator.py @@ -25,8 +25,8 @@ THE SOFTWARE. Manage the emulator hardware. """ -import digitalio import adafruit_mcp230xx +import digitalio # control pin values @@ -57,7 +57,7 @@ class Emulator(object): def __init__(self, i2c): self.mcp = adafruit_mcp230xx.MCP23017(i2c) - self.mcp.iodir = 0x0000 # Make all pins outputs + self.mcp.iodir = 0x0000 # Make all pins outputs # Configure the individual control pins @@ -85,47 +85,38 @@ class Emulator(object): self.led_pin.direction = digitalio.Direction.OUTPUT self.led_pin.value = False - def __pulse_write(self): self.write_pin.value = WRITE_ENABLED self.write_pin.value = WRITE_DISABLED - def __deactivate_ram(self): self.chip_select_pin.value = CHIP_DISABLED - def __activate_ram(self): self.chip_select_pin.value = CHIP_ENABLED - def __reset_address_counter(self): self.clock_reset_pin.value = RESET_ACTIVE self.clock_reset_pin.value = RESET_INACTIVE - def __advance_address_counter(self): self.address_clock_pin.value = CLOCK_ACTIVE self.address_clock_pin.value = CLOCK_INACTIVE - def __output_on_port_a(self, data_byte): """A hack to get around the limitation of the 23017 library to use 8-bit ports""" self.mcp.gpio = (self.mcp.gpio & 0xFF00) | (data_byte & 0x00FF) - def enter_program_mode(self): """Enter program mode, allowing loading of the emulator RAM.""" self.mode_pin.value = PROGRAMMER_USE self.led_pin.value = LED_OFF - def enter_emulate_mode(self): """Enter emulate mode, giving control of the emulator ram to the host.""" self.mode_pin.value = EMULATE_USE self.led_pin.value = LED_ON - def load_ram(self, code): """Load the emulator RAM. Automatically switched to program mode. :param [byte] code: the list of bytes to load into the emulator RAM diff --git a/EPROM_Emulator/main.py b/EPROM_Emulator/main.py index b99b5a895..9fc5a483b 100644 --- a/EPROM_Emulator/main.py +++ b/EPROM_Emulator/main.py @@ -29,18 +29,17 @@ Targeted for the SAMD51 boards. by Dave Astels """ -import digitalio +import adafruit_sdcard +import adafruit_ssd1306 import board import busio -import adafruit_ssd1306 +import digitalio import storage -import adafruit_sdcard - +from debouncer import Debouncer from directory_node import DirectoryNode from emulator import Emulator -from debouncer import Debouncer -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Initialize Rotary encoder # Encoder button is a digital input with pullup on D2 @@ -55,7 +54,7 @@ rot_b = digitalio.DigitalInOut(board.D3) rot_b.direction = digitalio.Direction.INPUT rot_b.pull = digitalio.Pull.UP -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Initialize I2C and OLED i2c = busio.I2C(board.SCL, board.SDA) @@ -65,12 +64,12 @@ oled.fill(0) oled.text("Initializing SD", 0, 10) oled.show() -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Initialize SD card -#SD_CS = board.D10 +# SD_CS = board.D10 # Connect to the card and mount the filesystem. -spi = busio.SPI(board.D13, board.D11, board.D12) # SCK, MOSI, MISO +spi = busio.SPI(board.D13, board.D11, board.D12) # SCK, MOSI, MISO cs = digitalio.DigitalInOut(board.D10) sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) @@ -80,8 +79,7 @@ oled.fill(0) oled.text("Done", 0, 10) oled.show() - -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Initialize globals encoder_counter = 0 @@ -101,7 +99,7 @@ current_mode = PROGRAM_MODE emulator = Emulator(i2c) -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Helper functions def is_binary_name(filename): @@ -138,7 +136,7 @@ def program(): current_dir.force_update() -#-------------------------------------------------------------------------------- +# -------------------------------------------------------------------------------- # Main loop current_dir = DirectoryNode(oled, name="/sd") @@ -196,7 +194,7 @@ while True: rotary_prev_state = rotary_curr_state # Handle encoder rotation - if current_mode == PROGRAM_MODE: #Ignore rotation if in EMULATE mode + if current_mode == PROGRAM_MODE: # Ignore rotation if in EMULATE mode if encoder_direction == -1: current_dir.up() elif encoder_direction == 1: diff --git a/Foul_Fowl/main.py b/Foul_Fowl/main.py index 04ba79500..d4c1b66ff 100644 --- a/Foul_Fowl/main.py +++ b/Foul_Fowl/main.py @@ -6,12 +6,13 @@ # Use a jumper wire from D2 to GND to prevent injection while programming! -from digitalio import DigitalInOut, Direction, Pull -import board import time + +import board from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode +from digitalio import DigitalInOut, Direction, Pull #################################################################### # Select the target operating system for payload: @@ -53,7 +54,10 @@ led.value = True # Wait a moment pause = 0.25 + # The functions that follow are the various payloads to deliver + + def launch_terminal(): if operating_system is 0: led.value = False @@ -105,7 +109,8 @@ def launch_terminal(): time.sleep(2) led.value = False - layout.write("echo \'Try to be more careful what you put in your USB port.\'") + layout.write( + "echo \'Try to be more careful what you put in your USB port.\'") time.sleep(pause) kbd.press(Keycode.ENTER) kbd.release_all() @@ -138,19 +143,24 @@ def launch_terminal(): # time.sleep(pause) time.sleep(2) - layout.write(" _ _ _____ _ _ ___ _____ ____ ___ _____ _ _ ____") + layout.write( + " _ _ _____ _ _ ___ _____ ____ ___ _____ _ _ ____") kbd.press(Keycode.ENTER) kbd.release_all() - layout.write("| | | | ____| | | | / _ \ | ___| _ \|_ _| ____| \ | | _ \ ") + layout.write( + "| | | | ____| | | | / _ \ | ___| _ \|_ _| ____| \ | | _ \ ") kbd.press(Keycode.ENTER) kbd.release_all() - layout.write("| |_| | _| | | | | | | | | | |_ | |_) || || _| | \| | | | |") + layout.write( + "| |_| | _| | | | | | | | | | |_ | |_) || || _| | \| | | | |") kbd.press(Keycode.ENTER) kbd.release_all() - layout.write("| _ | |___| |___| |__| |_| | | _| | _ < | || |___| |\ | |_| |") + layout.write( + "| _ | |___| |___| |__| |_| | | _| | _ < | || |___| |\ | |_| |") kbd.press(Keycode.ENTER) kbd.release_all() - layout.write("|_| |_|_____|_____|_____\___/ |_| |_| \_\___|_____|_| \_|____/ ") + layout.write( + "|_| |_|_____|_____|_____\___/ |_| |_| \_\___|_____|_| \_|____/ ") kbd.press(Keycode.ENTER) kbd.release_all() @@ -159,6 +169,7 @@ def launch_terminal(): kbd.press(Keycode.ENTER) kbd.release_all() + def download_image(): led.value = False # run this after running 'launch_terminal' @@ -178,7 +189,8 @@ def download_image(): # this says where to save image, and where to get it led.value = False - layout.write('curl -o ~/Desktop/hackimage.jpg https://cdn-learn.adafruit.com/assets/assets/000/051/840/original/hacks_foulFowl.jpg') + layout.write( + 'curl -o ~/Desktop/hackimage.jpg https://cdn-learn.adafruit.com/assets/assets/000/051/840/original/hacks_foulFowl.jpg') time.sleep(pause) kbd.press(Keycode.ENTER) led.value = True @@ -200,7 +212,8 @@ def replace_background(): led.value = False # run this after download_image (which ran after launch_terminal) # it uses actionscript to change the background - layout.write('osascript -e \'tell application \"System Events\" to set picture of every desktop to (POSIX path of (path to home folder) & \"/Desktop/hackimage.jpg\" as POSIX file as alias)\'') + layout.write( + 'osascript -e \'tell application \"System Events\" to set picture of every desktop to (POSIX path of (path to home folder) & \"/Desktop/hackimage.jpg\" as POSIX file as alias)\'') time.sleep(pause) kbd.press(Keycode.ENTER) kbd.release_all() @@ -216,6 +229,7 @@ def replace_background(): led.value = True time.sleep(3) # give it a moment to refresh dock and BG + def hide_everything(): led.value = False # print("Hiding stuff... ") @@ -224,6 +238,7 @@ def hide_everything(): time.sleep(10) kbd.release_all() + while True: # check for presence of jumper from GND to D2 if buttons[0].value is False and payload_delivered is 0: @@ -235,8 +250,7 @@ while True: led.value = False payload_delivered = 1 - - if buttons[0].value is True and payload_delivered is 0: #run it + if buttons[0].value is True and payload_delivered is 0: # run it led.value = True print("Release the water fowl!") # for debugging in screen or putty for i in range(10): # blink 5 times diff --git a/FruitBox_Sequencer/main.py b/FruitBox_Sequencer/main.py index e93574cfe..1aad432e3 100644 --- a/FruitBox_Sequencer/main.py +++ b/FruitBox_Sequencer/main.py @@ -2,9 +2,10 @@ # for Adafruit Circuit Playground express # with CircuitPython -from adafruit_circuitplayground.express import cpx import time +from adafruit_circuitplayground.express import cpx + # Change this number to adjust touch sensitivity threshold, 0 is default cpx.adjust_touch_threshold(600) @@ -40,6 +41,7 @@ step_pixel = [9, 8, 7, 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] # step colors step_col = [WHITE, RED, YELLOW, GREEN, AQUA, BLUE, PURPLE, BLACK] + def prog_mode(i): cpx.play_file(audio_files[i]) step_note[step] = i diff --git a/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py b/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py index b24179b25..3e9357ead 100644 --- a/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py +++ b/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py @@ -2,45 +2,48 @@ # uses two 16 NeoPixel rings (RGBW) # connected to Gemma M0 powered by LiPo battery -import board -import neopixel import time -pixpinLeft = board.D1 #Data In attached to Gemma pin D1 -pixpinRight = board.D0 #Data In attached to Gemma pin D0 +import board +import neopixel + +pixpinLeft = board.D1 # Data In attached to Gemma pin D1 +pixpinRight = board.D0 # Data In attached to Gemma pin D0 numpix = 16 -#uncomment the lines below for RGB NeoPixels +# uncomment the lines below for RGB NeoPixels stripLeft = neopixel.NeoPixel(pixpinLeft, numpix, bpp=3, brightness=.18, - auto_write=False) + auto_write=False) stripRight = neopixel.NeoPixel(pixpinRight, numpix, bpp=3, brightness=.18, - auto_write=False) -#Use these lines for RGBW NeoPixels -#stripLeft = neopixel.NeoPixel(pixpinLeft, numpix, bpp=4, brightness=.18, -# auto_write=False) -#stripRight = neopixel.NeoPixel(pixpinRight, numpix, bpp=4, brightness=.18, -# auto_write=False) + auto_write=False) +# Use these lines for RGBW NeoPixels +# stripLeft = neopixel.NeoPixel(pixpinLeft, numpix, bpp=4, brightness=.18, +# auto_write=False) +# stripRight = neopixel.NeoPixel(pixpinRight, numpix, bpp=4, brightness=.18, +# auto_write=False) + def cog(pos): # Input a value 0 to 255 to get a color value. # Note: switch the commented lines below if using RGB vs. RGBW NeoPixles if (pos < 8) or (pos > 250): - #return (120, 0, 0, 0) #first color, red: for RGBW NeoPixels - return (120, 0, 0) #first color, red: for RGB NeoPixels + # return (120, 0, 0, 0) #first color, red: for RGBW NeoPixels + return (120, 0, 0) # first color, red: for RGB NeoPixels if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) - #return (125, 35, 0, 0) #second color, brass: for RGBW NeoPixels - return (125, 35, 0) #second color, brass: for RGB NeoPixels + return (int(pos * 3), int(255 - (pos * 3)), 0) + # return (125, 35, 0, 0) #second color, brass: for RGBW NeoPixels + return (125, 35, 0) # second color, brass: for RGB NeoPixels elif (pos < 170): pos -= 85 - #return (int(255 - pos*3), 0, int(pos*3), 0)#: for RGBW NeoPixels - return (int(255 - pos*3), 0, int(pos*3))#: for RGB NeoPixels + # return (int(255 - pos*3), 0, int(pos*3), 0)#: for RGBW NeoPixels + return (int(255 - pos * 3), 0, int(pos * 3)) # : for RGB NeoPixels else: pos -= 170 - #return (0, int(pos*3), int(255 - pos*3), 0)#: for RGBW NeoPixels - return (0, int(pos*3), int(255 - pos*3))#: for RGB NeoPixels + # return (0, int(pos*3), int(255 - pos*3), 0)#: for RGBW NeoPixels + return (0, int(pos * 3), int(255 - pos * 3)) # : for RGB NeoPixels + def brass_cycle(wait, patternL, patternR): # patterns do different things, try: @@ -53,14 +56,15 @@ def brass_cycle(wait, patternL, patternR): # 256 quarter turn for j in range(255): for i in range(len(stripLeft)): - idxL = int ((i * patternL / len(stripLeft)) + j) - stripLeft[i] = cog(idxL & 64) #sets the second (brass) color - idxR = int ((i * patternR / len(stripRight)) + j) - stripRight[i] = cog(idxR & 64) #sets the second (brass) color + idxL = int((i * patternL / len(stripLeft)) + j) + stripLeft[i] = cog(idxL & 64) # sets the second (brass) color + idxR = int((i * patternR / len(stripRight)) + j) + stripRight[i] = cog(idxR & 64) # sets the second (brass) color stripLeft.show() stripRight.show() time.sleep(wait) + while True: - brass_cycle(0.01, 256, 24) # brass color cycle with 1ms delay per step - # patternL, patternR + brass_cycle(0.01, 256, 24) # brass color cycle with 1ms delay per step + # patternL, patternR diff --git a/GemmaM0_Password_Vault/main.py b/GemmaM0_Password_Vault/main.py index 99f599aa0..5efb93512 100644 --- a/GemmaM0_Password_Vault/main.py +++ b/GemmaM0_Password_Vault/main.py @@ -1,13 +1,13 @@ # Gemma M0 Password Vault # press cap touch pads to enter strong passwords over USB -from digitalio import DigitalInOut, Direction -import touchio -import board import time + +import board +import touchio from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from digitalio import DigitalInOut, Direction led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT diff --git a/GemmaM0_Radio_Tuning_Knob/main.py b/GemmaM0_Radio_Tuning_Knob/main.py index ff55936e0..82886fa3e 100644 --- a/GemmaM0_Radio_Tuning_Knob/main.py +++ b/GemmaM0_Radio_Tuning_Knob/main.py @@ -2,11 +2,12 @@ # for fine tuning Software Defined Radio CubicSDR software # 10k pot hooked to 3v, A2, and D2 acting as GND -from analogio import AnalogIn -import board import time + +import board from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode +from analogio import AnalogIn from digitalio import DigitalInOut, Direction d2_ground = DigitalInOut(board.D2) @@ -22,12 +23,15 @@ pot_min = 0.00 step = (pot_max - pot_min) / 10.0 last_knob = 0 + def steps(x): return round((x - pot_min) / step) + def getVoltage(pin): return (pin.value * 3.3) / 65536 + def spamKey(code): knobkeys = [Keycode.RIGHT_BRACKET, Keycode.RIGHT_BRACKET, Keycode.RIGHT_BRACKET, Keycode.RIGHT_BRACKET, @@ -35,12 +39,14 @@ def spamKey(code): Keycode.LEFT_BRACKET, Keycode.LEFT_BRACKET, Keycode.LEFT_BRACKET, Keycode.LEFT_BRACKET, Keycode.LEFT_BRACKET] - spamRate = [0.01, 0.05, 0.125, 0.25, 0.5, 0.5, 0.5, 0.25, 0.125, 0.05, 0.01] + spamRate = [0.01, 0.05, 0.125, 0.25, 0.5, + 0.5, 0.5, 0.25, 0.125, 0.05, 0.01] kbd = Keyboard() kbd.press(knobkeys[code]) # which keycode is entered kbd.release_all() time.sleep(spamRate[code]) # how fast the key is spammed + while True: knob = (getVoltage(analog2in)) if steps(knob) is 5: # the center position is active diff --git a/GemmaM0_Vibration_Switch_Motion_Alarm/main.py b/GemmaM0_Vibration_Switch_Motion_Alarm/main.py index 699fc138f..a386af847 100644 --- a/GemmaM0_Vibration_Switch_Motion_Alarm/main.py +++ b/GemmaM0_Vibration_Switch_Motion_Alarm/main.py @@ -1,7 +1,6 @@ # Motion Sensor Alarm # uses Gemma M0, vibration sensor on A0/GND, & piezo on D0/GND import pulseio -from digitalio import DigitalInOut, Direction, Pull from analogio import AnalogIn import board import time @@ -11,18 +10,20 @@ piezo = pulseio.PWMOut(board.D0, duty_cycle=0, frequency=440, vibrationPin = AnalogIn(board.A0) + def get_voltage(pin): return (pin.value * 3.3) / 65536 + while True: print((get_voltage(vibrationPin),)) vibration = get_voltage(vibrationPin) if vibration < 1: # the sensor has been tripped, you can adjust this value - # for sensitivity + # for sensitivity for f in (2620, 4400, 2620, 4400, 2620, 4400, 2620, 4400): piezo.frequency = f - piezo.duty_cycle = 65536//2 # on 50% + piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(0.2) # on 1/5 second piezo.duty_cycle = 0 # off time.sleep(0.02) # pause diff --git a/Gemma_3D_Printed_Tree_Topper/Gemma_3D_Printed_Tree_Topper.py b/Gemma_3D_Printed_Tree_Topper/Gemma_3D_Printed_Tree_Topper.py index 6d88f2033..28b162904 100644 --- a/Gemma_3D_Printed_Tree_Topper/Gemma_3D_Printed_Tree_Topper.py +++ b/Gemma_3D_Printed_Tree_Topper/Gemma_3D_Printed_Tree_Topper.py @@ -1,47 +1,50 @@ +import time + import board import neopixel -import time + try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random -numpix = 36 # Number of NeoPixels +numpix = 36 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=1.0) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=1.0) -mode = 0 # Current animation effect -offset = 0 # Position of spinner animation -color = [160, 0, 160] # RGB color - purple +mode = 0 # Current animation effect +offset = 0 # Position of spinner animation +color = [160, 0, 160] # RGB color - purple prevtime = time.monotonic() # Time of last animation mode switch while True: # Loop forever... - if mode == 0: # Random sparkles - lights just one LED at a time - i = random.randint(0, numpix - 1) # Choose random pixel - strip[i] = color # Set it to current color - strip.write() # Refresh LED states - # Set same pixel to "off" color now but DON'T refresh... - # it stays on for now...bot this and the next random - # pixel will be refreshed on the next pass. - strip[i] = [0,0,0] - time.sleep(0.008) # 8 millisecond delay - elif mode == 1: # Spinny wheel (4 LEDs on at a time) - for i in range(numpix): # For each LED... - if ((offset + i) & 7) < 2: # 2 pixels out of 8... - strip[i] = color # are set to current color - else: - strip[i] = [0,0,0] # other pixels are off - strip.write() # Refresh LED states - time.sleep(0.08) # 80 millisecond delay - offset += 1 # Shift animation by 1 pixel on next frame - if offset >= 8: offset = 0 - # Additional animation modes could be added here! + if mode == 0: # Random sparkles - lights just one LED at a time + i = random.randint(0, numpix - 1) # Choose random pixel + strip[i] = color # Set it to current color + strip.write() # Refresh LED states + # Set same pixel to "off" color now but DON'T refresh... + # it stays on for now...bot this and the next random + # pixel will be refreshed on the next pass. + strip[i] = [0, 0, 0] + time.sleep(0.008) # 8 millisecond delay + elif mode == 1: # Spinny wheel (4 LEDs on at a time) + for i in range(numpix): # For each LED... + if ((offset + i) & 7) < 2: # 2 pixels out of 8... + strip[i] = color # are set to current color + else: + strip[i] = [0, 0, 0] # other pixels are off + strip.write() # Refresh LED states + time.sleep(0.08) # 80 millisecond delay + offset += 1 # Shift animation by 1 pixel on next frame + if offset >= 8: + offset = 0 + # Additional animation modes could be added here! - t = time.monotonic() # Current time in seconds - if (t - prevtime) >= 8: # Every 8 seconds... - mode += 1 # Advance to next mode - if mode > 1: # End of modes? - mode = 0 # Start over from beginning - strip.fill([0,0,0]) # Turn off all pixels - prevtime = t # Record time of last mode change + t = time.monotonic() # Current time in seconds + if (t - prevtime) >= 8: # Every 8 seconds... + mode += 1 # Advance to next mode + if mode > 1: # End of modes? + mode = 0 # Start over from beginning + strip.fill([0, 0, 0]) # Turn off all pixels + prevtime = t # Record time of last mode change diff --git a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py index bcda95050..e4871c5c9 100644 --- a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py +++ b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py @@ -1,88 +1,89 @@ -# Gemma "Firewalker Lite" sneakers +# Gemma "Firewalker Lite" sneakers # - Uses the following Adafruit parts (X2 for two shoes): # * Gemma M0 3V microcontroller (#3501) # * 150 mAh LiPoly battery (#1317) or larger # * Medium vibration sensor switch (#2384) # * 60/m NeoPixel RGB LED strip (#1138 or #1461) -# * LiPoly charger such as #1304 +# * LiPoly charger such as #1304 # # - originally written by Phil Burgess for Gemma using Arduino # * https://learn.adafruit.com/gemma-led-sneakers import board +import digitalio import neopixel -import time -import digitalio + try: - import urandom as random + import urandom as random except ImportError: - import random + import random # Declare a NeoPixel object on led_pin with num_leds as pixels -# No auto-write. -led_pin = board.D1 # Which pin your pixels are connected to -num_leds = 40 # How many LEDs you have -circumference = 40 # Shoe circumference, in pixels, may be > NUM_LEDS -frames_per_second = 50 # Animation frames per second -brightness = 0 # Current wave height +# No auto-write. +led_pin = board.D1 # Which pin your pixels are connected to +num_leds = 40 # How many LEDs you have +circumference = 40 # Shoe circumference, in pixels, may be > NUM_LEDS +frames_per_second = 50 # Animation frames per second +brightness = 0 # Current wave height strip = neopixel.NeoPixel(led_pin, num_leds, brightness=1, auto_write=False) offset = 0 # vibration sensor -motion_pin = board.D0 # Pin where vibration switch is connected -pin = digitalio.DigitalInOut(motion_pin) +motion_pin = board.D0 # Pin where vibration switch is connected +pin = digitalio.DigitalInOut(motion_pin) pin.direction = digitalio.Direction.INPUT -pin.pull = digitalio.Pull.UP +pin.pull = digitalio.Pull.UP ramping_up = False -center = 0 # Center point of wave in fixed-point space (0 - 255) -speed = 1 # Distance to move between frames (-128 - +127) -width = 2 # Width from peak to bottom of triangle wave (0 - 128) -hue = 3 # Current wave hue (color) see comments later +center = 0 # Center point of wave in fixed-point space (0 - 255) +speed = 1 # Distance to move between frames (-128 - +127) +width = 2 # Width from peak to bottom of triangle wave (0 - 128) +hue = 3 # Current wave hue (color) see comments later hue_target = 4 # Final hue we're aiming for -red = 5 # LED RGB color calculated from hue -green = 6 # LED RGB color calculated from hue -blue = 7 # LED RGB color calculated from hue +red = 5 # LED RGB color calculated from hue +green = 6 # LED RGB color calculated from hue +blue = 7 # LED RGB color calculated from hue y = 0 brightness = 0 -count = 0 +count = 0 # Gemma can animate 3 of these on 40 LEDs at 50 FPS # More LEDs and/or more waves will need lower wave = [0] * 8, [0] * 8, [0] * 8 -# Note that the speeds of each wave are different prime numbers. -# This avoids repetition as the waves move around the -# perimeter...if they were even numbers or multiples of each +# Note that the speeds of each wave are different prime numbers. +# This avoids repetition as the waves move around the +# perimeter...if they were even numbers or multiples of each # other, there'd be obvious repetition in the pattern of motion... # beat frequencies. n_waves = len(wave) # 90 distinct hues (0-89) around color wheel -hue_table = [ 255, 255, 255, 255, 255, 255, 255, 255, 237, 203, - 169, 135, 101, 67, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 154, 188, 222, - 255, 255, 255, 255, 255, 255, 255, 255 ] +hue_table = [255, 255, 255, 255, 255, 255, 255, 255, 237, 203, + 169, 135, 101, 67, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 154, 188, 222, + 255, 255, 255, 255, 255, 255, 255, 255] -# Gamma-correction table +# Gamma-correction table gammas = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, - 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, - 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, - 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, - 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, - 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, - 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, - 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, - 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, - 90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114, - 115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142, - 144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175, - 177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213, - 215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 ] + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, + 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, + 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, + 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, + 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, + 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, + 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, + 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, + 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, + 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 109, 110, 112, 114, + 115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 138, 140, 142, + 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175, + 177, 180, 182, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213, + 215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255] + def h2rgb(hue): # return value @@ -91,90 +92,92 @@ def h2rgb(hue): hue %= 90 h = hue_table[hue >> 1] - if ( hue & 1 ): + if (hue & 1): ret = h & 15 else: - ret = ( h >> 4 ) - - return ( ret * 17 ) + ret = (h >> 4) + + return (ret * 17) def wave_setup(): global wave - wave = [ [ 0, 3, 60, 0, 0, 0, 0, 0 ], - [ 0, -5, 45, 0, 0, 0, 0, 0 ], - [ 0, 7, 30, 0, 0, 0, 0, 0 ] ] + wave = [[0, 3, 60, 0, 0, 0, 0, 0], + [0, -5, 45, 0, 0, 0, 0, 0], + [0, 7, 30, 0, 0, 0, 0, 0]] # assign random starting colors to waves for w in range(n_waves): - wave[w][hue] = wave[w][hue_target] = 90 + random.randint(0,90) + wave[w][hue] = wave[w][hue_target] = 90 + random.randint(0, 90) wave[w][red] = h2rgb(wave[w][hue] - 30) wave[w][green] = h2rgb(wave[w][hue]) wave[w][blue] = h2rgb(wave[w][hue] + 30) def vibration_detector(): - while ( True ): + while (True): if not pin.value: - return(True) + return (True) -while ( True ) : + +while (True): # wait for vibration sensor to trigger - if ( ramping_up == False ): + if (ramping_up == False): ramping_up = vibration_detector() wave_setup() - # But it's not just a straight shot that it ramps up. - # This is a low-pass filter...it makes the brightness - # value decelerate as it approaches a target (200 in - # this case). 207 is used here because integers round + # But it's not just a straight shot that it ramps up. + # This is a low-pass filter...it makes the brightness + # value decelerate as it approaches a target (200 in + # this case). 207 is used here because integers round # down on division and we'd never reach the target; # it's an ersatz ceil() function: ((199*7)+200+7)/8 = 200; - brightness = int( ((brightness * 7) + 207) / 8 ) + brightness = int(((brightness * 7) + 207) / 8) count += 1 - if ( count == ( circumference + num_leds + 5) ): + if (count == (circumference + num_leds + 5)): ramping_up = False count = 0 # Wave positions and colors are updated... - for w in range(n_waves): + for w in range(n_waves): # Move wave; wraps around ends, is OK! - wave[w][center] += wave[w][speed] + wave[w][center] += wave[w][speed] # Hue not currently changing? - if ( wave[w][hue] == wave[w][hue_target] ): + if (wave[w][hue] == wave[w][hue_target]): # There's a tiny random chance of picking a new hue... - if ( not random.randint(frames_per_second * 4, 255) ): + if (not random.randint(frames_per_second * 4, 255)): # Within 1/3 color wheel - wave[w][hue_target] = random.randint(wave[w][hue] - 30, wave[w][hue] + 30) + wave[w][hue_target] = random.randint( + wave[w][hue] - 30, wave[w][hue] + 30) # This wave's hue is currently shifting... - else: + else: - if ( wave[w][hue] < wave[w][hue_target] ): - wave[w][hue] += 1 # Move up or - else: - wave[w][hue] -= 1 # down as needed + if (wave[w][hue] < wave[w][hue_target]): + wave[w][hue] += 1 # Move up or + else: + wave[w][hue] -= 1 # down as needed # Reached destination? - if ( wave[w][hue] == wave[w][hue_target] ): - wave[w][hue] = 90 + wave[w][hue] % 90 # Clamp to 90-180 range - wave[w][hue_target] = wave[w][hue] # Copy to target + if (wave[w][hue] == wave[w][hue_target]): + wave[w][hue] = 90 + wave[w][hue] % 90 # Clamp to 90-180 range + wave[w][hue_target] = wave[w][hue] # Copy to target - wave[w][red] = h2rgb( wave[w][hue] - 30 ) - wave[w][green] = h2rgb( wave[w][hue] ) - wave[w][blue] = h2rgb( wave[w][hue] + 30) + wave[w][red] = h2rgb(wave[w][hue] - 30) + wave[w][green] = h2rgb(wave[w][hue]) + wave[w][blue] = h2rgb(wave[w][hue] + 30) - # Now render the LED strip using the current + # Now render the LED strip using the current # brightness & wave states. # Each LED in strip is visited just once... - for i in range(num_leds): + for i in range(num_leds): - # Transform 'i' (LED number in pixel space) to the + # Transform 'i' (LED number in pixel space) to the # equivalent point in 8-bit fixed-point space (0-255) # "* 256" because that would be # the start of the (N+1)th pixel @@ -182,72 +185,73 @@ while ( True ) : x = (i * 256 + 127) / circumference # LED assumed off, but wave colors will add up here - r = g = b = 0 + r = g = b = 0 # For each item in wave[] array... for w in range(n_waves): - # Calculate distance from pixel center to wave - # center point, using both signed and unsigned + # Calculate distance from pixel center to wave + # center point, using both signed and unsigned # 8-bit integers... - d1 = int( abs(x - wave[w][center]) ) - d2 = int( abs(x - wave[w][center]) ) + d1 = int(abs(x - wave[w][center])) + d2 = int(abs(x - wave[w][center])) - # Then take the lesser of the two, resulting in + # Then take the lesser of the two, resulting in # a distance (0-128) - # that 'wraps around' the ends of the strip as - # necessary...it's a contiguous ring, and waves + # that 'wraps around' the ends of the strip as + # necessary...it's a contiguous ring, and waves # can move smoothly across the gap. - if ( d2 < d1 ): - d1 = d2 # d1 is pixel-to-wave-center distance + if (d2 < d1): + d1 = d2 # d1 is pixel-to-wave-center distance - # d2 distance, relative to wave width, is then - # proportional to the wave's brightness at this + # d2 distance, relative to wave width, is then + # proportional to the wave's brightness at this # pixel (basic linear y=mx+b stuff). # Is distance within wave's influence? # d2 is opposite; distance to wave's end - if ( d1 < wave[w][width] ): + if (d1 < wave[w][width]): d2 = wave[w][width] - d1 - y = int ( brightness * d2 / wave[w][width] ) # 0 to 200 + y = int(brightness * d2 / wave[w][width]) # 0 to 200 - # y is a brightness scale value -- - # proportional to, but not exactly equal - # to, the resulting RGB value. - if ( y < 128 ): # Fade black to RGB color - # In HSV colorspace, this would be + # y is a brightness scale value -- + # proportional to, but not exactly equal + # to, the resulting RGB value. + if (y < 128): # Fade black to RGB color + # In HSV colorspace, this would be # tweaking 'value' - n = int(y * 2 + 1) # 1-256 - r += ( wave[w][red] * n ) >> 8 # More fixed-point math - g += ( wave[w][green] * n ) >> 8 # Wave color is scaled by 'n' - b += ( wave[w][blue] * n ) >> 8 # >>8 is equiv to /256 - else: # Fade RGB color to white + n = int(y * 2 + 1) # 1-256 + r += (wave[w][red] * n) >> 8 # More fixed-point math + # Wave color is scaled by 'n' + g += (wave[w][green] * n) >> 8 + b += (wave[w][blue] * n) >> 8 # >>8 is equiv to /256 + else: # Fade RGB color to white # In HSV colorspace, this would be tweaking 'saturation' - n = int( ( y - 128 ) * 2 ) # 0-255 affects white level - m = 256 * n - n = 256 - n # 1-256 affects RGB level + n = int((y - 128) * 2) # 0-255 affects white level + m = 256 * n + n = 256 - n # 1-256 affects RGB level r += (m + wave[w][red] * n) >> 8 g += (m + wave[w][green] * n) >> 8 b += (m + wave[w][blue] * n) >> 8 - # r,g,b are 16-bit types that accumulate brightness - # from all waves that affect this pixel; may exceed + # r,g,b are 16-bit types that accumulate brightness + # from all waves that affect this pixel; may exceed # 255. Now clip to 0-255 range: - if ( r > 255 ): + if (r > 255): r = 255 - if ( g > 255 ): + if (g > 255): g = 255 - if ( b > 255 ): + if (b > 255): b = 255 - # Store resulting RGB value and we're done with + # Store resulting RGB value and we're done with # this pixel! strip[i] = (r, g, b) - - # Once rendering is complete, a second pass is made - # through pixel data applying gamma correction, for + + # Once rendering is complete, a second pass is made + # through pixel data applying gamma correction, for # more perceptually linear colors. # https://learn.adafruit.com/led-tricks-gamma-correction - for j in range( num_leds ): - ( red_gamma, green_gamma, blue_gamma ) = strip[j] + for j in range(num_leds): + (red_gamma, green_gamma, blue_gamma) = strip[j] red_gamma = gammas[red_gamma] green_gamma = gammas[green_gamma] blue_gamma = gammas[blue_gamma] diff --git a/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py b/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py index 0c1ab7a0c..b7c3d0f46 100644 --- a/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py +++ b/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py @@ -1,67 +1,72 @@ # NeoPixel earrings example. Makes a nice blinky display with just a # few LEDs on at any time...uses MUCH less juice than rainbow display! +import time + import board import neopixel -import time + try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random numpix = 16 # Number of NeoPixels (e.g. 16-pixel ring) pixpin = board.D0 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=.3) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=.3) + def wheel(pos): - # Input a value 0 to 255 to get a color value. - # The colours are a transition r - g - b - back to r. - if (pos < 0) or (pos > 255): - return [0, 0, 0] - elif (pos < 85): - return [int(pos * 3), int(255 - (pos * 3)), 0] - elif (pos < 170): - pos -= 85 - return [int(255 - pos * 3), 0, int(pos * 3)] - else: - pos -= 170 - return [0, int(pos * 3), int(255 - pos * 3)] + # Input a value 0 to 255 to get a color value. + # The colours are a transition r - g - b - back to r. + if (pos < 0) or (pos > 255): + return [0, 0, 0] + elif (pos < 85): + return [int(pos * 3), int(255 - (pos * 3)), 0] + elif (pos < 170): + pos -= 85 + return [int(255 - pos * 3), 0, int(pos * 3)] + else: + pos -= 170 + return [0, int(pos * 3), int(255 - pos * 3)] -mode = 0 # Current animation effect -offset = 0 # Position of spinner animation -hue = 0 # Starting hue -color = wheel(hue & 255) # hue -> RGB color + +mode = 0 # Current animation effect +offset = 0 # Position of spinner animation +hue = 0 # Starting hue +color = wheel(hue & 255) # hue -> RGB color prevtime = time.monotonic() # Time of last animation mode switch while True: # Loop forever... - if mode == 0: # Random sparkles - lights just one LED at a time - i = random.randint(0, numpix - 1) # Choose random pixel - strip[i] = color # Set it to current color - strip.write() # Refresh LED states - # Set same pixel to "off" color now but DON'T refresh... - # it stays on for now...bot this and the next random - # pixel will be refreshed on the next pass. - strip[i] = [0,0,0] - time.sleep(0.008) # 8 millisecond delay - elif mode == 1: # Spinny wheel (4 LEDs on at a time) - for i in range(numpix): # For each LED... - if ((offset + i) & 7) < 2: # 2 pixels out of 8... - strip[i] = color # are set to current color - else: - strip[i] = [0,0,0] # other pixels are off - strip.write() # Refresh LED states - time.sleep(0.04) # 40 millisecond delay - offset += 1 # Shift animation by 1 pixel on next frame - if offset >= 8: offset = 0 - # Additional animation modes could be added here! + if mode == 0: # Random sparkles - lights just one LED at a time + i = random.randint(0, numpix - 1) # Choose random pixel + strip[i] = color # Set it to current color + strip.write() # Refresh LED states + # Set same pixel to "off" color now but DON'T refresh... + # it stays on for now...bot this and the next random + # pixel will be refreshed on the next pass. + strip[i] = [0, 0, 0] + time.sleep(0.008) # 8 millisecond delay + elif mode == 1: # Spinny wheel (4 LEDs on at a time) + for i in range(numpix): # For each LED... + if ((offset + i) & 7) < 2: # 2 pixels out of 8... + strip[i] = color # are set to current color + else: + strip[i] = [0, 0, 0] # other pixels are off + strip.write() # Refresh LED states + time.sleep(0.04) # 40 millisecond delay + offset += 1 # Shift animation by 1 pixel on next frame + if offset >= 8: + offset = 0 + # Additional animation modes could be added here! - t = time.monotonic() # Current time in seconds - if (t - prevtime) >= 8: # Every 8 seconds... - mode += 1 # Advance to next mode - if mode > 1: # End of modes? - mode = 0 # Start over from beginning - hue += 80 # And change color - color = wheel(hue & 255) - strip.fill([0,0,0]) # Turn off all pixels - prevtime = t # Record time of last mode change + t = time.monotonic() # Current time in seconds + if (t - prevtime) >= 8: # Every 8 seconds... + mode += 1 # Advance to next mode + if mode > 1: # End of modes? + mode = 0 # Start over from beginning + hue += 80 # And change color + color = wheel(hue & 255) + strip.fill([0, 0, 0]) # Turn off all pixels + prevtime = t # Record time of last mode change diff --git a/Gemma_LightTouch/gemma_lighttouch.py b/Gemma_LightTouch/gemma_lighttouch.py index 04ffcb255..d92d753b1 100644 --- a/Gemma_LightTouch/gemma_lighttouch.py +++ b/Gemma_LightTouch/gemma_lighttouch.py @@ -1,8 +1,9 @@ """Interactive light show using built-in LED and capacitive touch""" import time + import adafruit_dotstar -import touchio import board +import touchio led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) touch_A0 = touchio.TouchIn(board.A0) @@ -59,7 +60,6 @@ color_sequences = cycle_sequence( ] ) - cycle_speeds = cycle_sequence([0.1, 0.3, 0.5]) brightness = brightness_cycle() diff --git a/Gemma_LightTouch/red_green_blue.py b/Gemma_LightTouch/red_green_blue.py index 800686c59..fb27212ab 100644 --- a/Gemma_LightTouch/red_green_blue.py +++ b/Gemma_LightTouch/red_green_blue.py @@ -1,8 +1,9 @@ """Touch each pad to change red, green, and blue values on the LED""" import time -import touchio + import adafruit_dotstar import board +import touchio led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) touch_A0 = touchio.TouchIn(board.A0) diff --git a/Giant_Mechanical_Keyboard/code.py b/Giant_Mechanical_Keyboard/code.py index ebfe8636f..5a9b89ec5 100644 --- a/Giant_Mechanical_Keyboard/code.py +++ b/Giant_Mechanical_Keyboard/code.py @@ -6,16 +6,17 @@ # Author: Collin Cunningham # License: MIT License (https://opensource.org/licenses/MIT) -from digitalio import DigitalInOut, Direction, Pull -import board import time + +import board import neopixel from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode +from digitalio import DigitalInOut, Direction, Pull pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2) -pixels.fill((0,0,0)) +pixels.fill((0, 0, 0)) pixels.show() # The pins connected to each switch/button @@ -56,18 +57,21 @@ statusled.direction = Direction.OUTPUT print("Waiting for button presses") + def pressbutton(i): - l = leds[i] # find the switch LED - k = buttonkeys[i] # get the corresp. keycode/str - l.value = True # turn on LED - kbd.press(k) # send keycode - + l = leds[i] # find the switch LED + k = buttonkeys[i] # get the corresp. keycode/str + l.value = True # turn on LED + kbd.press(k) # send keycode + + def releasebutton(i): - l = leds[i] # find the switch LED - k = buttonkeys[i] # get the corresp. keycode/str - l.value = False # turn on LED - kbd.release(k) # send keycode - + l = leds[i] # find the switch LED + k = buttonkeys[i] # get the corresp. keycode/str + l.value = False # turn on LED + kbd.release(k) # send keycode + + def lightneopixels(): vals = [0, 0, 0] # if switch 0 pressed, show blue @@ -82,30 +86,30 @@ def lightneopixels(): vals[0] = 255 # if all pressed, show white if buttonspressed[0] and buttonspressed[1] and buttonspressed[2]: - vals = [255,255,255] + vals = [255, 255, 255] # if 0 & 1 pressed, show green if buttonspressed[0] and buttonspressed[1] and not buttonspressed[2]: - vals = [0,255,0] - pixels.fill((vals[0],vals[1],vals[2])) + vals = [0, 255, 0] + pixels.fill((vals[0], vals[1], vals[2])) pixels.show() - + while True: # check each button for button in buttons: i = buttons.index(button) - if button.value == False: # button is pressed? - buttonspressed[i] = True # save pressed button - if buttonspressedlast[i] == False: # was button not pressed last time? + if button.value == False: # button is pressed? + buttonspressed[i] = True # save pressed button + # was button not pressed last time? + if buttonspressedlast[i] == False: print("Pressed #%d" % i) pressbutton(i) else: - buttonspressed[i] = False # button was not pressed - if buttonspressedlast[i] == True: # was button pressed last time? + buttonspressed[i] = False # button was not pressed + if buttonspressedlast[i] == True: # was button pressed last time? print("Released #%d" % i) releasebutton(i) lightneopixels() # save pressed buttons as pressed last buttonspressedlast = list(buttonspressed) time.sleep(0.01) - diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink.py index 7d33238b6..ef82920c6 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink.py @@ -1,4 +1,5 @@ import time + from adafruit_circuitplayground.express import cpx while True: diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_Monotonic.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_Monotonic.py index 940d39c70..1e35fad7d 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_Monotonic.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_Monotonic.py @@ -1,4 +1,5 @@ import time + from adafruit_circuitplayground.express import cpx blink_speed = 0.5 diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_NeoPixel.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_NeoPixel.py index ab6b7941b..fd8908b92 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_NeoPixel.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Blink_NeoPixel.py @@ -1,4 +1,5 @@ import time + from adafruit_circuitplayground.express import cpx while True: diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py index b905a6b98..58f021d8d 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py @@ -1,5 +1,8 @@ import time + from adafruit_circuitplayground.express import cpx + + # pylint: disable=redefined-outer-name diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Sjopenna_Remote_Lamp.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Sjopenna_Remote_Lamp.py index 1e9723acd..489c664e5 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Sjopenna_Remote_Lamp.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Sjopenna_Remote_Lamp.py @@ -13,18 +13,18 @@ last_command = None brightness_up = 95 # Up arrow brightness_down = 79 # Down arrow -command_to_color = { # button = color - 247: (255, 0, 0), # 1 = red - 119: (255, 40, 0), # 2 = orange - 183: (255, 150, 0), # 3 = yellow - 215: (0, 255, 0), # 4 = green - 87: (0, 255, 120), # 5 = teal - 151: (0, 255, 255), # 6 = cyan - 231: (0, 0, 255), # 7 = blue - 103: (180, 0, 255), # 8 = purple - 167: (255, 0, 20), # 9 = magenta +command_to_color = { # button = color + 247: (255, 0, 0), # 1 = red + 119: (255, 40, 0), # 2 = orange + 183: (255, 150, 0), # 3 = yellow + 215: (0, 255, 0), # 4 = green + 87: (0, 255, 120), # 5 = teal + 151: (0, 255, 255), # 6 = cyan + 231: (0, 0, 255), # 7 = blue + 103: (180, 0, 255), # 8 = purple + 167: (255, 0, 20), # 9 = magenta 207: (255, 255, 255), # 0 = white - 127: (0, 0, 0), # Play/Pause = off + 127: (0, 0, 0), # Play/Pause = off } while True: diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Generators.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Generators.py index b9f511ea5..dbc6efb54 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Generators.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Generators.py @@ -1,5 +1,8 @@ import time + from adafruit_circuitplayground.express import cpx + + # pylint: disable=stop-iteration-return @@ -9,12 +12,12 @@ def wheel(pos): if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: - return int(255 - pos*3), int(pos*3), 0 + return int(255 - pos * 3), int(pos * 3), 0 if pos < 170: pos -= 85 - return 0, int(255 - pos*3), int(pos*3) + return 0, int(255 - pos * 3), int(pos * 3) pos -= 170 - return int(pos * 3), 0, int(255 - (pos*3)) + return int(pos * 3), 0, int(255 - (pos * 3)) def cycle_sequence(seq): @@ -32,13 +35,13 @@ def rainbow_lamp(seq): color_sequences = cycle_sequence([ range(256), # rainbow_cycle - [0], # red - [10], # orange - [30], # yellow - [85], # green - [137], # cyan - [170], # blue - [213], # purple + [0], # red + [10], # orange + [30], # yellow + [85], # green + [137], # cyan + [170], # blue + [213], # purple [0, 10, 30, 85, 137, 170, 213], # party mode ]) diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py index 1b335192e..2684e3c69 100755 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py @@ -1,4 +1,5 @@ import time + from adafruit_circuitplayground.express import cpx @@ -8,12 +9,12 @@ def wheel(pos): if pos < 0 or pos > 255: return 0, 0, 0 if pos < 85: - return int(255 - pos*3), int(pos*3), 0 + return int(255 - pos * 3), int(pos * 3), 0 if pos < 170: pos -= 85 - return 0, int(255 - pos*3), int(pos*3) + return 0, int(255 - pos * 3), int(pos * 3) pos -= 170 - return int(pos * 3), 0, int(255 - (pos*3)) + return int(pos * 3), 0, int(255 - (pos * 3)) # pylint: disable=redefined-outer-name @@ -27,6 +28,8 @@ def right_side(x, y, z): def left_side(x, y, z): return abs(9.8 - x) < accel_threshold and abs(y) < accel_threshold and abs(z) < accel_threshold + + # pylint: enable=redefined-outer-name @@ -54,13 +57,13 @@ def brightness_lamp(): color_sequences = cycle_sequence([ range(256), # rainbow_cycle - [0], # red - [10], # orange - [30], # yellow - [85], # green - [137], # cyan - [170], # blue - [213], # purple + [0], # red + [10], # orange + [30], # yellow + [85], # green + [137], # cyan + [170], # blue + [213], # purple [0, 10, 30, 85, 137, 170, 213], # party mode ]) diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_Dictionary.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_Dictionary.py index acbd3ab31..2f0d436b1 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_Dictionary.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_Dictionary.py @@ -1,13 +1,13 @@ from adafruit_circuitplayground.express import cpx touchpad_to_color = { - "touch_A1": (255, 0, 0), # red - "touch_A2": (255, 40, 0), # orange + "touch_A1": (255, 0, 0), # red + "touch_A2": (255, 40, 0), # orange "touch_A3": (255, 150, 0), # yellow - "touch_A4": (0, 255, 0), # green - "touch_A5": (0, 0, 255), # blue + "touch_A4": (0, 255, 0), # green + "touch_A5": (0, 0, 255), # blue "touch_A6": (180, 0, 255), # purple - "touch_A7": (0, 0, 0), # off + "touch_A7": (0, 0, 0), # off } while True: diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_if_elif.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_if_elif.py index 32513ddfc..a01ec9564 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_if_elif.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Touch_NeoPixel_if_elif.py @@ -2,16 +2,16 @@ from adafruit_circuitplayground.express import cpx while True: if cpx.touch_A1: - cpx.pixels.fill((255, 0, 0)) # red + cpx.pixels.fill((255, 0, 0)) # red elif cpx.touch_A2: - cpx.pixels.fill((255, 40, 0)) # orange + cpx.pixels.fill((255, 40, 0)) # orange elif cpx.touch_A3: cpx.pixels.fill((255, 150, 0)) # yellow elif cpx.touch_A4: - cpx.pixels.fill((0, 255, 0)) # green + cpx.pixels.fill((0, 255, 0)) # green elif cpx.touch_A5: - cpx.pixels.fill((0, 0, 255)) # blue + cpx.pixels.fill((0, 0, 255)) # blue elif cpx.touch_A6: cpx.pixels.fill((180, 0, 255)) # purple elif cpx.touch_A7: - cpx.pixels.fill((0, 0, 0)) # off + cpx.pixels.fill((0, 0, 0)) # off diff --git a/Interior_Purse_Light/Interior_Purse_Light.py b/Interior_Purse_Light/Interior_Purse_Light.py index 717b1448d..7f792f3bd 100644 --- a/Interior_Purse_Light/Interior_Purse_Light.py +++ b/Interior_Purse_Light/Interior_Purse_Light.py @@ -1,7 +1,8 @@ -from digitalio import DigitalInOut, Direction, Pull -import board import time +import board +from digitalio import DigitalInOut, Direction, Pull + button = DigitalInOut(board.D1) button.direction = Direction.INPUT button.pull = Pull.UP @@ -11,8 +12,8 @@ led.direction = Direction.OUTPUT while True: if button.value: - led.value = True # check if the pushbutton is pressed. + led.value = True # check if the pushbutton is pressed. else: - led.value = False # turn LED off + led.value = False # turn LED off - time.sleep(0.01) # debounce delay + time.sleep(0.01) # debounce delay diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AnalogIn.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AnalogIn.py index 8b36d95a0..5c858634f 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AnalogIn.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AnalogIn.py @@ -3,15 +3,18 @@ # connected to GND, 3.3V, and pin A1 # and prints the results to the REPL -from analogio import AnalogIn -import board import time +import board +from analogio import AnalogIn + analogin = AnalogIn(board.A1) -def getVoltage(pin): # helper + +def getVoltage(pin): # helper return (pin.value * 3.3) / 65536 + while True: print("Analog Voltage: %f" % getVoltage(analogin)) - time.sleep(0.1) \ No newline at end of file + time.sleep(0.1) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioFiles.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioFiles.py index b65d81cdc..edbf59e97 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioFiles.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioFiles.py @@ -1,6 +1,6 @@ -from digitalio import DigitalInOut, Direction, Pull import audioio import board +from digitalio import DigitalInOut, Direction, Pull # enable the speaker spkrenable = DigitalInOut(board.SPEAKER_ENABLE) @@ -19,8 +19,9 @@ buttonB.pull = Pull.DOWN # The two files assigned to buttons A & B audiofiles = ["rimshot.wav", "laugh.wav"] + def play_file(filename): - print("playing file "+filename) + print("playing file " + filename) f = open(filename, "rb") a = audioio.AudioOut(board.A0, f) a.play() @@ -28,6 +29,7 @@ def play_file(filename): pass print("finished") + while True: if buttonA.value: play_file(audiofiles[0]) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioSine.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioSine.py index f9a4fdb6c..297ae9b58 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioSine.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_AudioSine.py @@ -1,11 +1,12 @@ -from digitalio import DigitalInOut, Direction +import array +import math +import time + import audioio import board -import array -import time -import math +from digitalio import DigitalInOut, Direction -FREQUENCY = 440 # 440 Hz middle 'A' +FREQUENCY = 440 # 440 Hz middle 'A' SAMPLERATE = 8000 # 8000 samples/second, recommended! # Generate one period of sine wav. @@ -22,5 +23,5 @@ spkrenable.value = True sample = audioio.AudioOut(board.SPEAKER, sine_wave) sample.frequency = SAMPLERATE sample.play(loop=True) # keep playing the sample over and over -time.sleep(1) # until... -sample.stop() # we tell the board to stop +time.sleep(1) # until... +sample.stop() # we tell the board to stop diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky.py index 43a70018c..f61c9a996 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky.py @@ -1,14 +1,15 @@ # CircuitPlaygroundExpress_Blinky -import digitalio -import board import time -led = digitalio.DigitalInOut(board.D13) #defines the variable 'led' -led.direction = digitalio.Direction.OUTPUT #set the pin as output +import board +import digitalio -while True: #code below this point loops over and over - led.value = True #turn on the LED - time.sleep(0.5) #pause - led.value = False #turn off the LED - time.sleep(0.5) #pause +led = digitalio.DigitalInOut(board.D13) # defines the variable 'led' +led.direction = digitalio.Direction.OUTPUT # set the pin as output + +while True: # code below this point loops over and over + led.value = True # turn on the LED + time.sleep(0.5) # pause + led.value = False # turn off the LED + time.sleep(0.5) # pause diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky_cpx.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky_cpx.py index 8be6f8a10..a0f0998ed 100755 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky_cpx.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Blinky_cpx.py @@ -1,6 +1,7 @@ -from adafruit_circuitplayground.express import cpx import time +from adafruit_circuitplayground.express import cpx + while True: cpx.red_led = True time.sleep(0.5) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_CapTouch.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_CapTouch.py index fd2861750..ef1134fde 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_CapTouch.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_CapTouch.py @@ -1,9 +1,10 @@ -#CircuitPlaygroundExpress_CapTouch +# CircuitPlaygroundExpress_CapTouch -import touchio -import board import time +import board +import touchio + touch1 = touchio.TouchIn(board.A1) touch2 = touchio.TouchIn(board.A2) touch3 = touchio.TouchIn(board.A3) @@ -12,7 +13,6 @@ touch5 = touchio.TouchIn(board.A5) touch6 = touchio.TouchIn(board.A6) touch7 = touchio.TouchIn(board.A7) - while True: if touch1.value: print("A1 touched!") diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py index 575444a57..35b256bc7 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py @@ -1,9 +1,10 @@ # CircuitPlaygroundExpress_DigitalIO -from digitalio import DigitalInOut, Direction, Pull -import board import time +import board +from digitalio import DigitalInOut, Direction, Pull + led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py index ad04865a0..1f8afd474 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py @@ -1,12 +1,12 @@ # CircuitPlaygroundExpress_HIDKeyboard -from digitalio import DigitalInOut, Direction, Pull -import touchio -import board import time + +import board from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode +from digitalio import DigitalInOut, Direction, Pull # A simple neat keyboard demo in circuitpython @@ -43,22 +43,22 @@ while True: # when released, the keycode or string will be sent # this prevents rapid-fire repeats! for button in buttons: - if button.value: # pressed? + if button.value: # pressed? i = buttons.index(button) print("Button #%d Pressed" % i) # turn on the LED led.value = True - while button.value: + while button.value: pass # wait for it to be released! # type the keycode or string - k = buttonkeys[i] # get the corresp. keycode/str + k = buttonkeys[i] # get the corresp. keycode/str if type(k) is str: layout.write(k) else: - kbd.press(controlkey, k) # press... - kbd.release_all() # release! + kbd.press(controlkey, k) # press... + kbd.release_all() # release! # turn off the LED led.value = False diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor.py index caac2f4f1..905a6597c 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor.py @@ -1,29 +1,30 @@ # CircuitPlaygroundExpress_LightSensor # reads the on-board light sensor and graphs the brighness with NeoPixels -from simpleio import map_range -from analogio import AnalogIn -import board -import neopixel import time +import board +import neopixel +from analogio import AnalogIn +from simpleio import map_range + pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=0, brightness=.05) -pixels.fill((0,0,0)) +pixels.fill((0, 0, 0)) pixels.show() analogin = AnalogIn(board.LIGHT) while True: - #light value remaped to pixel position + # light value remaped to pixel position peak = map_range(analogin.value, 2000, 62000, 0, 9) print(analogin.value) print(int(peak)) for i in range(0, 9, 1): - if i <= peak: - pixels[i] = (0, 255, 0) - else: - pixels[i] = (0,0,0) + if i <= peak: + pixels[i] = (0, 255, 0) + else: + pixels[i] = (0, 0, 0) pixels.show() time.sleep(0.01) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py index 8c5631a9d..d5341906d 100755 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_LightSensor_cpx.py @@ -1,14 +1,15 @@ # CircuitPlaygroundExpress_LightSensor # reads the on-board light sensor and graphs the brighness with NeoPixels +import time + from adafruit_circuitplayground.express import cpx from simpleio import map_range -import time cpx.pixels.brightness = 0.05 while True: - #light value remaped to pixel position + # light value remaped to pixel position peak = map_range(cpx.light, 10, 325, 0, 9) print(cpx.light) print(int(peak)) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_NeoPixel.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_NeoPixel.py index bdcbbb0bf..f9117b760 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_NeoPixel.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_NeoPixel.py @@ -1,51 +1,56 @@ # CircuitPlaygroundExpress_NeoPixel +import time + import board import neopixel -import time pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2) -pixels.fill((0,0,0)) +pixels.fill((0, 0, 0)) pixels.show() -#choose which demos to play +# choose which demos to play # 1 means play, 0 means don't! simpleCircleDemo = 1 flashDemo = 1 rainbowDemo = 1 rainbowCycleDemo = 1 + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 85: - return (int(pos*3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif pos < 170: pos -= 85 - return (int(255 - (pos*3)), 0, int(pos*3)) + return (int(255 - (pos * 3)), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) + def rainbow_cycle(wait): for j in range(255): for i in range(len(pixels)): - idx = int ((i * 256 / len(pixels)) + j*10) + idx = int((i * 256 / len(pixels)) + j * 10) pixels[i] = wheel(idx & 255) pixels.show() time.sleep(wait) + def rainbow(wait): for j in range(255): for i in range(len(pixels)): - idx = int (i+j) + idx = int(i + j) pixels[i] = wheel(idx & 255) pixels.show() time.sleep(wait) + def simpleCircle(wait): - RED = 0x100000 # (0x10, 0, 0) also works - YELLOW=(0x10, 0x10, 0) + RED = 0x100000 # (0x10, 0, 0) also works + YELLOW = (0x10, 0x10, 0) GREEN = (0, 0x10, 0) AQUA = (0, 0x10, 0x10) BLUE = (0, 0, 0x10) @@ -93,7 +98,7 @@ while True: print('Simple Circle Demo') simpleCircle(.05) - if flashDemo: #this will play if flashDemo = 1 up above + if flashDemo: # this will play if flashDemo = 1 up above print('Flash Demo') pixels.fill((255, 0, 0)) pixels.show() diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Neopixel_cpx.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Neopixel_cpx.py index de191d219..8ed199be6 100755 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Neopixel_cpx.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Neopixel_cpx.py @@ -1,6 +1,7 @@ -from adafruit_circuitplayground.express import cpx import time +from adafruit_circuitplayground.express import cpx + # choose which demos to play # 1 means play, 0 means don't! simpleCircleDemo = 1 @@ -16,17 +17,18 @@ BLUE = (0, 0, 10) PURPLE = (10, 0, 10) BLACK = (0, 0, 0) + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 85: - return (int(pos*3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif pos < 170: pos -= 85 - return (int(255 - (pos*3)), 0, int(pos*3)) + return (int(255 - (pos * 3)), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) while True: @@ -83,7 +85,7 @@ while True: print('Rainbow Demo') for j in range(255): for i in range(len(cpx.pixels)): - idx = int(i+j) + idx = int(i + j) cpx.pixels[i] = wheel(idx & 255) time.sleep(.001) @@ -91,6 +93,6 @@ while True: print('Rainbow Cycle Demo') for j in range(255): for i in range(len(cpx.pixels)): - idx = int((i * 256 / len(cpx.pixels)) + j*10) + idx = int((i * 256 / len(cpx.pixels)) + j * 10) cpx.pixels[i] = wheel(idx & 255) time.sleep(.001) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py index a04c57b8d..bdf45a254 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py @@ -22,15 +22,16 @@ # THE SOFTWARE. import array +import math + import audiobusio import board -import math import neopixel # Exponential scaling factor. # Should probably be in range -10 .. 10 to be reasonable. CURVE = 2 -SCALE_EXPONENT = math.pow(10, CURVE*-0.1) +SCALE_EXPONENT = math.pow(10, CURVE * -0.1) PEAK_COLOR = (100, 0, 255) NUM_PIXELS = 10 @@ -38,34 +39,50 @@ NUM_PIXELS = 10 # Number of samples to read at once. NUM_SAMPLES = 160 + # Restrict value to be between floor and ceiling. + + def constrain(value, floor, ceiling): return max(floor, min(value, ceiling)) + # Scale input_value to be between output_min and output_max, in an exponential way. + + def log_scale(input_value, input_min, input_max, output_min, output_max): - normalized_input_value = (input_value - input_min) / (input_max - input_min) + normalized_input_value = (input_value - input_min) / \ + (input_max - input_min) return output_min + math.pow(normalized_input_value, SCALE_EXPONENT) * (output_max - output_min) + # Remove DC bias before computing RMS. + + def normalized_rms(values): minbuf = int(mean(values)) - return math.sqrt(sum(float(sample-minbuf)*(sample-minbuf) for sample in values) / len(values)) + return math.sqrt(sum(float(sample - minbuf) * (sample - minbuf) for sample in values) / len(values)) + def mean(values): return (sum(values) / len(values)) + def volume_color(i): - return (200, i*(255//NUM_PIXELS), 0) + return (200, i * (255 // NUM_PIXELS), 0) + # Main program + # Set up NeoPixels and turn them all off. -pixels = neopixel.NeoPixel(board.NEOPIXEL, NUM_PIXELS, brightness=0.1, auto_write=False) +pixels = neopixel.NeoPixel(board.NEOPIXEL, NUM_PIXELS, + brightness=0.1, auto_write=False) pixels.fill(0) pixels.show() -mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, frequency=16000, bit_depth=16) +mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, + board.MICROPHONE_DATA, frequency=16000, bit_depth=16) # Record an initial sample to calibrate. Assume it's quiet when we start. samples = array.array('H', [0] * NUM_SAMPLES) mic.record(samples, len(samples)) @@ -89,7 +106,8 @@ while True: # print(magnitude) # Compute scaled logarithmic reading in the range 0 to NUM_PIXELS - c = log_scale(constrain(magnitude, input_floor, input_ceiling), input_floor, input_ceiling, 0, NUM_PIXELS) + c = log_scale(constrain(magnitude, input_floor, input_ceiling), + input_floor, input_ceiling, 0, NUM_PIXELS) # Light up pixels that are below the scaled and interpolated magnitude. pixels.fill(0) @@ -98,7 +116,7 @@ while True: pixels[i] = volume_color(i) # Light up the peak pixel and animate it slowly dropping. if c >= peak: - peak = min(c, NUM_PIXELS-1) + peak = min(c, NUM_PIXELS - 1) elif peak > 0: peak = peak - 1 if peak > 0: diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py index a9a3476e1..bab712f74 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py @@ -1,15 +1,16 @@ # CircuitPlaygroundExpress_Temperature # reads the on-board temperature sensor and prints the value -import adafruit_thermistor -import board import time -thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950) +import adafruit_thermistor +import board +thermistor = adafruit_thermistor.Thermistor( + board.TEMPERATURE, 10000, 10000, 25, 3950) while True: print("Temperature is: %f C and %f F" % (thermistor.temperature, - (thermistor.temperature*9/5+32))) + (thermistor.temperature * 9 / 5 + 32))) time.sleep(0.25) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature_cpx.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature_cpx.py index 9270842ad..0bd30e93e 100755 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature_cpx.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature_cpx.py @@ -1,6 +1,7 @@ -from adafruit_circuitplayground.express import cpx import time +from adafruit_circuitplayground.express import cpx + while True: print(cpx.temperature) time.sleep(0.5) diff --git a/Introducing_CircuitPlaygroundExpress/Playground_808.py b/Introducing_CircuitPlaygroundExpress/Playground_808.py index cb478693b..9aa8fac0a 100644 --- a/Introducing_CircuitPlaygroundExpress/Playground_808.py +++ b/Introducing_CircuitPlaygroundExpress/Playground_808.py @@ -1,12 +1,13 @@ # Playground 808 # Drum machine -from digitalio import DigitalInOut, Direction -import audioio -import touchio -import board import time -bpm = 120 #beats per minute for sustained hold, change this to suit your tempo +import audioio +import board +import touchio +from digitalio import DigitalInOut, Direction + +bpm = 120 # beats per minute for sustained hold, change this to suit your tempo # enable the speaker spkrenable = DigitalInOut(board.SPEAKER_ENABLE) @@ -23,15 +24,17 @@ for i in range(7): # The seven files assigned to the touchpads audiofiles = ["bd_tek.wav", "elec_hi_snare.wav", "elec_cymbal.wav", - "elec_blip2.wav", "bd_zome.wav", "bass_hit_c.wav", - "drum_cowbell.wav"] + "elec_blip2.wav", "bd_zome.wav", "bass_hit_c.wav", + "drum_cowbell.wav"] + def play_file(filename): - print("playing file "+filename) + print("playing file " + filename) f = open(filename, "rb") a = audioio.AudioOut(board.A0, f) a.play() - time.sleep(bpm/960) #sixteenthNote delay + time.sleep(bpm / 960) # sixteenthNote delay + while True: diff --git a/Introducing_Gemma_M0/Gemma_AnalogIn.py b/Introducing_Gemma_M0/Gemma_AnalogIn.py index bee72d1e1..f4059ba25 100644 --- a/Introducing_Gemma_M0/Gemma_AnalogIn.py +++ b/Introducing_Gemma_M0/Gemma_AnalogIn.py @@ -1,10 +1,11 @@ # Gemma IO demo - analog inputs -from digitalio import DigitalInOut, Direction -from analogio import AnalogIn -import board import time +import board +from analogio import AnalogIn +from digitalio import DigitalInOut, Direction + led = DigitalInOut(board.L) led.direction = Direction.OUTPUT @@ -12,9 +13,11 @@ analog0in = AnalogIn(board.A0) analog1in = AnalogIn(board.A1) analog2in = AnalogIn(board.A2) + def getVoltage(pin): return (pin.value * 3.3) / 65536 + while True: print("A0: %f \t\t A1: %f \t\t A2: %f" % (getVoltage(analog0in), diff --git a/Introducing_Gemma_M0/Gemma_AnalogOut.py b/Introducing_Gemma_M0/Gemma_AnalogOut.py index 8bda102e4..85f307a63 100644 --- a/Introducing_Gemma_M0/Gemma_AnalogOut.py +++ b/Introducing_Gemma_M0/Gemma_AnalogOut.py @@ -1,13 +1,12 @@ # CircuitPython IO demo - analog output - -from analogio import AnalogOut + import board -import time - +from analogio import AnalogOut + aout = AnalogOut(board.A0) - + while True: - # Count up from 0 to 65535, with 64 increment - # which ends up corresponding to the DAC's 10-bit range - for i in range (0,65535,64): - aout.value = i + # Count up from 0 to 65535, with 64 increment + # which ends up corresponding to the DAC's 10-bit range + for i in range(0, 65535, 64): + aout.value = i diff --git a/Introducing_Gemma_M0/Gemma_CapTouch.py b/Introducing_Gemma_M0/Gemma_CapTouch.py index 0f4f7dcd2..98c9dc8b3 100644 --- a/Introducing_Gemma_M0/Gemma_CapTouch.py +++ b/Introducing_Gemma_M0/Gemma_CapTouch.py @@ -1,9 +1,10 @@ # Gemma IO demo - captouch -import touchio -import board import time +import board +import touchio + touch0 = touchio.TouchIn(board.A0) touch1 = touchio.TouchIn(board.A1) touch2 = touchio.TouchIn(board.A2) diff --git a/Introducing_Gemma_M0/Gemma_DigitalIO.py b/Introducing_Gemma_M0/Gemma_DigitalIO.py index 61f8a4b4f..5eefbb63c 100644 --- a/Introducing_Gemma_M0/Gemma_DigitalIO.py +++ b/Introducing_Gemma_M0/Gemma_DigitalIO.py @@ -1,9 +1,10 @@ # CircuitPython IO demo #1 - General Purpose I/O -from digitalio import DigitalInOut, Direction, Pull -import board import time +import board +from digitalio import DigitalInOut, Direction, Pull + led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT @@ -14,8 +15,8 @@ button.pull = Pull.UP while True: # we could also just do "led.value = not button.value" ! if button.value: - led.value = False + led.value = False else: - led.value = True + led.value = True - time.sleep(0.01) # debounce delay + time.sleep(0.01) # debounce delay diff --git a/Introducing_Gemma_M0/Gemma_DotStar.py b/Introducing_Gemma_M0/Gemma_DotStar.py index 97d9c8ac3..d8b847412 100644 --- a/Introducing_Gemma_M0/Gemma_DotStar.py +++ b/Introducing_Gemma_M0/Gemma_DotStar.py @@ -1,34 +1,38 @@ # CircuitPython demo - Dotstar -import board -import adafruit_dotstar import time +import adafruit_dotstar +import board + numpix = 64 strip = adafruit_dotstar.DotStar(board.D2, board.D0, numpix, brightness=0.2) + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) + def rainbow_cycle(wait): for j in range(255): for i in range(len(strip)): - idx = int ((i * 256 / len(strip)) + j) + idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) strip.show() time.sleep(wait) + while True: strip.fill((255, 0, 0)) strip.show() @@ -42,4 +46,4 @@ while True: strip.show() time.sleep(1) - rainbow_cycle(0.001) # high speed rainbow cycle w/1ms delay per sweep + rainbow_cycle(0.001) # high speed rainbow cycle w/1ms delay per sweep diff --git a/Introducing_Gemma_M0/Gemma_HIDkeyboard.py b/Introducing_Gemma_M0/Gemma_HIDkeyboard.py index 8650738e1..0bfa30d42 100644 --- a/Introducing_Gemma_M0/Gemma_HIDkeyboard.py +++ b/Introducing_Gemma_M0/Gemma_HIDkeyboard.py @@ -1,12 +1,12 @@ # CircuitPlayground demo - Keyboard emu -from digitalio import DigitalInOut, Direction, Pull -import touchio -import board import time + +import board from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode +from digitalio import DigitalInOut, Direction, Pull # A simple neat keyboard demo in circuitpython @@ -29,18 +29,18 @@ layout = KeyboardLayoutUS(kbd) for pin in buttonpins: button = DigitalInOut(pin) button.direction = Direction.INPUT - button.pull = Pull.UP + button.pull = Pull.UP buttons.append(button) led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT - + print("Waiting for button presses") while True: # check each button for button in buttons: - if not button.value: # pressed? + if not button.value: # pressed? i = buttons.index(button) print("Button #%d Pressed" % i) @@ -50,14 +50,14 @@ while True: while not button.value: pass # wait for it to be released! # type the keycode or string - k = buttonkeys[i] # get the corresp. keycode/str + k = buttonkeys[i] # get the corresp. keycode/str if type(k) is str: layout.write(k) else: - kbd.press(controlkey, k) # press... - kbd.release_all() # release! + kbd.press(controlkey, k) # press... + kbd.release_all() # release! # turn off the LED led.value = False - + time.sleep(0.01) diff --git a/Introducing_Gemma_M0/Gemma_I2CScan.py b/Introducing_Gemma_M0/Gemma_I2CScan.py index 66f586e3d..63b65375e 100644 --- a/Introducing_Gemma_M0/Gemma_I2CScan.py +++ b/Introducing_Gemma_M0/Gemma_I2CScan.py @@ -1,8 +1,9 @@ # Gemma/Trinket IO demo - I2C scan +import time + import board import busio -import time # can also use board.SDA and board.SCL for neater looking code! i2c = busio.I2C(board.D2, board.D0) diff --git a/Introducing_Gemma_M0/Gemma_I2Csi7021.py b/Introducing_Gemma_M0/Gemma_I2Csi7021.py index 470afca2d..ff4e7121a 100644 --- a/Introducing_Gemma_M0/Gemma_I2Csi7021.py +++ b/Introducing_Gemma_M0/Gemma_I2Csi7021.py @@ -1,9 +1,10 @@ # I2C sensor demo +import time + +import adafruit_si7021 import board import busio -import adafruit_si7021 -import time i2c = busio.I2C(board.SCL, board.SDA) @@ -18,8 +19,8 @@ i2c.unlock() # Create library object on our I2C port si7021 = adafruit_si7021.SI7021(i2c) - # Use library to read the data! while True: - print("Temp: %0.2F *C Humidity: %0.1F %%" % (si7021.temperature, si7021.relative_humidity)) + print("Temp: %0.2F *C Humidity: %0.1F %%" % + (si7021.temperature, si7021.relative_humidity)) time.sleep(1) diff --git a/Introducing_Gemma_M0/Gemma_Logger.py b/Introducing_Gemma_M0/Gemma_Logger.py index a8fa70889..fe43400d7 100644 --- a/Introducing_Gemma_M0/Gemma_Logger.py +++ b/Introducing_Gemma_M0/Gemma_Logger.py @@ -1,7 +1,8 @@ +import time + import board import digitalio import microcontroller -import time led = digitalio.DigitalInOut(board.D13) led.switch_to_output() diff --git a/Introducing_Gemma_M0/Gemma_Logger_boot.py b/Introducing_Gemma_M0/Gemma_Logger_boot.py index 13082b5b2..10d73a6e7 100644 --- a/Introducing_Gemma_M0/Gemma_Logger_boot.py +++ b/Introducing_Gemma_M0/Gemma_Logger_boot.py @@ -1,5 +1,5 @@ -import digitalio import board +import digitalio import storage switch = digitalio.DigitalInOut(board.D0) diff --git a/Introducing_Gemma_M0/Gemma_NeoPixel.py b/Introducing_Gemma_M0/Gemma_NeoPixel.py index 85808444b..6f61a7fd6 100644 --- a/Introducing_Gemma_M0/Gemma_NeoPixel.py +++ b/Introducing_Gemma_M0/Gemma_NeoPixel.py @@ -1,8 +1,9 @@ # CircuitPython demo - NeoPixel +import time + import board import neopixel -import time pixpin = board.D1 numpix = 10 @@ -16,22 +17,24 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) + def rainbow_cycle(wait): for j in range(255): for i in range(len(strip)): - idx = int ((i * 256 / len(strip)) + j) + idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) strip.write() time.sleep(wait) + while True: strip.fill((255, 0, 0)) strip.write() @@ -45,4 +48,4 @@ while True: strip.write() time.sleep(1) - rainbow_cycle(0.001) # rainbowcycle with 1ms delay per step + rainbow_cycle(0.001) # rainbowcycle with 1ms delay per step diff --git a/Introducing_Gemma_M0/Gemma_Touch_DotStar.py b/Introducing_Gemma_M0/Gemma_Touch_DotStar.py index 7d8b7436b..070099581 100644 --- a/Introducing_Gemma_M0/Gemma_Touch_DotStar.py +++ b/Introducing_Gemma_M0/Gemma_Touch_DotStar.py @@ -1,10 +1,11 @@ # Gemma IO demo - captouch to dotstar -import touchio -import busio -import board import time +import board +import busio +import touchio + dotstar = busio.SPI(board.APA102_SCK, board.APA102_MOSI) touch0 = touchio.TouchIn(board.A0) touch1 = touchio.TouchIn(board.A1) @@ -12,6 +13,7 @@ touch2 = touchio.TouchIn(board.A2) r = g = b = 0 + def setPixel(red, green, blue): if not dotstar.try_lock(): return @@ -24,12 +26,13 @@ def setPixel(red, green, blue): dotstar.unlock() time.sleep(0.01) + while True: if touch0.value: - r = (r+1) % 256 + r = (r + 1) % 256 if touch1.value: - g = (g+1) % 256 + g = (g + 1) % 256 if touch2.value: - b = (b+1) % 256 + b = (b + 1) % 256 setPixel(r, g, b) diff --git a/Introducing_Gemma_M0/Gemma_UART.py b/Introducing_Gemma_M0/Gemma_UART.py index 2dce92bf9..f33d45666 100644 --- a/Introducing_Gemma_M0/Gemma_UART.py +++ b/Introducing_Gemma_M0/Gemma_UART.py @@ -1,9 +1,8 @@ # Gemma IO demo - USB/Serial echo -from digitalio import * -from board import * import busio -import time +from board import * +from digitalio import * led = DigitalInOut(D13) led.direction = Direction.OUTPUT @@ -12,12 +11,13 @@ uart = busio.UART(D0, D2, baudrate=9600) while True: data = uart.read(32) # read up to 32 bytes - #print(data) # this is a bytearray type + # print(data) # this is a bytearray type if data != None: led.value = True - datastr = ''.join([chr(b) for b in data]) # convert bytearray to string - print(datastr, end="") + # convert bytearray to string + datastr = ''.join([chr(b) for b in data]) + print(datastr, end="") led.value = False diff --git a/Introducing_Gemma_M0/dht22.py b/Introducing_Gemma_M0/dht22.py index cad43e513..8d727b31e 100644 --- a/Introducing_Gemma_M0/dht22.py +++ b/Introducing_Gemma_M0/dht22.py @@ -1,9 +1,9 @@ -import board import time + import adafruit_dht +import board - -dht = adafruit_dht.DHT22(board.D2) +dht = adafruit_dht.DHT22(board.D2) while True: try: @@ -13,6 +13,6 @@ while True: print("Temp: {:.1f} *C \t Humidity: {}% ".format(temperature, humidity)) except RuntimeError as e: # Reading doesn't always work! Just print error and we'll try again - print("Reading from DHT failure: ",e.args) + print("Reading from DHT failure: ", e.args) time.sleep(1) diff --git a/Introducing_Gemma_M0/piezo_manual.py b/Introducing_Gemma_M0/piezo_manual.py index 122d42778..5260795de 100644 --- a/Introducing_Gemma_M0/piezo_manual.py +++ b/Introducing_Gemma_M0/piezo_manual.py @@ -1,14 +1,16 @@ -import pulseio import time -import board -piezo = pulseio.PWMOut(board.D2, duty_cycle=0, frequency=440, variable_frequency=True) +import board +import pulseio + +piezo = pulseio.PWMOut(board.D2, duty_cycle=0, + frequency=440, variable_frequency=True) while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): - piezo.frequency = f - piezo.duty_cycle =65536//2 # on 50% - time.sleep(0.25) # on for 1/4 second - piezo.duty_cycle = 0 # off - time.sleep(0.05) # pause between notes + piezo.frequency = f + piezo.duty_cycle = 65536 // 2 # on 50% + time.sleep(0.25) # on for 1/4 second + piezo.duty_cycle = 0 # off + time.sleep(0.05) # pause between notes time.sleep(0.5) diff --git a/Introducing_Gemma_M0/piezo_simpleio.py b/Introducing_Gemma_M0/piezo_simpleio.py index 7bb58628e..b09657d2e 100644 --- a/Introducing_Gemma_M0/piezo_simpleio.py +++ b/Introducing_Gemma_M0/piezo_simpleio.py @@ -1,10 +1,10 @@ -import pulseio import time + import board import simpleio while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): - simpleio.tone(board.D2, f, 0.25) # on for 1/4 second - time.sleep(0.05) # pause between notes + simpleio.tone(board.D2, f, 0.25) # on for 1/4 second + time.sleep(0.05) # pause between notes time.sleep(0.5) diff --git a/Introducing_Gemma_M0/servosweep.py b/Introducing_Gemma_M0/servosweep.py index 3a4377f6c..7f9a5c1cd 100644 --- a/Introducing_Gemma_M0/servosweep.py +++ b/Introducing_Gemma_M0/servosweep.py @@ -1,4 +1,5 @@ import time + import board import simpleio @@ -6,9 +7,9 @@ servo = simpleio.Servo(board.D2) # sweep back and forth! while True: - for angle in range (0, 180, 5): # 0-180 degrees, 5 degrees at a time - servo.angle = angle - time.sleep(0.05) - for angle in range (180, 0, -5): # 180-0 degrees, 5 degrees at a time - servo.angle = angle - time.sleep(0.05) + for angle in range(0, 180, 5): # 0-180 degrees, 5 degrees at a time + servo.angle = angle + time.sleep(0.05) + for angle in range(180, 0, -5): # 180-0 degrees, 5 degrees at a time + servo.angle = angle + time.sleep(0.05) diff --git a/Introducing_Trinket_M0/Trinket_AnalogIn.py b/Introducing_Trinket_M0/Trinket_AnalogIn.py index 269e83044..f227ac818 100644 --- a/Introducing_Trinket_M0/Trinket_AnalogIn.py +++ b/Introducing_Trinket_M0/Trinket_AnalogIn.py @@ -1,23 +1,26 @@ # Trinket IO demo - analog inputs -from analogio import AnalogIn -import board import time +import board +from analogio import AnalogIn + analog0in = AnalogIn(board.D0) analog1in = AnalogIn(board.D1) analog2in = AnalogIn(board.D2) analog3in = AnalogIn(board.D3) analog4in = AnalogIn(board.D4) + def getVoltage(pin): return (pin.value * 3.3) / 65536 + while True: print("D0: %0.2f \t D1: %0.2f \t D2: %0.2f \t D3: %0.2f \t D4: %0.2f" % (getVoltage(analog0in), getVoltage(analog1in), getVoltage(analog2in), getVoltage(analog3in), - getVoltage(analog4in) )) + getVoltage(analog4in))) time.sleep(0.1) diff --git a/Introducing_Trinket_M0/Trinket_AnalogOut.py b/Introducing_Trinket_M0/Trinket_AnalogOut.py index 927eb0da0..d56ed8f03 100644 --- a/Introducing_Trinket_M0/Trinket_AnalogOut.py +++ b/Introducing_Trinket_M0/Trinket_AnalogOut.py @@ -1,13 +1,12 @@ # Trinket IO demo - analog output -from analogio import AnalogOut import board -import time - +from analogio import AnalogOut + aout = AnalogOut(board.D1) while True: - # Count up from 0 to 65535, with 64 increment - # which ends up corresponding to the DAC's 10-bit range - for i in range (0,65535,64): - aout.value = i + # Count up from 0 to 65535, with 64 increment + # which ends up corresponding to the DAC's 10-bit range + for i in range(0, 65535, 64): + aout.value = i diff --git a/Introducing_Trinket_M0/Trinket_CapTouch.py b/Introducing_Trinket_M0/Trinket_CapTouch.py index bbb9e222c..f3e6cc639 100644 --- a/Introducing_Trinket_M0/Trinket_CapTouch.py +++ b/Introducing_Trinket_M0/Trinket_CapTouch.py @@ -1,9 +1,10 @@ # Trinket IO demo - captouch -import touchio -import board import time +import board +import touchio + touch0 = touchio.TouchIn(board.D1) touch1 = touchio.TouchIn(board.D3) touch2 = touchio.TouchIn(board.D4) diff --git a/Introducing_Trinket_M0/Trinket_SDCardList.py b/Introducing_Trinket_M0/Trinket_SDCardList.py index 3a5038dcf..d77b23671 100644 --- a/Introducing_Trinket_M0/Trinket_SDCardList.py +++ b/Introducing_Trinket_M0/Trinket_SDCardList.py @@ -1,9 +1,10 @@ +import os + import adafruit_sdcard +import board import busio import digitalio -import board import storage -import os # Use any pin that is not taken by SPI SD_CS = board.D0 @@ -15,22 +16,25 @@ sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") + # Use the filesystem as normal! Our files are under /sd # This helper function will print the contents of the SD -def print_directory(path, tabs = 0): + + +def print_directory(path, tabs=0): for file in os.listdir(path): - stats = os.stat(path+"/"+file) + stats = os.stat(path + "/" + file) filesize = stats[6] isdir = stats[0] & 0x4000 - + if filesize < 1000: sizestr = str(filesize) + " by" elif filesize < 1000000: - sizestr = "%0.1f KB" % (filesize/1000) + sizestr = "%0.1f KB" % (filesize / 1000) else: - sizestr = "%0.1f MB" % (filesize/1000000) - + sizestr = "%0.1f MB" % (filesize / 1000000) + prettyprintname = "" for i in range(tabs): prettyprintname += " " @@ -38,10 +42,10 @@ def print_directory(path, tabs = 0): if isdir: prettyprintname += "/" print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr)) - + # recursively print directory contents if isdir: - print_directory(path+"/"+file, tabs+1) + print_directory(path + "/" + file, tabs + 1) print("Files on filesystem:") diff --git a/Introducing_Trinket_M0/Trinket_SDlogger.py b/Introducing_Trinket_M0/Trinket_SDlogger.py index 7e3046740..be08eeb71 100644 --- a/Introducing_Trinket_M0/Trinket_SDlogger.py +++ b/Introducing_Trinket_M0/Trinket_SDlogger.py @@ -1,11 +1,11 @@ +import time + import adafruit_sdcard -import microcontroller +import board import busio import digitalio -import board +import microcontroller import storage -import os -import time # Use any pin that is not taken by SPI SD_CS = board.D0 @@ -27,10 +27,10 @@ print("Logging temperature to filesystem") while True: # open file for append with open("/sd/temperature.txt", "a") as f: - led.value = True # turn on LED to indicate we're writing to the file + led.value = True # turn on LED to indicate we're writing to the file t = microcontroller.cpu.temperature print("Temperature = %0.1f" % t) f.write("%0.1f\n" % t) - led.value = False # turn off LED to indicate we're done + led.value = False # turn off LED to indicate we're done # file is saved time.sleep(1) diff --git a/Introducing_Trinket_M0/Trinket_TouchStar.py b/Introducing_Trinket_M0/Trinket_TouchStar.py index 12f1c2514..24a9d7890 100644 --- a/Introducing_Trinket_M0/Trinket_TouchStar.py +++ b/Introducing_Trinket_M0/Trinket_TouchStar.py @@ -1,10 +1,11 @@ # Trinket IO demo - captouch to dotstar -import touchio -import busio -import board import time +import board +import busio +import touchio + touch0 = touchio.TouchIn(board.D1) touch1 = touchio.TouchIn(board.D3) touch2 = touchio.TouchIn(board.D4) @@ -12,25 +13,27 @@ touch2 = touchio.TouchIn(board.D4) dotstar = busio.SPI(board.APA102_SCK, board.APA102_MOSI) r = g = b = 0 - + + def setPixel(red, green, blue): if not dotstar.try_lock(): return print("setting pixel to: %d %d %d" % (red, green, blue)) - + data = bytearray([0x00, 0x00, 0x00, 0x00, 0xff, blue, green, red, 0xff, 0xff, 0xff, 0xff]) dotstar.write(data) dotstar.unlock() time.sleep(0.01) - + + while True: if touch0.value: - r = (r+1) % 256 + r = (r + 1) % 256 if touch1.value: - g = (g+1) % 256 + g = (g + 1) % 256 if touch2.value: - b = (b+1) % 256 - + b = (b + 1) % 256 + setPixel(r, g, b) diff --git a/Introducing_Trinket_M0/Trinket_UART.py b/Introducing_Trinket_M0/Trinket_UART.py index 1bf0d8206..3f1cf3d82 100644 --- a/Introducing_Trinket_M0/Trinket_UART.py +++ b/Introducing_Trinket_M0/Trinket_UART.py @@ -1,9 +1,8 @@ # Trinket IO demo - USB/Serial echo -from digitalio import DigitalInOut, Direction import board import busio -import time +from digitalio import DigitalInOut, Direction led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT @@ -13,12 +12,13 @@ uart = busio.UART(board.D4, board.D3, baudrate=9600) while True: data = uart.read(32) # read up to 32 bytes - #print(data) # this is a bytearray type + # print(data) # this is a bytearray type if data != None: led.value = True - datastr = ''.join([chr(b) for b in data]) # convert bytearray to string - print(datastr, end="") + # convert bytearray to string + datastr = ''.join([chr(b) for b in data]) + print(datastr, end="") led.value = False diff --git a/Jewel_Hair_Stick/Jewel_Hair_Stick.py b/Jewel_Hair_Stick/Jewel_Hair_Stick.py index a7bdbcb6d..1f619b60b 100644 --- a/Jewel_Hair_Stick/Jewel_Hair_Stick.py +++ b/Jewel_Hair_Stick/Jewel_Hair_Stick.py @@ -1,11 +1,12 @@ # Jewel Hairstick by Leslie Birch for Adafruit Industries # Based on NeoPixel Library by Adafruit -from digitalio import DigitalInOut, Direction -import board -import neopixel import time +import board +import neopixel +from digitalio import DigitalInOut, Direction + pixpin = board.D1 numpix = 7 @@ -15,52 +16,49 @@ led.direction = Direction.OUTPUT # defaults to RGB|GRB Neopixels strip = neopixel.NeoPixel(pixpin, numpix, brightness=.1, auto_write=True) # uncomment the following line for RGBW Neopixels -#strip = neopixel.NeoPixel(pixpin, numpix, bpp=4, brightness=.3, auto_write=True) +# strip = neopixel.NeoPixel(pixpin, numpix, bpp=4, brightness=.3, auto_write=True) # You can have fun here changing the colors for the code color1 = (236, 79, 100) # Salmon Pink -color2 = (246, 216, 180) # Cream -color3 = (174, 113, 208) # Lavendar -color4 = (182, 31, 40) # Red -color5 = (91, 44, 86); # Purple +color2 = (246, 216, 180) # Cream +color3 = (174, 113, 208) # Lavendar +color4 = (182, 31, 40) # Red +color5 = (91, 44, 86) # Purple while True: + # the first number is the pixel number for Jewel. O is the center one + strip[1] = color1 + strip[2] = color1 + strip[3] = color1 + strip[4] = color1 + strip[5] = color1 + strip[6] = color1 + strip[0] = color2 + time.sleep(3) - # the first number is the pixel number for Jewel. O is the center one - strip[1] = color1 - strip[2] = color1 - strip[3] = color1 - strip[4] = color1 - strip[5] = color1 - strip[6] = color1 - strip[0] = color2 - time.sleep(3) - - strip[1] = color2 - strip[2] = color2 - strip[3] = color2 - strip[4] = color2 - strip[5] = color2 - strip[6] = color2 - strip[0] = color3 - time.sleep(3) - - strip[1] = color3 - strip[2] = color3 - strip[3] = color3 - strip[4] = color3 - strip[5] = color3 - strip[6] = color3 - strip[0] = color4 - time.sleep(3) - - strip[1] = color4 - strip[2] = color4 - strip[3] = color4 - strip[4] = color4 - strip[5] = color4 - strip[6] = color4 - strip[0] = color5 - time.sleep(3) + strip[1] = color2 + strip[2] = color2 + strip[3] = color2 + strip[4] = color2 + strip[5] = color2 + strip[6] = color2 + strip[0] = color3 + time.sleep(3) + strip[1] = color3 + strip[2] = color3 + strip[3] = color3 + strip[4] = color3 + strip[5] = color3 + strip[6] = color3 + strip[0] = color4 + time.sleep(3) + strip[1] = color4 + strip[2] = color4 + strip[3] = color4 + strip[4] = color4 + strip[5] = color4 + strip[6] = color4 + strip[0] = color5 + time.sleep(3) diff --git a/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py b/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py index 7c53be0a5..03626c933 100644 --- a/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py +++ b/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py @@ -1,33 +1,37 @@ # # Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py # +import time + import board import neopixel -import time + try: import urandom as random # for v1.0 API support except ImportError: import random -numpix = 32 # Number of NeoPixels -pixpin = board.D0 # Pin where NeoPixels are connected +numpix = 32 # Number of NeoPixels +pixpin = board.D0 # Pin where NeoPixels are connected -mode = 0 # Current animation effect -offset = 0 # Position of spinny eyes +mode = 0 # Current animation effect +offset = 0 # Position of spinny eyes -rgb_colors = ( [255,0,0], # red - [0,255,0], # green - [0,0,255] ) # blue +rgb_colors = ([255, 0, 0], # red + [0, 255, 0], # green + [0, 0, 255]) # blue -rgb_idx = 0 # index counter - primary color we are on +rgb_idx = 0 # index counter - primary color we are on color = rgb_colors[rgb_idx] prevtime = 0 pixels = neopixel.NeoPixel(pixpin, numpix, brightness=.3, auto_write=False) + def setup(): prevtime = time.monotonic() + setup() while True: @@ -35,15 +39,15 @@ while True: t = 0 # Random sparks - just one LED on at a time! - if ( mode == 0 ): + if (mode == 0): i = random.randint(0, (numpix - 1)) pixels[i] = color pixels.write() time.sleep(0.01) - pixels[i] = (0,0,0) + pixels[i] = (0, 0, 0) # Spinny wheels (8 LEDs on at a time) - elif ( mode == 1 ): + elif (mode == 1): for i in range(0, numpix): c = 0 @@ -51,27 +55,27 @@ while True: if (((offset + i) & 7) < 2): c = color - pixels[i] = c # First eye - pixels[(numpix - 1) - i] = c # Second eye (flipped) + pixels[i] = c # First eye + pixels[(numpix - 1) - i] = c # Second eye (flipped) - pixels.write() - offset += 1 - time.sleep(0.05); + pixels.write() + offset += 1 + time.sleep(0.05) t = time.monotonic() - if ((t - prevtime) > 8): # Every 8 seconds... - mode += 1 # Next mode - if( mode > 1 ): # End of modes? - mode = 0 # Start modes over + if ((t - prevtime) > 8): # Every 8 seconds... + mode += 1 # Next mode + if (mode > 1): # End of modes? + mode = 0 # Start modes over - if ( rgb_idx > 2 ): # reset R-->G-->B rotation + if (rgb_idx > 2): # reset R-->G-->B rotation rgb_idx = 0 - color = rgb_colors[rgb_idx] # next color assignment + color = rgb_colors[rgb_idx] # next color assignment rgb_idx += 1 for i in range(0, numpix): - pixels[i] = (0,0,0) + pixels[i] = (0, 0, 0) - prevtime = t + prevtime = t diff --git a/LED_Candles/LED_Candles.py b/LED_Candles/LED_Candles.py index f48b99f90..601d7fae2 100644 --- a/LED_Candles/LED_Candles.py +++ b/LED_Candles/LED_Candles.py @@ -1,14 +1,15 @@ +import time + import board import neopixel -import time from analogio import AnalogIn try: - import urandom as random + import urandom as random except ImportError: - import random + import random -wick_pin = board.D0 # The data-in pin of the NeoPixel +wick_pin = board.D0 # The data-in pin of the NeoPixel unconnected_pin = board.A0 # Any unconnected pin, to try to generate a random seed # The LED can be in only one of these states at any given time @@ -19,36 +20,40 @@ dim = 3 bright_hold = 4 dim_hold = 5 -index_bottom_percent = 10 # Percent chance the LED will suddenly fall to minimum brightness -index_bottom = 128 # Absolute minimum red value (green value is a function of red's value) -index_min = 192 # Minimum red value during "normal" flickering (not a dramatic change) -index_max = 255 # Maximum red value +# Percent chance the LED will suddenly fall to minimum brightness +index_bottom_percent = 10 +# Absolute minimum red value (green value is a function of red's value) +index_bottom = 128 +# Minimum red value during "normal" flickering (not a dramatic change) +index_min = 192 +index_max = 255 # Maximum red value # Decreasing brightness will take place over a number of milliseconds in this range -down_min_msecs = 20 -down_max_msecs = 250 +down_min_msecs = 20 +down_max_msecs = 250 # Increasing brightness will take place over a number of milliseconds in this range -up_min_msecs = 20 -up_max_msecs = 250 +up_min_msecs = 20 +up_max_msecs = 250 # Percent chance the color will hold unchanged after brightening -bright_hold_percent = 20 +bright_hold_percent = 20 # When holding after brightening, hold for a number of milliseconds in this range bright_hold_min_msecs = 0 -bright_hold_max_msecs = 100 +bright_hold_max_msecs = 100 # Percent chance the color will hold unchanged after dimming dim_hold_percent = 5 # When holding after dimming, hold for a number of milliseconds in this range dim_hold_min_msecs = 0 -dim_hold_max_msecs = 50 +dim_hold_max_msecs = 50 -numpix = 1 # Number of NeoPixels +numpix = 1 # Number of NeoPixels pixpin = board.D0 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) # initialize strip +strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, + auto_write=True) # initialize strip # Random number generator is seeded from an unused 'floating' # analog input - this helps ensure the random color choices @@ -62,12 +67,14 @@ index_start = 255 index_end = 255 state = bright + def set_color(index): - index = max(min(index,index_max), index_bottom) - if ( index >= index_min ): - strip[0] = [index, int ( (index * 3) / 8 ), 0] - elif ( index < index_min ): - strip[0] = [index, int ( (index * 3.25) / 8 ) , 0] + index = max(min(index, index_max), index_bottom) + if (index >= index_min): + strip[0] = [index, int((index * 3) / 8), 0] + elif (index < index_min): + strip[0] = [index, int((index * 3.25) / 8), 0] + set_color(255) @@ -76,52 +83,60 @@ while True: current_time = time.monotonic() # BRIGHT - if ( state == bright ): - flicker_msecs = random.randint(0, down_max_msecs - down_min_msecs) + down_min_msecs + if (state == bright): + flicker_msecs = random.randint( + 0, down_max_msecs - down_min_msecs) + down_min_msecs flicker_start = current_time index_start = index_end - if (( index_start > index_bottom ) and ( random.randint(0, 100) < index_bottom_percent)): - index_end = random.randint(0, index_start - index_bottom) + index_bottom + if ((index_start > index_bottom) and (random.randint(0, 100) < index_bottom_percent)): + index_end = random.randint( + 0, index_start - index_bottom) + index_bottom else: - index_end = random.randint(0, index_start - index_min) + index_min + index_end = random.randint(0, index_start - index_min) + index_min state = down # DIM - elif ( state == dim ): - flicker_msecs = random.randint(0, up_max_msecs - up_min_msecs) + up_min_msecs + elif (state == dim): + flicker_msecs = random.randint( + 0, up_max_msecs - up_min_msecs) + up_min_msecs flicker_start = current_time index_start = index_end - index_end = random.randint(0, (index_max - index_start) ) + index_min + index_end = random.randint(0, (index_max - index_start)) + index_min state = down # DIM_HOLD - elif ( state == dim_hold ): - if (current_time >= ( flicker_start + ( flicker_msecs / 1000) ) ): # dividing flicker_msecs by 1000 to convert to milliseconds - if ( state == bright_hold ): + elif (state == dim_hold): + # dividing flicker_msecs by 1000 to convert to milliseconds + if (current_time >= (flicker_start + (flicker_msecs / 1000))): + if (state == bright_hold): state = bright else: state = dim # DOWN - elif ( state == down ): - if (current_time < (flicker_start + ( flicker_msecs / 1000 ) )): # dividing flicker_msecs by 1000 to convert to milliseconds - set_color(index_start + int ( ((index_end - index_start) * (((current_time - flicker_start) * 1.0) / flicker_msecs))) ) - else: - set_color(index_end) - - if (state == down): - if (random.randint(0,100) < dim_hold_percent): - flicker_start = current_time - flicker_msecs = random.randint(0, dim_hold_max_msecs - dim_hold_min_msecs) + dim_hold_min_msecs - state = dim_hold - else: - state = dim + elif (state == down): + # dividing flicker_msecs by 1000 to convert to milliseconds + if (current_time < (flicker_start + (flicker_msecs / 1000))): + set_color(index_start + int(((index_end - index_start) * + (((current_time - flicker_start) * 1.0) / flicker_msecs)))) else: - if (random.randint(0,100) < bright_hold_percent): - flicker_start = current_time - flicker_msecs = random.randint(0, bright_hold_max_msecs - bright_hold_min_msecs) + bright_hold_min_msecs - state = bright_hold - else: - state = bright + set_color(index_end) + + if (state == down): + if (random.randint(0, 100) < dim_hold_percent): + flicker_start = current_time + flicker_msecs = random.randint( + 0, dim_hold_max_msecs - dim_hold_min_msecs) + dim_hold_min_msecs + state = dim_hold + else: + state = dim + else: + if (random.randint(0, 100) < bright_hold_percent): + flicker_start = current_time + flicker_msecs = random.randint( + 0, bright_hold_max_msecs - bright_hold_min_msecs) + bright_hold_min_msecs + state = bright_hold + else: + state = bright diff --git a/LED_Masquerade_Masks/Audio_Reactive.py b/LED_Masquerade_Masks/Audio_Reactive.py index 1deb397eb..b0127d6df 100644 --- a/LED_Masquerade_Masks/Audio_Reactive.py +++ b/LED_Masquerade_Masks/Audio_Reactive.py @@ -1,27 +1,32 @@ -import board -import pulseio -import analogio import time -sampleWindow = 0.033 # Sample window width (0.033 sec = 33 mS = ~30 Hz) -ledPin = board.D0 # Pin where LEDs are connected (PWM not avail on D1) -micPin = board.A1 # Microphone 'OUT' is connected here +import analogio +import board +import pulseio + +sampleWindow = 0.033 # Sample window width (0.033 sec = 33 mS = ~30 Hz) +ledPin = board.D0 # Pin where LEDs are connected (PWM not avail on D1) +micPin = board.A1 # Microphone 'OUT' is connected here mic = analogio.AnalogIn(micPin) pwm = pulseio.PWMOut(ledPin, frequency=1000, duty_cycle=0) while True: - # Listen to mic for short interval, recording min & max signal - signalMin = 65535 - signalMax = 0 - startTime = time.monotonic() - while((time.monotonic() - startTime) < sampleWindow): - signal = mic.value - if signal < signalMin: signalMin = signal - if signal > signalMax: signalMax = signal + # Listen to mic for short interval, recording min & max signal + signalMin = 65535 + signalMax = 0 + startTime = time.monotonic() + while ((time.monotonic() - startTime) < sampleWindow): + signal = mic.value + if signal < signalMin: + signalMin = signal + if signal > signalMax: + signalMax = signal - peakToPeak = signalMax - signalMin # Audio amplitude - n = (peakToPeak - 250) * 4 # Remove low-level noise, boost - if n > 65535: n = 65535 # Limit to valid PWM range - elif n < 0: n = 0 - pwm.duty_cycle = n # And send to LED as PWM level + peakToPeak = signalMax - signalMin # Audio amplitude + n = (peakToPeak - 250) * 4 # Remove low-level noise, boost + if n > 65535: + n = 65535 # Limit to valid PWM range + elif n < 0: + n = 0 + pwm.duty_cycle = n # And send to LED as PWM level diff --git a/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py b/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py index a7de7a750..08dbab1c3 100644 --- a/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py +++ b/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py @@ -4,26 +4,28 @@ import time numpix = 5 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -hue = 0 # Starting color -strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.4) +hue = 0 # Starting color +strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.4) + def wheel(pos): - # Input a value 0 to 255 to get a color value. - # The colours are a transition r - g - b - back to r. - if (pos < 0) or (pos > 255): - return [0, 0, 0] - elif (pos < 85): - return [int(pos * 3), int(255 - (pos * 3)), 0] - elif (pos < 170): - pos -= 85 - return [int(255 - pos * 3), 0, int(pos * 3)] - else: - pos -= 170 - return [0, int(pos * 3), int(255 - pos * 3)] + # Input a value 0 to 255 to get a color value. + # The colours are a transition r - g - b - back to r. + if (pos < 0) or (pos > 255): + return [0, 0, 0] + elif (pos < 85): + return [int(pos * 3), int(255 - (pos * 3)), 0] + elif (pos < 170): + pos -= 85 + return [int(255 - pos * 3), 0, int(pos * 3)] + else: + pos -= 170 + return [0, int(pos * 3), int(255 - pos * 3)] + while True: # Loop forever... - for i in range(numpix): - strip[i] = wheel((hue + i * 8) & 255) - strip.write() - time.sleep(0.02) # 20 ms = ~50 fps - hue = (hue + 1) & 255 # Increment hue and 'wrap around' at 255 + for i in range(numpix): + strip[i] = wheel((hue + i * 8) & 255) + strip.write() + time.sleep(0.02) # 20 ms = ~50 fps + hue = (hue + 1) & 255 # Increment hue and 'wrap around' at 255 diff --git a/LED_Trampoline/LED_Trampoline.py b/LED_Trampoline/LED_Trampoline.py index 734caac85..6e757995c 100644 --- a/LED_Trampoline/LED_Trampoline.py +++ b/LED_Trampoline/LED_Trampoline.py @@ -1,8 +1,9 @@ -import time import random +import time + import board -import neopixel import digitalio +import neopixel pixel_pin = board.D10 # The pin the NeoPixels are connected to button_switch_pin = board.D9 # Pin button is attached to @@ -10,7 +11,8 @@ vibration_switch_pin = board.D7 # Pin vibration switch is attached to. pixel_count = 40 # Number of pixels in your strip chase_color_duration = 3 # Time in seconds each color lasts in the color chase mode -pixels = neopixel.NeoPixel(pixel_pin, pixel_count, brightness=.4, auto_write=False) +pixels = neopixel.NeoPixel(pixel_pin, pixel_count, + brightness=.4, auto_write=False) button_switch = digitalio.DigitalInOut(button_switch_pin) button_switch.direction = digitalio.Direction.INPUT @@ -69,7 +71,6 @@ def sparkle_code(color_values): fade = fade_control() - flash_color = cycle_sequence([RED, YELLOW, ORANGE, GREEN, TEAL, CYAN, BLUE, PURPLE, MAGENTA, WHITE]) @@ -121,7 +122,8 @@ while True: if mode == 1 and not vibration_switch.value: print("Sparkle mode activate!") pixels.brightness = 1 - sparkle_color_index = (sparkle_color_index + 1) % len(sparkle_color_list) + sparkle_color_index = ( + sparkle_color_index + 1) % len(sparkle_color_list) sparkle_code(sparkle_color_list[sparkle_color_index]) if mode == 2 and not vibration_switch.value: print("Chase mode activate!") @@ -135,7 +137,8 @@ while True: pixels.show() offset += 1 if now >= chase_next_color: - chase_color_index = (chase_color_index + 1) % len(chase_color_list) + chase_color_index = (chase_color_index + + 1) % len(chase_color_list) chase_color_cycle = chase_color_list[chase_color_index] pixels.fill((0, 0, 0)) chase_last_color = now diff --git a/Labo_Piano_Light_FX/code.py b/Labo_Piano_Light_FX/code.py index 0c4845c60..ea46e97b4 100644 --- a/Labo_Piano_Light_FX/code.py +++ b/Labo_Piano_Light_FX/code.py @@ -1,45 +1,48 @@ import board import neopixel -import time from analogio import AnalogIn -import array -n_pixels = 10 # Number of pixels you are using -dc_offset = 0 # DC offset in mic signal - if unusure, leave 0 -noise = 100 # Noise/hum/interference in mic signal -lvl = 10 # Current "dampened" audio level -maxbrt = 127 # Maximum brightness of the neopixels (0-255) -wheelStart = 0 # Start of the RGB spectrum we'll use -wheelEnd = 255 # End of the RGB spectrum we'll use +n_pixels = 10 # Number of pixels you are using +dc_offset = 0 # DC offset in mic signal - if unusure, leave 0 +noise = 100 # Noise/hum/interference in mic signal +lvl = 10 # Current "dampened" audio level +maxbrt = 127 # Maximum brightness of the neopixels (0-255) +wheelStart = 0 # Start of the RGB spectrum we'll use +wheelEnd = 255 # End of the RGB spectrum we'll use mic_pin = AnalogIn(board.A7) # Set up NeoPixels and turn them all off. -strip = neopixel.NeoPixel(board.NEOPIXEL, n_pixels, brightness=0.1, auto_write=False) +strip = neopixel.NeoPixel(board.NEOPIXEL, n_pixels, + brightness=0.1, auto_write=False) strip.fill(0) strip.show() + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) - + return (0, int(pos * 3), int(255 - pos * 3)) + + def remapRangeSafe(value, leftMin, leftMax, rightMin, rightMax): # this remaps a value from original (left) range to new (right) range - + # Force the input value to within left min & max - if value < leftMin: value = leftMin - if value > leftMax: value = leftMax - + if value < leftMin: + value = leftMin + if value > leftMax: + value = leftMax + # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin @@ -50,19 +53,21 @@ def remapRangeSafe(value, leftMin, leftMax, rightMin, rightMax): # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) + while True: - n = int ( ( mic_pin.value / 65536 ) * 1000 ) # 10-bit ADC format - n = abs(n - 512 - dc_offset) # Center on zero + n = int((mic_pin.value / 65536) * 1000) # 10-bit ADC format + n = abs(n - 512 - dc_offset) # Center on zero - if ( n >= noise ): # Remove noise/hum - n = n - noise + if (n >= noise): # Remove noise/hum + n = n - noise + + # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) + lvl = int(((lvl * 7) + n) / 8) - lvl = int ( ( (lvl * 7) + n ) / 8 ) # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) - # Color pixels based on rainbow gradient vlvl = remapRangeSafe(lvl, 0, 255, wheelStart, wheelEnd) for i in range(0, len(strip)): strip[i] = wheel(vlvl) # Set strip brightness based on audio level - strip.brightness = float(remapRangeSafe(lvl,50,255,0,maxbrt))/255.0 + strip.brightness = float(remapRangeSafe(lvl, 50, 255, 0, maxbrt)) / 255.0 strip.show() diff --git a/Labo_RC_Car_Light_FX/code.py b/Labo_RC_Car_Light_FX/code.py index 75e028704..63a433195 100644 --- a/Labo_RC_Car_Light_FX/code.py +++ b/Labo_RC_Car_Light_FX/code.py @@ -1,21 +1,20 @@ -from adafruit_circuitplayground.express import cpx import board import neopixel +from adafruit_circuitplayground.express import cpx pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.1, auto_write=True) pixels.fill(0) while True: - + x, y, z = cpx.acceleration # read acceleromter r, g, b = 0, 0, 0 - + if abs(x) > 4.0: r = 255 if abs(y) > 2.0: g = 255 if z > -6.0 or z < -12.0: - b = 255 - - pixels.fill((r,g,b)) - \ No newline at end of file + b = 255 + + pixels.fill((r, g, b)) diff --git a/Larson_Scanner_Shades/Larson_Scanner_Shades.py b/Larson_Scanner_Shades/Larson_Scanner_Shades.py index d04ec761c..e75881e8d 100644 --- a/Larson_Scanner_Shades/Larson_Scanner_Shades.py +++ b/Larson_Scanner_Shades/Larson_Scanner_Shades.py @@ -1,21 +1,23 @@ -import board -import neopixel import time -numpix = 22 # Number of NeoPixels -pixpin = board.D1 # Pin where NeoPixels are connected Gemma M0 = D1 | Trinket M0 = D4 -strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) -pos = 0 # position -direction = 1 # direction of "eye" +import board +import neopixel + +numpix = 22 # Number of NeoPixels +pixpin = board.D1 # Pin where NeoPixels are connected Gemma M0 = D1 | Trinket M0 = D4 +strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) +pos = 0 # position +direction = 1 # direction of "eye" while True: - strip[pos-2] = ([16,0,0]) # Dark red - strip[pos-1] = ([128,0,0]) # Medium red - strip[pos] = ([255,48,0]) # brightest - strip[pos+1] = ([128,0,0]) # Medium red + strip[pos - 2] = ([16, 0, 0]) # Dark red + strip[pos - 1] = ([128, 0, 0]) # Medium red + strip[pos] = ([255, 48, 0]) # brightest + strip[pos + 1] = ([128, 0, 0]) # Medium red - if ( (pos + 2) < numpix ): - strip[pos+2] = ([16,0,0]) # Dark red, do not exceed number of pixels + if ((pos + 2) < numpix): + # Dark red, do not exceed number of pixels + strip[pos + 2] = ([16, 0, 0]) strip.write() time.sleep(0.03) @@ -23,15 +25,15 @@ while True: # Rather than being sneaky and erasing just the tail pixel, # it's easier to erase it all and draw a new one next time. for j in range(-2, 2): - strip[pos+j] = (0,0,0) - if ( (pos + 2) < numpix ): - strip[pos+2] = (0,0,0) + strip[pos + j] = (0, 0, 0) + if ((pos + 2) < numpix): + strip[pos + 2] = (0, 0, 0) # Bounce off ends of strip pos += direction - if ( pos < 0 ): + if (pos < 0): pos = 1 direction = -direction - elif ( pos >= (numpix - 1) ): + elif (pos >= (numpix - 1)): pos = numpix - 2 direction = -direction diff --git a/Light_Activated_Pixel_Heart/Light_Activated_Pixel_Heart.py b/Light_Activated_Pixel_Heart/Light_Activated_Pixel_Heart.py index 1094738b5..399a3f92a 100644 --- a/Light_Activated_Pixel_Heart/Light_Activated_Pixel_Heart.py +++ b/Light_Activated_Pixel_Heart/Light_Activated_Pixel_Heart.py @@ -1,28 +1,31 @@ -import board -import neopixel -import digitalio import time -numpix = 8 # Number of NeoPixels -ledpin = board.D1 # Digital pin # where NeoPixels are connected +import board +import digitalio +import neopixel + +numpix = 8 # Number of NeoPixels +ledpin = board.D1 # Digital pin # where NeoPixels are connected sensorpin = board.D2 # Digital pin # where light sensor is connected -strip = neopixel.NeoPixel(ledpin, numpix, brightness=1.0) +strip = neopixel.NeoPixel(ledpin, numpix, brightness=1.0) # Enable internal pullup resistor on sensor pin -pin = digitalio.DigitalInOut(sensorpin) +pin = digitalio.DigitalInOut(sensorpin) pin.direction = digitalio.Direction.INPUT -pin.pull = digitalio.Pull.UP +pin.pull = digitalio.Pull.UP while True: # Loop forever... - # LDR is being used as a digital (binary) sensor. It must be - # completely dark to turn it off, a finger may not be opaque enough! - if pin.value: color = (0,0,0) # Off - else: color = (255,0,255) # Purple + # LDR is being used as a digital (binary) sensor. It must be + # completely dark to turn it off, a finger may not be opaque enough! + if pin.value: + color = (0, 0, 0) # Off + else: + color = (255, 0, 255) # Purple - for i in range(numpix): # For each pixel... - strip[i] = color # Set to 'color' - strip.write() # Push data to pixels - time.sleep(0.05) # Pause 50 ms + for i in range(numpix): # For each pixel... + strip[i] = color # Set to 'color' + strip.write() # Push data to pixels + time.sleep(0.05) # Pause 50 ms - time.sleep(0.002); # Pause 2 ms + time.sleep(0.002) # Pause 2 ms diff --git a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py index 9034e4002..bc673c4fa 100644 --- a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py +++ b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py @@ -1,52 +1,63 @@ -import board -import neopixel import time +import board +import neopixel + pixpin = board.D1 numpix = 7 -wait = .5 # 1/2 second color fade duration +wait = .5 # 1/2 second color fade duration # defaults to RGB|GRB Neopixels strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) + # uncomment the following line for RGBW Neopixels # strip = neopixel.NeoPixel(pixpin, numpix, bpp=4, brightness=.3, auto_write=True) # Linear interpolation of y value given min/max x, min/max y, and x position. -def lerp(x, x0, x1, y0, y1): + +def lerp(x, x0, x1, y0, y1): # Clamp x within x0 and x1 bounds. - if ( x > x1 ): + if (x > x1): x = x1 - - if ( x < x0 ): + + if (x < x0): x = x0 # Calculate linear interpolation of y value. - return (y0 + (y1-y0) * ( (x-x0) / (x1-x0) ) ) + return (y0 + (y1 - y0) * ((x - x0) / (x1 - x0))) + # Set all pixels to the specified color. + + def fill_pixels(r, g, b): for i in range(0, numpix): strip[i] = (r, g, b) strip.write() + # Get the color of a pixel within a smooth gradient of two colors. # Starting R,G,B color # Ending R,G,B color # Position along gradient, should be a value 0 to 1.0 -def color_gradient(start_r, start_g, start_b, end_r,end_g, end_b, pos): + +def color_gradient(start_r, start_g, start_b, end_r, end_g, end_b, pos): # Interpolate R,G,B values and return them as a color. - red = lerp(pos, 0.0, 1.0, start_r, end_r) + red = lerp(pos, 0.0, 1.0, start_r, end_r) green = lerp(pos, 0.0, 1.0, start_g, end_g) - blue = lerp(pos, 0.0, 1.0, start_b, end_b) + blue = lerp(pos, 0.0, 1.0, start_b, end_b) return (red, green, blue) + # Starting R,G,B color # Ending R,G,B color # Total duration of animation, in milliseconds + + def animate_gradient_fill(start_r, start_g, start_b, end_r, end_g, end_b, duration_ms): start = time.monotonic() @@ -56,20 +67,21 @@ def animate_gradient_fill(start_r, start_g, start_b, end_r, end_g, end_b, durati # Main animation loop. delta = time.monotonic() - start - while (delta < duration_ms): + while (delta < duration_ms): # Calculate how far along we are in the duration as a position 0...1.0 pos = delta / duration_ms # Get the gradient color and fill all the pixels with it. - color = color_gradient(start_r, start_g, start_b, end_r, end_g, end_b, pos) - fill_pixels( int ( color[0]) , int ( color[1] ), int ( color[2] ) ) + color = color_gradient(start_r, start_g, start_b, + end_r, end_g, end_b, pos) + fill_pixels(int(color[0]), int(color[1]), int(color[2])) # Update delta and repeat. delta = time.monotonic() - start # Display end color. fill_pixels(end_r, end_g, end_b) -while True: +while True: # Run It: # Nice fade from dim red to full red for 1/2 of a second: diff --git a/Minecraft_Gesture_Controller/main.py b/Minecraft_Gesture_Controller/main.py index 2754c3069..f2b8e75e2 100644 --- a/Minecraft_Gesture_Controller/main.py +++ b/Minecraft_Gesture_Controller/main.py @@ -1,10 +1,10 @@ ############################################### # Minecraft Gesture Controller -# -#Written by +# +# Written by # MIT License V.asof2018 # Also coffee/beer ware license :) -#Super awesome thanks to: +# Super awesome thanks to: # Richard Albritton, Tony DiCola, John Parker # All the awesome people who wrote the libraries ################################################ @@ -13,18 +13,19 @@ ## Libraries ## ########################## -#Libraries for accelerometer +import time + +# Libraries for accelerometer import adafruit_lis3dh -#Libraries for HID Keyboard & Mouse -from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode -from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS -from adafruit_hid.mouse import Mouse -# General purpose libraries -import touchio import board import busio -import time +# General purpose libraries +import touchio +# Libraries for HID Keyboard & Mouse +from adafruit_hid.keyboard import Keyboard +from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode +from adafruit_hid.mouse import Mouse ####################### # CPX Setup # @@ -38,7 +39,6 @@ touch_a3.threshold = 2000 touch_a4 = touchio.TouchIn(board.A4) touch_a4.threshold = 2000 - ############################ # Keyboard & Mouse Setup # ############################ @@ -46,33 +46,37 @@ touch_a4.threshold = 2000 kbd = Keyboard() # we're americans :) layout = KeyboardLayoutUS(kbd) -#The mouse object! +# The mouse object! mouse = Mouse() ####################### # Accelerometer Setup # ####################### -#Initialize Accelerometer +# Initialize Accelerometer i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=25) # Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G). lis3dh.range = adafruit_lis3dh.RANGE_8_G + ########################### ## Controller Functions ## ########################### # A helper to 'remap' an input range to an output range -def Map(x, in_min, in_max, out_min, out_max): - return int((x - in_min)*(out_max - out_min) / (in_max - in_min) + out_min) -def Move(upDown_axis, isBackward): + +def Map(x, in_min, in_max, out_min, out_max): + return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) + + +def Move(upDown_axis, isBackward): axis_new = abs(upDown_axis) - #If you are touching A4, walk backwards, else walk forwards + # If you are touching A4, walk backwards, else walk forwards if isBackward: - print("backwards") #Debugging - if (axis_new > 1.2): #walk threshold - if(axis_new > 2.5): #run threshold + print("backwards") # Debugging + if (axis_new > 1.2): # walk threshold + if (axis_new > 2.5): # run threshold kbd.press(Keycode.LEFT_CONTROL, Keycode.S) time.sleep(0.1) kbd.release_all() @@ -81,8 +85,8 @@ def Move(upDown_axis, isBackward): time.sleep(0.1) kbd.release_all() else: - if (axis_new > 1.2): #walk threshold - if(axis_new > 2.5): #run threshold + if (axis_new > 1.2): # walk threshold + if (axis_new > 2.5): # run threshold kbd.press(Keycode.LEFT_CONTROL) time.sleep(0.1) kbd.release_all() @@ -90,35 +94,39 @@ def Move(upDown_axis, isBackward): kbd.press(Keycode.W) time.sleep(0.1) kbd.release_all() - + + def Turn(upDown_axis, frontBack_axis, leftRight_axis, lookUp): - leftRight_adj = int(leftRight_axis) #currently z_axis - upDown_adj = int(upDown_axis) #currently y_axis + leftRight_adj = int(leftRight_axis) # currently z_axis + upDown_adj = int(upDown_axis) # currently y_axis leftRight_new = Map(leftRight_adj, -3, 3, -100, 100) - if(lookUp and abs(upDown_adj) < 1.2): + if (lookUp and abs(upDown_adj) < 1.2): upDown_new = Map(upDown_adj, -1, 1, -100, 100) else: upDown_new = 0 - if abs(leftRight_new) < 127: + if abs(leftRight_new) < 127: mouse.move(-leftRight_new, upDown_new) else: mouse.move(0, 0) + def Jump(upDown_axis): upDown = abs(upDown_axis) - if(upDown > 3): + if (upDown > 3): kbd.press(Keycode.SPACE, Keycode.W) kbd.release_all() + def Give(upDown_axis, frontBack_axis): frontBack_new = abs(frontBack_axis) if abs(upDown_axis) < 1: - if(frontBack_new > 2): + if (frontBack_new > 2): print("give") mouse.click(Mouse.RIGHT_BUTTON) mouse.release_all() + def Attack(): """Attack! By clicking the left mouse button""" print("attack") @@ -126,34 +134,37 @@ def Attack(): time.sleep(0.1) mouse.release_all() + def Inventory(): """Open up inventory, press the E keyboard key""" - print("inventory") #Debugging -- view in serial monitor + print("inventory") # Debugging -- view in serial monitor kbd.press(Keycode.E) time.sleep(0.01) kbd.release_all() + def ESC(): """Escape by pressing the ESCape key""" - print("ESC") #Debugging -- view in serial monitor + print("ESC") # Debugging -- view in serial monitor kbd.press(Keycode.ESCAPE) time.sleep(0.01) kbd.release_all() + def readAxes(): """Convert acceleration from m/s^2 to G, with a delay""" x, y, z = lis3dh.acceleration time.sleep(0.01) - return ( x/9.806, y/9.806, z/9.806 ) # 9.806 m/s^2 per G + return (x / 9.806, y / 9.806, z / 9.806) # 9.806 m/s^2 per G ########################### -## Main Function ## +## Main Function ## ########################### while True: # Read accelerometer values (in G). Returns a 3-tuple of x, y, x axis x, y, z = readAxes() - + # Read finger pads and act accordingly if touch_a1.value: Attack() @@ -172,12 +183,12 @@ while True: Turn(y, x, z, lookUp) Jump(y) Give(y, x) - + # Small delay to keep things responsive but give time for interrupt processing. time.sleep(0.01) - + ## Debugging Ahead!! ## # Use the following 2 lines to figure out which axis is upDown, frontBack, or LeftRight # and also for debugging! - #print('x = {}G, y = {}G, z = {}G'.format(x, y, z)) - #time.sleep(0.3) + # print('x = {}G, y = {}G, z = {}G'.format(x, y, z)) + # time.sleep(0.3) diff --git a/Morse_Code_Flasher/main.py b/Morse_Code_Flasher/main.py index 89753b67f..9911569c4 100644 --- a/Morse_Code_Flasher/main.py +++ b/Morse_Code_Flasher/main.py @@ -11,35 +11,40 @@ import board import neopixel # Configuration: -message = 'SOS' # Message to display (capital letters and numbers only) +# Message to display (capital letters and numbers only) +message = 'SOS' dot_length = 0.15 # Duration of one Morse dot dash_length = (dot_length * 3.0) # Duration of one Morse dash symbol_gap = dot_length # Duration of gap between dot or dash character_gap = (dot_length * 3.0) # Duration of gap between characters flash_color = (255, 0, 0) # Color of the morse display. brightness = 0.5 # Display brightness (0.0 - 1.0) -morse = [('A', '.-'), ('B', '-...'), ('C', '-.-.'), ('D', '-..'), ('E', '.'), ('F', '..-.'), ('G', '--.'), ('H', '....'), ('I', '..'), ('J', '.---'), ('K', '-.-'), ('L', '.-..'), ('M', '--'), ('N', '-.'), ('O', '---'), ('P', '.--.'), ('Q', '--.-'), ('R', '.-.'), ('S', '...'), ('T', '-'), ('U', '..-'), ('V', '...-'), ('W', '.--'), ('X', '-..-'), ('Y', '-.--'), ('Z', '--..'), ('0', '-----'), ('1', '.----'), ('2', '..---'), ('3', '...--'), ('4', '....-'), ('5', '.....'), ('6', '-....'), ('7', '--...'), ('8', '---..'), ('9', '----.')] +morse = [('A', '.-'), ('B', '-...'), ('C', '-.-.'), ('D', '-..'), ('E', '.'), ('F', '..-.'), ('G', '--.'), ('H', '....'), ('I', '..'), ('J', '.---'), ('K', '-.-'), ('L', '.-..'), ('M', '--'), ('N', '-.'), ('O', '---'), ('P', '.--.'), ('Q', '--.-'), ('R', '.-.'), ('S', + '...'), ('T', '-'), ('U', '..-'), ('V', '...-'), ('W', '.--'), ('X', '-..-'), ('Y', '-.--'), ('Z', '--..'), ('0', '-----'), ('1', '.----'), ('2', '..---'), ('3', '...--'), ('4', '....-'), ('5', '.....'), ('6', '-....'), ('7', '--...'), ('8', '---..'), ('9', '----.')] # Define a class that represents the morse flasher. + + class MorseFlasher: - def __init__(self, color=(255,255,255)): - #set the color adjusted for brightness - self._color = (int(color[0]*brightness), int(color[1]*brightness), int(color[2]*brightness)) - + def __init__(self, color=(255, 255, 255)): + # set the color adjusted for brightness + self._color = ( + int(color[0]*brightness), int(color[1]*brightness), int(color[2]*brightness)) + def light(self, on=True): if on: pixels.fill(self._color) else: - pixels.fill((0,0,0)) + pixels.fill((0, 0, 0)) pixels.show() - + def showDot(self): self.light(True) time.sleep(dot_length) self.light(False) time.sleep(symbol_gap) - + def showDash(self): self.light(True) time.sleep(dash_length) @@ -48,18 +53,18 @@ class MorseFlasher: def encode(self, str): output = "" - #iterate through string's characters + # iterate through string's characters for c in str: - #find morse code for a character + # find morse code for a character for x in morse: if x[0] == c: - #add code to output + # add code to output output += x[1] # add a space in between characters output += " " - #save complete morse code output to display + # save complete morse code output to display self.display(output) - + def display(self, code=".-.-.- "): # iterate through morse code symbols for c in code: @@ -73,6 +78,7 @@ class MorseFlasher: elif c == " ": time.sleep(character_gap) + # Initialize NeoPixels pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False) pixels.fill((0, 0, 0)) diff --git a/Motorized_Turntable/turntable.py b/Motorized_Turntable/turntable.py index d880ad02c..68a66023c 100644 --- a/Motorized_Turntable/turntable.py +++ b/Motorized_Turntable/turntable.py @@ -14,15 +14,17 @@ pot = AnalogIn(board.A0) continuous = adafruit_motor.servo.ContinuousServo(pwm) + def val(pin): # divides voltage (65535) to get a value between 0 and 1 return pin.value / 65535 + while True: - + if switch.value: continuous.throttle = val(pot) * -1 else: continuous.throttle = val(pot) * 1 - + time.sleep(0.001) diff --git a/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py b/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py index 6b588e75f..42fc5a072 100644 --- a/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py +++ b/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py @@ -2,35 +2,35 @@ import board import neopixel import time try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random numpix = 17 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix) +strip = neopixel.NeoPixel(pixpin, numpix) -minAlpha = 0.1 # Minimum brightness -maxAlpha = 0.4 # Maximum brightness -alpha = (minAlpha + maxAlpha) / 2 # Start in middle +minAlpha = 0.1 # Minimum brightness +maxAlpha = 0.4 # Maximum brightness +alpha = (minAlpha + maxAlpha) / 2 # Start in middle alphaDelta = 0.008 # Amount to change brightness each time through loop -alphaUp = True # If True, brightness increasing, else decreasing +alphaUp = True # If True, brightness increasing, else decreasing strip.fill([255, 0, 0]) # Fill red, or change to R,G,B of your liking while True: # Loop forever... - if random.randint(1, 5) == 5: # 1-in-5 random chance - alphaUp = not alphaUp # of reversing direction - if alphaUp: # Increasing brightness? - alpha += alphaDelta # Add some amount - if alpha >= maxAlpha: # At or above max? - alpha = maxAlpha # Limit to max - alphaUp = False # and switch direction - else: # Else decreasing brightness - alpha -= alphaDelta # Subtract some amount - if alpha <= minAlpha: # At or below min? - alpha = minAlpha # Limit to min - alphaUp = True # and switch direction + if random.randint(1, 5) == 5: # 1-in-5 random chance + alphaUp = not alphaUp # of reversing direction + if alphaUp: # Increasing brightness? + alpha += alphaDelta # Add some amount + if alpha >= maxAlpha: # At or above max? + alpha = maxAlpha # Limit to max + alphaUp = False # and switch direction + else: # Else decreasing brightness + alpha -= alphaDelta # Subtract some amount + if alpha <= minAlpha: # At or below min? + alpha = minAlpha # Limit to min + alphaUp = True # and switch direction - strip.brightness = alpha # Set brightness to 0.0 to 1.0 - strip.write() # and issue data to LED strip + strip.brightness = alpha # Set brightness to 0.0 to 1.0 + strip.write() # and issue data to LED strip diff --git a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py index 481f17785..67e1f2829 100644 --- a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py +++ b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py @@ -4,29 +4,29 @@ import analogio import neopixel import time try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except: - import random + import random -num_leds = 24 # 24 LED NeoPixel ring -neopixel_pin = board.D0 # Pin where NeoPixels are connected -vibration_pin = board.D1 # Pin where vibration switch is connected -analog_pin = board.A0 # Not connected to anything -strip = neopixel.NeoPixel(neopixel_pin, num_leds) +num_leds = 24 # 24 LED NeoPixel ring +neopixel_pin = board.D0 # Pin where NeoPixels are connected +vibration_pin = board.D1 # Pin where vibration switch is connected +analog_pin = board.A0 # Not connected to anything +strip = neopixel.NeoPixel(neopixel_pin, num_leds) default_frame_len = 0.06 # Time (in seconds) of typical animation frame -max_frame_len = 0.25 # Gradually slows toward this -min_frame_len = 0.005 # But sometimes as little as this -cooldown_at = 2.0 # After this many seconds, start slowing down -dim_at = 2.5 # After this many seconds, dim LEDs -brightness_high = 0.5 # Active brightness -brightness_low = 0.125 # Idle brightness +max_frame_len = 0.25 # Gradually slows toward this +min_frame_len = 0.005 # But sometimes as little as this +cooldown_at = 2.0 # After this many seconds, start slowing down +dim_at = 2.5 # After this many seconds, dim LEDs +brightness_high = 0.5 # Active brightness +brightness_low = 0.125 # Idle brightness -color = [0, 120, 30] # Initial LED color -offset = 0 # Animation position -frame_len = default_frame_len # Frame-to-frame time, seconds -last_vibration = 0.0 # Time of last vibration -last_frame = 0.0 # Time of last animation frame +color = [0, 120, 30] # Initial LED color +offset = 0 # Animation position +frame_len = default_frame_len # Frame-to-frame time, seconds +last_vibration = 0.0 # Time of last vibration +last_frame = 0.0 # Time of last animation frame # Random number generator is seeded from an unused 'floating' # analog input - this helps ensure the random color choices @@ -36,45 +36,47 @@ random.seed(pin.value) pin.deinit() # Set up digital pin for reading vibration switch -pin = digitalio.DigitalInOut(vibration_pin) +pin = digitalio.DigitalInOut(vibration_pin) pin.direction = digitalio.Direction.INPUT -pin.pull = digitalio.Pull.UP +pin.pull = digitalio.Pull.UP while True: # Loop forever... - while True: - # Compare time.monotonic() against last_frame to keep - # frame-to-frame animation timing consistent. Use this - # idle time to check the vibration switch for activity. - t = time.monotonic() - if t - last_frame >= frame_len: break - if not pin.value: # Vibration switch activated? - color = [ # Pick a random RGB color... - random.randint(32, 255), - random.randint(32, 255), - random.randint(32, 255) ] - frame_len = default_frame_len # Reset frame timing - last_vibration = t # Save last trigger time + while True: + # Compare time.monotonic() against last_frame to keep + # frame-to-frame animation timing consistent. Use this + # idle time to check the vibration switch for activity. + t = time.monotonic() + if t - last_frame >= frame_len: + break + if not pin.value: # Vibration switch activated? + color = [ # Pick a random RGB color... + random.randint(32, 255), + random.randint(32, 255), + random.randint(32, 255)] + frame_len = default_frame_len # Reset frame timing + last_vibration = t # Save last trigger time - # Stretch out frames if nothing has happened in a couple of seconds: - if((t - last_vibration) > cooldown_at): - frame_len += 0.001 # Add 1 ms - if frame_len > max_frame_len: frame_len = min_frame_len + # Stretch out frames if nothing has happened in a couple of seconds: + if((t - last_vibration) > cooldown_at): + frame_len += 0.001 # Add 1 ms + if frame_len > max_frame_len: + frame_len = min_frame_len - # If we haven't registered a vibration in dim_at ms, go dim: - if (t - last_vibration) > dim_at: - strip.brightness = brightness_low - else: - strip.brightness = brightness_high + # If we haven't registered a vibration in dim_at ms, go dim: + if (t - last_vibration) > dim_at: + strip.brightness = brightness_low + else: + strip.brightness = brightness_high - # Erase previous pixels and light new ones: - strip.fill( [0, 0, 0] ) - for i in range(0, num_leds, 6): - strip[(offset + i) % num_leds] = color + # Erase previous pixels and light new ones: + strip.fill([0, 0, 0]) + for i in range(0, num_leds, 6): + strip[(offset + i) % num_leds] = color - strip.write() # and issue data to LED strip + strip.write() # and issue data to LED strip - # Increase pixel offset until it hits 6, then roll back to 0: - offset = (offset + 1) % 6 + # Increase pixel offset until it hits 6, then roll back to 0: + offset = (offset + 1) % 6 - last_frame = t + last_frame = t diff --git a/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py b/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py index d61c73059..8d9f06036 100644 --- a/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py +++ b/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py @@ -10,15 +10,17 @@ BPP = 4 # required for RGBW ring ring = neopixel.NeoPixel(pixpin, numpix, bpp=BPP, brightness=0.9) + def val(pin): # divides voltage (65535) to get a value between 0 and 255 - return pin.value / 257 + return pin.value / 257 + while True: # Two lines for troubleshooting to see analog value in REPL # print("A0: %f" % (pot.value / 65535 * 3.3)) - # time.sleep(1) - + # time.sleep(1) + # change floating point value to an int ring.fill((0, 0, 0, int(val(pot)))) time.sleep(0.01) diff --git a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py index 1d319581f..5fc675039 100644 --- a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py +++ b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py @@ -1,4 +1,4 @@ -import board +import board import neopixel import time @@ -6,17 +6,18 @@ pixpin = board.D1 numpix = 7 pixels = neopixel.NeoPixel(pixpin, numpix, brightness=.3, auto_write=False) - -rgb_colors = ( [179,0,0], - [0,179,0], - [0,0,0] ) + +rgb_colors = ([179, 0, 0], + [0, 179, 0], + [0, 0, 0]) rgb_idx = 0 # index counter - primary color we are on -color = (0, 164, 179) # Starting color -mode = 0 # Current animation effect -offset = 0; +color = (0, 164, 179) # Starting color +mode = 0 # Current animation effect +offset = 0 prevtime = 0 + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. @@ -31,49 +32,54 @@ def wheel(pos): pos -= 170 return (0, int(pos*3), int(255 - pos*3)) + def rainbow_cycle(wait): - for j in range(255*6): # 6 cycles of all colors on wheel + for j in range(255*6): # 6 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow(wait): for j in range(255): for i in range(len(pixels)): - idx = int (i+j) + idx = int(i+j) pixels[i] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow_cycle_slow(wait): for j in range(255*3): # 3 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow_hold(wait): - for j in range(255*1): # 3 cycles of all colors on wheel + for j in range(255*1): # 3 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + while True: - if ( mode == 0 ): # rainbow hold + if (mode == 0): # rainbow hold rainbow_hold(0.02) time.sleep(.5) - elif ( mode == 1 ): # rainbow cycle slow - rainbow_cycle_slow(0.02) + elif (mode == 1): # rainbow cycle slow + rainbow_cycle_slow(0.02) time.sleep(0.05) - elif ( mode == 2): # rainbow cycle fast + elif (mode == 2): # rainbow cycle fast rainbow_cycle(0.005) time.sleep(0.050) @@ -81,16 +87,16 @@ while True: if ((t - prevtime) > 8): # Every 8 seconds... mode += 1 # Next mode - if( mode > 2 ): # End of modes? + if(mode > 2): # End of modes? mode = 0 # Start modes over - if ( rgb_idx > 2 ): # reset R-->G-->B rotation + if (rgb_idx > 2): # reset R-->G-->B rotation rgb_idx = 0 - color = rgb_colors[rgb_idx] # next color assignment + color = rgb_colors[rgb_idx] # next color assignment rgb_idx += 1 for i in range(numpix): - pixels[i] = (0,0,0) + pixels[i] = (0, 0, 0) prevtime = t diff --git a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py index b652ee60a..bb0f6ba44 100644 --- a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py +++ b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py @@ -1,5 +1,5 @@ from digitalio import DigitalInOut, Direction -import board +import board import neopixel import time @@ -11,10 +11,12 @@ led.direction = Direction.OUTPUT strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) + def colorWipe(color, wait): for j in range(len(strip)): - strip[j] = (color) - time.sleep(wait) + strip[j] = (color) + time.sleep(wait) + def wheel(pos): # Input a value 0 to 255 to get a color value. @@ -30,24 +32,27 @@ def wheel(pos): pos -= 170 return (0, int(pos*3), int(255 - pos*3)) + def rainbow_cycle(wait): for j in range(255): for i in range(len(strip)): - idx = int ((i * 256 / len(strip)) + j) + idx = int((i * 256 / len(strip)) + j) strip[i] = wheel(idx & 255) time.sleep(wait) + def rainbow(wait): for j in range(255): for i in range(len(strip)): - idx = int (i+j) + idx = int(i+j) strip[i] = wheel(idx & 255) + while True: - colorWipe( (255, 0, 0), .1 ) # red and delay - colorWipe( (0, 255, 0), .1 ) # green and delay - colorWipe( (0, 0, 255), .1) # blue and delay + colorWipe((255, 0, 0), .1) # red and delay + colorWipe((0, 255, 0), .1) # green and delay + colorWipe((0, 0, 255), .1) # blue and delay rainbow(0.05) rainbow_cycle(0.05) diff --git a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py index d4702e097..270c0bb93 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py @@ -2,26 +2,26 @@ import board import neopixel import time try: - import urandom as random + import urandom as random except ImportError: - import random + import random numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) -color = [5, 250, 200] # RGB color - cyan +strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) +color = [5, 250, 200] # RGB color - cyan -sine = [ # These are the pixels in order of animation - 70 pixels in total: - 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60, - 61, 62, 63, 48, 49, 50, 51, 52, 44, 43, 42, 41, 40, 39, 38, 37, 36, 28, - 29, 30, 31, 16, 17, 18, 19, 20, 12, 11, 10, 9, 8, 7, 6, 5 ] +sine = [ # These are the pixels in order of animation - 70 pixels in total: + 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 48, 49, 50, 51, 52, 44, 43, 42, 41, 40, 39, 38, 37, 36, 28, + 29, 30, 31, 16, 17, 18, 19, 20, 12, 11, 10, 9, 8, 7, 6, 5] while True: # Loop forever... - for i in range(len(sine)): - # Erase 'tail': - strip[sine[i]] = [0,0,0] - # Draw 'head,' 10 pixels ahead: - strip[sine[(i + 10) % len(sine)]] = color - strip.write() # Refresh LED states - time.sleep(0.04) # 40 millisecond delay + for i in range(len(sine)): + # Erase 'tail': + strip[sine[i]] = [0, 0, 0] + # Draw 'head,' 10 pixels ahead: + strip[sine[(i + 10) % len(sine)]] = color + strip.write() # Refresh LED states + time.sleep(0.04) # 40 millisecond delay diff --git a/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py b/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py index 022a0821a..f8a971191 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py @@ -2,27 +2,27 @@ import board import neopixel import time try: - import urandom as random + import urandom as random except ImportError: - import random + import random numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.0) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.0) colors = [ - [ 232, 100, 255 ], # Purple - [ 200, 200, 20 ], # Yellow - [ 30, 200, 200 ], # Blue + [232, 100, 255], # Purple + [200, 200, 20], # Yellow + [30, 200, 200], # Blue ] while True: # Loop forever... - c = random.randint(0, len(colors) - 1) # Choose random color index - j = random.randint(0, numpix - 1) # Choose random pixel - strip[j] = colors[c] # Set pixel to color - for i in range(1, 5): - strip.brightness = i / 5.0 # Ramp up brightness - strip.write() - for i in range(5, 0, -1): - strip.brightness = i / 5.0 # Ramp down brightness - strip.write() - strip[j] = [0,0,0] # Set pixel to 'off' + c = random.randint(0, len(colors) - 1) # Choose random color index + j = random.randint(0, numpix - 1) # Choose random pixel + strip[j] = colors[c] # Set pixel to color + for i in range(1, 5): + strip.brightness = i / 5.0 # Ramp up brightness + strip.write() + for i in range(5, 0, -1): + strip.brightness = i / 5.0 # Ramp down brightness + strip.write() + strip[j] = [0, 0, 0] # Set pixel to 'off' diff --git a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py index d47330119..43c536c6a 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py @@ -2,24 +2,24 @@ import board import neopixel import time try: - import urandom as random # for v1.0 API support + import urandom as random # for v1.0 API support except ImportError: - import random + import random numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) -color = [75, 250, 100] # RGB color - teal +strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) +color = [75, 250, 100] # RGB color - teal -sine = [ # These are the pixels in order of animation - 36 pixels in total: - 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60 ] +sine = [ # These are the pixels in order of animation - 36 pixels in total: + 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60] while True: # Loop forever... - for i in range(len(sine)): - # Set 'head' pixel to color: - strip[sine[i]] = color - # Erase 'tail,' 8 pixels back: - strip[sine[(i + len(sine) - 8) % len(sine)]] = [0,0,0] - strip.write() # Refresh LED states - time.sleep(0.016) # 16 millisecond delay + for i in range(len(sine)): + # Set 'head' pixel to color: + strip[sine[i]] = color + # Erase 'tail,' 8 pixels back: + strip[sine[(i + len(sine) - 8) % len(sine)]] = [0, 0, 0] + strip.write() # Refresh LED states + time.sleep(0.016) # 16 millisecond delay diff --git a/NeoPixel_Tiara/NeoPixel_Tiara.py b/NeoPixel_Tiara/NeoPixel_Tiara.py index 14c27ed1d..af64a5f4e 100644 --- a/NeoPixel_Tiara/NeoPixel_Tiara.py +++ b/NeoPixel_Tiara/NeoPixel_Tiara.py @@ -2,38 +2,41 @@ import board import neopixel import time try: - import urandom as random + import urandom as random except ImportError: - import random + import random numpix = 7 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) +strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) colors = [ - [ 232, 100, 255 ], # Purple - [ 200, 200, 20 ], # Yellow - [ 30, 200, 200 ], # Blue + [232, 100, 255], # Purple + [200, 200, 20], # Yellow + [30, 200, 200], # Blue ] -def flash_random(wait,howmany): - for k in range(howmany): +def flash_random(wait, howmany): - c = random.randint(0, len(colors) - 1) # Choose random color index - j = random.randint(0, numpix - 1) # Choose random pixel - strip[j] = colors[c] # Set pixel to color + for k in range(howmany): + + c = random.randint(0, len(colors) - 1) # Choose random color index + j = random.randint(0, numpix - 1) # Choose random pixel + strip[j] = colors[c] # Set pixel to color + + for i in range(1, 5): + strip.brightness = i / 5.0 # Ramp up brightness + time.sleep(wait) + + for i in range(5, 0, -1): + strip.brightness = i / 5.0 # Ramp down brightness + strip[j] = [0, 0, 0] # Set pixel to 'off' + time.sleep(wait) - for i in range(1, 5): - strip.brightness = i / 5.0 # Ramp up brightness - time.sleep(wait) - - - for i in range(5, 0, -1): - strip.brightness = i / 5.0 # Ramp down brightness - strip[j] = [0,0,0] # Set pixel to 'off' - time.sleep(wait) while True: - flash_random(.01, 1) # first number is 'wait' delay, shorter num == shorter twinkle - flash_random(.01, 3) # second number is how many neopixels to simultaneously light up - flash_random(.01, 2) + # first number is 'wait' delay, shorter num == shorter twinkle + flash_random(.01, 1) + # second number is how many neopixels to simultaneously light up + flash_random(.01, 3) + flash_random(.01, 2) diff --git a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py index ce3d2fb0c..c902c7e88 100644 --- a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py +++ b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py @@ -1,99 +1,100 @@ -# NeoPixie Dust Bag +# NeoPixie Dust Bag # learn.adafruit.com/neopixel-pixie-dust-bag -import digitalio -import board -import neopixel import time +import board +import digitalio +import neopixel + try: import urandom as random # for v1.0 API support except ImportError: import random -neo_pin = board.D0 # DIGITAL IO pin for NeoPixel OUTPUT from GEMMA -touch_pin = board.D2 # DIGITAL IO pin for momentary touch sensor INPUT to GEMMA -pixel_count = 30 # Number of NeoPixels connected to GEMMA -delay_sec = .010 # delay between blinks, smaller numbers are faster -delay_mult = 8 # Randomization multiplier, delay speed of the effect +neo_pin = board.D0 # DIGITAL IO pin for NeoPixel OUTPUT from GEMMA +touch_pin = board.D2 # DIGITAL IO pin for momentary touch sensor INPUT to GEMMA +pixel_count = 30 # Number of NeoPixels connected to GEMMA +delay_sec = .010 # delay between blinks, smaller numbers are faster +delay_mult = 8 # Randomization multiplier, delay speed of the effect # initialize neopixels -pixels = neopixel.NeoPixel(neo_pin, pixel_count, brightness=.4, auto_write=False) +pixels = neopixel.NeoPixel( + neo_pin, pixel_count, brightness=.4, auto_write=False) -oldstate = True # counting touch sensor button pushes -showcolor = 0 # color mode for cycling +oldstate = True # counting touch sensor button pushes +showcolor = 0 # color mode for cycling -# initialize capacitive touch input +# initialize capacitive touch input button = digitalio.DigitalInOut(touch_pin) button.direction = digitalio.Direction.INPUT button.pull = digitalio.Pull.UP while True: - rcolor = 100 # swtich cycles colors, initially GOLD + rcolor = 100 # swtich cycles colors, initially GOLD gcolor = 0 bcolor = 0 - - if ( showcolor == 0 ): # Garden PINK - rcolor = 242 - gcolor = 90 - bcolor = 255 - elif ( showcolor == 1 ): # Pixie GOLD - rcolor = 255 - gcolor = 222 - bcolor = 30 + if (showcolor == 0): # Garden PINK + rcolor = 242 + gcolor = 90 + bcolor = 255 - elif ( showcolor == 2 ): # Alchemy BLUE - rcolor = 50 - gcolor = 255 - bcolor = 255 + elif (showcolor == 1): # Pixie GOLD + rcolor = 255 + gcolor = 222 + bcolor = 30 - elif ( showcolor == 3 ): # Animal ORANGE - rcolor = 255 - gcolor = 100 - bcolor = 0 + elif (showcolor == 2): # Alchemy BLUE + rcolor = 50 + gcolor = 255 + bcolor = 255 + + elif (showcolor == 3): # Animal ORANGE + rcolor = 255 + gcolor = 100 + bcolor = 0 + + elif (showcolor == 4): # Tinker GREEN + rcolor = 0 + gcolor = 255 + bcolor = 40 - elif ( showcolor == 4 ): # Tinker GREEN - rcolor = 0 - gcolor = 255 - bcolor = 40 - # sparkling # select a random pixel - p = random.randint(0, (pixel_count - 2)) + p = random.randint(0, (pixel_count - 2)) # color value from momentary switch - pixels[p] = (rcolor, gcolor, bcolor) + pixels[p] = (rcolor, gcolor, bcolor) pixels.write() # delay value randomized to up to delay_mult times longer - time.sleep( delay_sec * random.randint(0, delay_mult) ) + time.sleep(delay_sec * random.randint(0, delay_mult)) # set to a dimmed version of the state color - pixels[p] = (int(rcolor / 10 ), int(gcolor / 10), int(bcolor / 10)) + pixels[p] = (int(rcolor / 10), int(gcolor / 10), int(bcolor / 10)) pixels.write() # set a neighbor pixel to an even dimmer value - pixels[p+1] = (int(rcolor / 15), int(gcolor / 15), int(bcolor / 15)) + pixels[p + 1] = (int(rcolor / 15), int(gcolor / 15), int(bcolor / 15)) pixels.write() - + # button check to cycle through color value sets - # get the current button state - newstate = button.value + # get the current button state + newstate = button.value # Check if state changed from high to low (button press). - if ( newstate and not oldstate ): - + if (newstate and not oldstate): # Short delay to debounce button. time.sleep(0.020) # Check if button is still low after debounce. newstate = button.value - if ( newstate == False ): + if (newstate == False): showcolor += 1 - if ( showcolor > 4 ): + if (showcolor > 4): showcolor = 0 # Set the last button state to the old state. diff --git a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py index d503cdab8..dfcf87ebc 100644 --- a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py +++ b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py @@ -18,13 +18,13 @@ buffer = [] while True: data = uart.read(32) # read up to 32 bytes data = list(data) - #print("read: ", data) # this is a bytearray type + # print("read: ", data) # this is a bytearray type buffer += data - + while buffer and buffer[0] != 0x42: buffer.pop(0) - + if len(buffer) > 200: buffer = [] # avoid an overrun if all bad data if len(buffer) < 32: @@ -44,14 +44,15 @@ while True: pm10_standard, pm25_standard, pm100_standard, pm10_env, pm25_env, pm100_env, particles_03um, particles_05um, particles_10um, particles_25um, particles_50um, particles_100um, skip, checksum = frame check = sum(buffer[0:30]) - + if check != checksum: buffer = [] continue print("Concentration Units (standard)") print("---------------------------------------") - print("PM 1.0: %d\tPM2.5: %d\tPM10: %d" % (pm10_standard, pm25_standard, pm100_standard)) + print("PM 1.0: %d\tPM2.5: %d\tPM10: %d" % + (pm10_standard, pm25_standard, pm100_standard)) print("Concentration Units (environmental)") print("---------------------------------------") print("PM 1.0: %d\tPM2.5: %d\tPM10: %d" % (pm10_env, pm25_env, pm100_env)) diff --git a/Pi_Hole_Ad_Blocker/stats.py b/Pi_Hole_Ad_Blocker/stats.py index 2d0f2c8c6..11a2aec94 100644 --- a/Pi_Hole_Ad_Blocker/stats.py +++ b/Pi_Hole_Ad_Blocker/stats.py @@ -19,23 +19,20 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. +import json +import subprocess import time -import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 - +import requests from PIL import Image from PIL import ImageDraw from PIL import ImageFont -import subprocess -import json -import requests - api_url = 'http://localhost/admin/api.php' # Raspberry Pi pin configuration: -RST = None # on the PiOLED this pin isnt used +RST = None # on the PiOLED this pin isnt used # 128x32 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) @@ -57,13 +54,13 @@ image = Image.new('1', (width, height)) draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. -draw.rectangle((0,0,width,height), outline=0, fill=0) +draw.rectangle((0, 0, width, height), outline=0, fill=0) # Draw some shapes. # First define some constants to allow easy resizing of shapes. padding = -2 top = padding -bottom = height-padding +bottom = height - padding # Move left to right keeping track of the current x position for drawing shapes. x = 0 @@ -72,40 +69,44 @@ font = ImageFont.truetype("/home/pi/slkscr.ttf", 8) while True: # Draw a black filled box to clear the image. - draw.rectangle((0,0,width,height), outline=0, fill=0) + draw.rectangle((0, 0, width, height), outline=0, fill=0) # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" - IP = subprocess.check_output(cmd, shell = True ) + IP = subprocess.check_output(cmd, shell=True) cmd = "hostname" - HOST = subprocess.check_output(cmd, shell = True ) + HOST = subprocess.check_output(cmd, shell=True) cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'" - CPU = subprocess.check_output(cmd, shell = True ) + CPU = subprocess.check_output(cmd, shell=True) cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'" - MemUsage = subprocess.check_output(cmd, shell = True ) + MemUsage = subprocess.check_output(cmd, shell=True) cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'" - Disk = subprocess.check_output(cmd, shell = True ) + Disk = subprocess.check_output(cmd, shell=True) # Pi Hole data! try: - r = requests.get(api_url) - data = json.loads(r.text) - DNSQUERIES = data['dns_queries_today'] - ADSBLOCKED = data['ads_blocked_today'] - CLIENTS = data['unique_clients'] + r = requests.get(api_url) + data = json.loads(r.text) + DNSQUERIES = data['dns_queries_today'] + ADSBLOCKED = data['ads_blocked_today'] + CLIENTS = data['unique_clients'] except: - time.sleep(1) - continue + time.sleep(1) + continue - draw.text((x, top), "IP: " + str(IP) + "( " + HOST + ")", font=font, fill=255) - draw.text((x, top+8), "Ads Blocked: " + str(ADSBLOCKED), font=font, fill=255) - draw.text((x, top+16), "Clients: " + str(CLIENTS), font=font, fill=255) - draw.text((x, top+24), "DNS Queries: " + str(DNSQUERIES), font=font, fill=255) + draw.text((x, top), "IP: " + str(IP) + + "( " + HOST + ")", font=font, fill=255) + draw.text((x, top + 8), "Ads Blocked: " + + str(ADSBLOCKED), font=font, fill=255) + draw.text((x, top + 16), "Clients: " + + str(CLIENTS), font=font, fill=255) + draw.text((x, top + 24), "DNS Queries: " + + str(DNSQUERIES), font=font, fill=255) # skip over original stats - #draw.text((x, top+8), str(CPU), font=font, fill=255) - #draw.text((x, top+16), str(MemUsage), font=font, fill=255) - #draw.text((x, top+25), str(Disk), font=font, fill=255) + # draw.text((x, top+8), str(CPU), font=font, fill=255) + # draw.text((x, top+16), str(MemUsage), font=font, fill=255) + # draw.text((x, top+25), str(Disk), font=font, fill=255) # Display image. disp.image(image) diff --git a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py index b77e3be9b..1a8aefc90 100644 --- a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py +++ b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py @@ -62,7 +62,8 @@ while True: if n >= noise: # Remove noise/hum n = n - noise - lvl = int(((lvl * 7) + n) / 8) # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) + # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) + lvl = int(((lvl * 7) + n) / 8) # Calculate bar height based on dynamic min/max levels (fixed point): height = top * (lvl - min_level_avg) / (max_level_avg - min_level_avg) @@ -112,7 +113,9 @@ while True: if (max_level - min_level) < top: max_level = min_level + top - min_level_avg = (min_level_avg * 63 + min_level) >> 6 # Dampen min/max levels - divide by 64 (2^6) - max_level_avg = (max_level_avg * 63 + max_level) >> 6 # fake rolling average - divide by 64 (2^6) + # Dampen min/max levels - divide by 64 (2^6) + min_level_avg = (min_level_avg * 63 + min_level) >> 6 + # fake rolling average - divide by 64 (2^6) + max_level_avg = (max_level_avg * 63 + max_level) >> 6 print(n) diff --git a/raver_bandolier/raver_bandolier.py b/raver_bandolier/raver_bandolier.py index f65b28411..ef47032d6 100644 --- a/raver_bandolier/raver_bandolier.py +++ b/raver_bandolier/raver_bandolier.py @@ -1,96 +1,103 @@ -import board -import neopixel import time +import board +import neopixel + pixpin = board.D1 numpix = 20 pixels = neopixel.NeoPixel(pixpin, numpix, brightness=.3, auto_write=False) - -rgb_colors = ( [179,0,0], - [0,179,0], - [0,0,0] ) -rgb_idx = 0 # index counter - primary color we are on -color = (0, 164, 179) # Starting color -mode = 0 # Current animation effect -offset = 0; +rgb_colors = ([179, 0, 0], + [0, 179, 0], + [0, 0, 0]) + +rgb_idx = 0 # index counter - primary color we are on +color = (0, 164, 179) # Starting color +mode = 0 # Current animation effect +offset = 0 prevtime = 0 + def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) - elif (pos < 170): + if pos < 85: + return (int(pos * 3), int(255 - (pos * 3)), 0) + elif pos < 170: pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) + def rainbow_cycle(wait): - for j in range(255*6): # 6 cycles of all colors on wheel + for j in range(255 * 6): # 6 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow(wait): for j in range(255): - for i in range(len(pixels)): - idx = int (i+j) - pixels[i] = wheel(idx & 255) + for index in range(len(pixels)): + idx = int(index + j) + pixels[index] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow_cycle_slow(wait): - for j in range(255*3): # 3 cycles of all colors on wheel + for j in range(255 * 3): # 3 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + def rainbow_hold(wait): - for j in range(255*1): # 3 cycles of all colors on wheel + for j in range(255 * 1): # 3 cycles of all colors on wheel for r in range(len(pixels)): - idx = int ((r * 255 / len(pixels)) + j) + idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) pixels.write() time.sleep(wait) + while True: - if ( mode == 0 ): # rainbow hold + if mode == 0: # rainbow hold rainbow_hold(0.02) time.sleep(.5) - elif ( mode == 1 ): # rainbow cycle slow - rainbow_cycle_slow(0.02) + elif mode == 1: # rainbow cycle slow + rainbow_cycle_slow(0.02) time.sleep(0.05) - elif ( mode == 2): # rainbow cycle fast + elif mode == 2: # rainbow cycle fast rainbow_cycle(0.005) time.sleep(0.050) t = time.monotonic() - if ((t - prevtime) > 8): # Every 8 seconds... - mode += 1 # Next mode - if( mode > 2 ): # End of modes? - mode = 0 # Start modes over + if (t - prevtime) > 8: # Every 8 seconds... + mode += 1 # Next mode + if mode > 2: # End of modes? + mode = 0 # Start modes over - if ( rgb_idx > 2 ): # reset R-->G-->B rotation + if rgb_idx > 2: # reset R-->G-->B rotation rgb_idx = 0 - color = rgb_colors[rgb_idx] # next color assignment + color = rgb_colors[rgb_idx] # next color assignment rgb_idx += 1 for i in range(numpix): - pixels[i] = (0,0,0) + pixels[i] = (0, 0, 0) prevtime = t From aecc9347c969494fed4719219bf9a832509b19e7 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 19:11:51 +0100 Subject: [PATCH 29/83] Autformat the rest --- Morse_Code_Flasher/main.py | 55 ++++++++++++++++--- Motorized_Turntable/turntable.py | 9 +-- .../Mystical_LED_Halloween_Hood.py | 36 ++++++------ NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py | 36 ++++++------ .../HSV_FancyLED_NeoPixel_Dailer.py | 5 +- NeoPixel_Dialer/RGB_NeoPixel_Dialer.py | 7 ++- .../NeoPixel_GoPro_Lens_Light.py | 11 ++-- .../NeoPixel_Jewel_10_Minute_Necklace.py | 39 ++++++------- NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py | 14 ++--- NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py | 12 ++-- NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py | 16 +++--- NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py | 10 ++-- NeoPixel_Tiara/NeoPixel_Tiara.py | 19 ++++--- .../PMS5003_CircuitPython/main.py | 8 +-- Remote_Tree_Ornament/main.py | 2 +- 15 files changed, 164 insertions(+), 115 deletions(-) diff --git a/Morse_Code_Flasher/main.py b/Morse_Code_Flasher/main.py index 9911569c4..89684ba22 100644 --- a/Morse_Code_Flasher/main.py +++ b/Morse_Code_Flasher/main.py @@ -7,30 +7,67 @@ # License: MIT License (https://opensource.org/licenses/MIT) import time + import board import neopixel # Configuration: # Message to display (capital letters and numbers only) message = 'SOS' -dot_length = 0.15 # Duration of one Morse dot -dash_length = (dot_length * 3.0) # Duration of one Morse dash -symbol_gap = dot_length # Duration of gap between dot or dash +dot_length = 0.15 # Duration of one Morse dot +dash_length = (dot_length * 3.0) # Duration of one Morse dash +symbol_gap = dot_length # Duration of gap between dot or dash character_gap = (dot_length * 3.0) # Duration of gap between characters -flash_color = (255, 0, 0) # Color of the morse display. -brightness = 0.5 # Display brightness (0.0 - 1.0) -morse = [('A', '.-'), ('B', '-...'), ('C', '-.-.'), ('D', '-..'), ('E', '.'), ('F', '..-.'), ('G', '--.'), ('H', '....'), ('I', '..'), ('J', '.---'), ('K', '-.-'), ('L', '.-..'), ('M', '--'), ('N', '-.'), ('O', '---'), ('P', '.--.'), ('Q', '--.-'), ('R', '.-.'), ('S', - '...'), ('T', '-'), ('U', '..-'), ('V', '...-'), ('W', '.--'), ('X', '-..-'), ('Y', '-.--'), ('Z', '--..'), ('0', '-----'), ('1', '.----'), ('2', '..---'), ('3', '...--'), ('4', '....-'), ('5', '.....'), ('6', '-....'), ('7', '--...'), ('8', '---..'), ('9', '----.')] +flash_color = (255, 0, 0) # Color of the morse display. +brightness = 0.5 # Display brightness (0.0 - 1.0) +morse = [ + ('A', '.-'), + ('B', '-...'), + ('C', '-.-.'), + ('D', '-..'), + ('E', '.'), + ('F', '..-.'), + ('G', '--.'), + ('H', '....'), + ('I', '..'), + ('J', '.---'), + ('K', '-.-'), + ('L', '.-..'), + ('M', '--'), + ('N', '-.'), + ('O', '---'), + ('P', '.--.'), + ('Q', '--.-'), + ('R', '.-.'), + ('S', '...'), + ('T', '-'), + ('U', '..-'), + ('V', '...-'), + ('W', '.--'), + ('X', '-..-'), + ('Y', '-.--'), + ('Z', '--..'), + ('0', '-----'), + ('1', '.----'), + ('2', '..---'), + ('3', '...--'), + ('4', '....-'), + ('5', '.....'), + ('6', '-....'), + ('7', '--...'), + ('8', '---..'), + ('9', '----.'), +] + # Define a class that represents the morse flasher. class MorseFlasher: - def __init__(self, color=(255, 255, 255)): # set the color adjusted for brightness self._color = ( - int(color[0]*brightness), int(color[1]*brightness), int(color[2]*brightness)) + int(color[0] * brightness), int(color[1] * brightness), int(color[2] * brightness)) def light(self, on=True): if on: diff --git a/Motorized_Turntable/turntable.py b/Motorized_Turntable/turntable.py index 68a66023c..0026ba53b 100644 --- a/Motorized_Turntable/turntable.py +++ b/Motorized_Turntable/turntable.py @@ -1,9 +1,10 @@ -import board import time -import pulseio -from digitalio import DigitalInOut, Direction, Pull -from analogio import AnalogIn + import adafruit_motor.servo +import board +import pulseio +from analogio import AnalogIn +from digitalio import DigitalInOut, Direction, Pull pwm = pulseio.PWMOut(board.D5, frequency=50) servo = adafruit_motor.servo.Servo(pwm) diff --git a/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py b/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py index 42fc5a072..d55753905 100644 --- a/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py +++ b/Mystical_LED_Halloween_Hood/Mystical_LED_Halloween_Hood.py @@ -1,36 +1,36 @@ import board import neopixel -import time + try: import urandom as random # for v1.0 API support except ImportError: import random -numpix = 17 # Number of NeoPixels -pixpin = board.D1 # Pin where NeoPixels are connected +numpix = 17 # Number of NeoPixels +pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix) -minAlpha = 0.1 # Minimum brightness -maxAlpha = 0.4 # Maximum brightness +minAlpha = 0.1 # Minimum brightness +maxAlpha = 0.4 # Maximum brightness alpha = (minAlpha + maxAlpha) / 2 # Start in middle alphaDelta = 0.008 # Amount to change brightness each time through loop -alphaUp = True # If True, brightness increasing, else decreasing +alphaUp = True # If True, brightness increasing, else decreasing strip.fill([255, 0, 0]) # Fill red, or change to R,G,B of your liking while True: # Loop forever... - if random.randint(1, 5) == 5: # 1-in-5 random chance - alphaUp = not alphaUp # of reversing direction - if alphaUp: # Increasing brightness? - alpha += alphaDelta # Add some amount - if alpha >= maxAlpha: # At or above max? + if random.randint(1, 5) == 5: # 1-in-5 random chance + alphaUp = not alphaUp # of reversing direction + if alphaUp: # Increasing brightness? + alpha += alphaDelta # Add some amount + if alpha >= maxAlpha: # At or above max? alpha = maxAlpha # Limit to max - alphaUp = False # and switch direction - else: # Else decreasing brightness - alpha -= alphaDelta # Subtract some amount - if alpha <= minAlpha: # At or below min? + alphaUp = False # and switch direction + else: # Else decreasing brightness + alpha -= alphaDelta # Subtract some amount + if alpha <= minAlpha: # At or below min? alpha = minAlpha # Limit to min - alphaUp = True # and switch direction + alphaUp = True # and switch direction - strip.brightness = alpha # Set brightness to 0.0 to 1.0 - strip.write() # and issue data to LED strip + strip.brightness = alpha # Set brightness to 0.0 to 1.0 + strip.write() # and issue data to LED strip diff --git a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py index 67e1f2829..d4b6dadcc 100644 --- a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py +++ b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py @@ -1,32 +1,34 @@ +import time + +import analogio import board import digitalio -import analogio import neopixel -import time + try: import urandom as random # for v1.0 API support except: import random -num_leds = 24 # 24 LED NeoPixel ring -neopixel_pin = board.D0 # Pin where NeoPixels are connected -vibration_pin = board.D1 # Pin where vibration switch is connected -analog_pin = board.A0 # Not connected to anything +num_leds = 24 # 24 LED NeoPixel ring +neopixel_pin = board.D0 # Pin where NeoPixels are connected +vibration_pin = board.D1 # Pin where vibration switch is connected +analog_pin = board.A0 # Not connected to anything strip = neopixel.NeoPixel(neopixel_pin, num_leds) -default_frame_len = 0.06 # Time (in seconds) of typical animation frame -max_frame_len = 0.25 # Gradually slows toward this +default_frame_len = 0.06 # Time (in seconds) of typical animation frame +max_frame_len = 0.25 # Gradually slows toward this min_frame_len = 0.005 # But sometimes as little as this -cooldown_at = 2.0 # After this many seconds, start slowing down -dim_at = 2.5 # After this many seconds, dim LEDs -brightness_high = 0.5 # Active brightness +cooldown_at = 2.0 # After this many seconds, start slowing down +dim_at = 2.5 # After this many seconds, dim LEDs +brightness_high = 0.5 # Active brightness brightness_low = 0.125 # Idle brightness -color = [0, 120, 30] # Initial LED color -offset = 0 # Animation position +color = [0, 120, 30] # Initial LED color +offset = 0 # Animation position frame_len = default_frame_len # Frame-to-frame time, seconds -last_vibration = 0.0 # Time of last vibration -last_frame = 0.0 # Time of last animation frame +last_vibration = 0.0 # Time of last vibration +last_frame = 0.0 # Time of last animation frame # Random number generator is seeded from an unused 'floating' # analog input - this helps ensure the random color choices @@ -55,10 +57,10 @@ while True: # Loop forever... random.randint(32, 255), random.randint(32, 255)] frame_len = default_frame_len # Reset frame timing - last_vibration = t # Save last trigger time + last_vibration = t # Save last trigger time # Stretch out frames if nothing has happened in a couple of seconds: - if((t - last_vibration) > cooldown_at): + if ((t - last_vibration) > cooldown_at): frame_len += 0.001 # Add 1 ms if frame_len > max_frame_len: frame_len = min_frame_len diff --git a/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py b/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py index eb76a6964..5578c2e54 100644 --- a/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py +++ b/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py @@ -1,10 +1,11 @@ import time -from analogio import AnalogIn + +import adafruit_character_lcd import adafruit_fancyled.adafruit_fancyled as fancy import board import digitalio -import adafruit_character_lcd import neopixel +from analogio import AnalogIn lcd_rs = digitalio.DigitalInOut(board.D5) lcd_en = digitalio.DigitalInOut(board.D6) diff --git a/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py b/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py index 0c9229c09..99b85f864 100644 --- a/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py +++ b/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py @@ -1,10 +1,11 @@ -import time import math -from analogio import AnalogIn +import time + +import adafruit_character_lcd import board import digitalio -import adafruit_character_lcd import neopixel +from analogio import AnalogIn lcd_rs = digitalio.DigitalInOut(board.D5) lcd_en = digitalio.DigitalInOut(board.D6) diff --git a/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py b/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py index 8d9f06036..538a0f63b 100644 --- a/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py +++ b/NeoPixel_GoPro_Lens_Light/NeoPixel_GoPro_Lens_Light.py @@ -1,12 +1,13 @@ -from analogio import AnalogIn -import board import time + +import board import neopixel +from analogio import AnalogIn pot = AnalogIn(board.A1) # what pin the pot is on -pixpin = board.D0 # what pin the LEDs are on -numpix = 16 # number of LEDs in ring! -BPP = 4 # required for RGBW ring +pixpin = board.D0 # what pin the LEDs are on +numpix = 16 # number of LEDs in ring! +BPP = 4 # required for RGBW ring ring = neopixel.NeoPixel(pixpin, numpix, bpp=BPP, brightness=0.9) diff --git a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py index 5fc675039..8fab2753b 100644 --- a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py +++ b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py @@ -1,6 +1,7 @@ +import time + import board import neopixel -import time pixpin = board.D1 numpix = 7 @@ -11,9 +12,9 @@ rgb_colors = ([179, 0, 0], [0, 179, 0], [0, 0, 0]) -rgb_idx = 0 # index counter - primary color we are on -color = (0, 164, 179) # Starting color -mode = 0 # Current animation effect +rgb_idx = 0 # index counter - primary color we are on +color = (0, 164, 179) # Starting color +mode = 0 # Current animation effect offset = 0 prevtime = 0 @@ -24,17 +25,17 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): - for j in range(255*6): # 6 cycles of all colors on wheel + for j in range(255 * 6): # 6 cycles of all colors on wheel for r in range(len(pixels)): idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) @@ -45,14 +46,14 @@ def rainbow_cycle(wait): def rainbow(wait): for j in range(255): for i in range(len(pixels)): - idx = int(i+j) + idx = int(i + j) pixels[i] = wheel(idx & 255) pixels.write() time.sleep(wait) def rainbow_cycle_slow(wait): - for j in range(255*3): # 3 cycles of all colors on wheel + for j in range(255 * 3): # 3 cycles of all colors on wheel for r in range(len(pixels)): idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) @@ -61,7 +62,7 @@ def rainbow_cycle_slow(wait): def rainbow_hold(wait): - for j in range(255*1): # 3 cycles of all colors on wheel + for j in range(255 * 1): # 3 cycles of all colors on wheel for r in range(len(pixels)): idx = int((r * 255 / len(pixels)) + j) pixels[r] = wheel(idx & 255) @@ -71,26 +72,26 @@ def rainbow_hold(wait): while True: - if (mode == 0): # rainbow hold + if (mode == 0): # rainbow hold rainbow_hold(0.02) time.sleep(.5) - elif (mode == 1): # rainbow cycle slow + elif (mode == 1): # rainbow cycle slow rainbow_cycle_slow(0.02) time.sleep(0.05) - elif (mode == 2): # rainbow cycle fast + elif (mode == 2): # rainbow cycle fast rainbow_cycle(0.005) time.sleep(0.050) t = time.monotonic() - if ((t - prevtime) > 8): # Every 8 seconds... - mode += 1 # Next mode - if(mode > 2): # End of modes? - mode = 0 # Start modes over + if ((t - prevtime) > 8): # Every 8 seconds... + mode += 1 # Next mode + if (mode > 2): # End of modes? + mode = 0 # Start modes over - if (rgb_idx > 2): # reset R-->G-->B rotation + if (rgb_idx > 2): # reset R-->G-->B rotation rgb_idx = 0 color = rgb_colors[rgb_idx] # next color assignment diff --git a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py index bb0f6ba44..937b0b40a 100644 --- a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py +++ b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py @@ -1,7 +1,8 @@ -from digitalio import DigitalInOut, Direction +import time + import board import neopixel -import time +from digitalio import DigitalInOut, Direction pixpin = board.D1 numpix = 5 @@ -24,13 +25,13 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if (pos < 85): - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif (pos < 170): pos -= 85 - return (int(255 - pos*3), 0, int(pos*3)) + return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170 - return (0, int(pos*3), int(255 - pos*3)) + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): @@ -44,12 +45,11 @@ def rainbow_cycle(wait): def rainbow(wait): for j in range(255): for i in range(len(strip)): - idx = int(i+j) + idx = int(i + j) strip[i] = wheel(idx & 255) while True: - colorWipe((255, 0, 0), .1) # red and delay colorWipe((0, 255, 0), .1) # green and delay colorWipe((0, 0, 255), .1) # blue and delay diff --git a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py index 270c0bb93..556a22a46 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py @@ -1,21 +1,23 @@ +import time + import board import neopixel -import time + try: import urandom as random except ImportError: import random -numpix = 64 # Number of NeoPixels +numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) color = [5, 250, 200] # RGB color - cyan sine = [ # These are the pixels in order of animation - 70 pixels in total: - 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 48, 49, 50, 51, 52, 44, 43, 42, 41, 40, 39, 38, 37, 36, 28, - 29, 30, 31, 16, 17, 18, 19, 20, 12, 11, 10, 9, 8, 7, 6, 5] + 29, 30, 31, 16, 17, 18, 19, 20, 12, 11, 10, 9, 8, 7, 6, 5] while True: # Loop forever... for i in range(len(sine)): @@ -23,5 +25,5 @@ while True: # Loop forever... strip[sine[i]] = [0, 0, 0] # Draw 'head,' 10 pixels ahead: strip[sine[(i + 10) % len(sine)]] = color - strip.write() # Refresh LED states + strip.write() # Refresh LED states time.sleep(0.04) # 40 millisecond delay diff --git a/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py b/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py index f8a971191..ef1d7cc62 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Random_Flash.py @@ -1,28 +1,28 @@ import board import neopixel -import time + try: import urandom as random except ImportError: import random -numpix = 64 # Number of NeoPixels +numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.0) colors = [ [232, 100, 255], # Purple - [200, 200, 20], # Yellow + [200, 200, 20], # Yellow [30, 200, 200], # Blue ] while True: # Loop forever... c = random.randint(0, len(colors) - 1) # Choose random color index - j = random.randint(0, numpix - 1) # Choose random pixel - strip[j] = colors[c] # Set pixel to color + j = random.randint(0, numpix - 1) # Choose random pixel + strip[j] = colors[c] # Set pixel to color for i in range(1, 5): - strip.brightness = i / 5.0 # Ramp up brightness + strip.brightness = i / 5.0 # Ramp up brightness strip.write() for i in range(5, 0, -1): - strip.brightness = i / 5.0 # Ramp down brightness + strip.brightness = i / 5.0 # Ramp down brightness strip.write() - strip[j] = [0, 0, 0] # Set pixel to 'off' + strip[j] = [0, 0, 0] # Set pixel to 'off' diff --git a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py index 43c536c6a..fdc293d57 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py @@ -1,18 +1,20 @@ +import time + import board import neopixel -import time + try: import urandom as random # for v1.0 API support except ImportError: import random -numpix = 64 # Number of NeoPixels +numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) color = [75, 250, 100] # RGB color - teal sine = [ # These are the pixels in order of animation - 36 pixels in total: - 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 4, 3, 2, 1, 0, 15, 14, 13, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 36, 35, 34, 33, 32, 47, 46, 45, 44, 52, 53, 54, 55, 56, 57, 58, 59, 60] while True: # Loop forever... @@ -21,5 +23,5 @@ while True: # Loop forever... strip[sine[i]] = color # Erase 'tail,' 8 pixels back: strip[sine[(i + len(sine) - 8) % len(sine)]] = [0, 0, 0] - strip.write() # Refresh LED states + strip.write() # Refresh LED states time.sleep(0.016) # 16 millisecond delay diff --git a/NeoPixel_Tiara/NeoPixel_Tiara.py b/NeoPixel_Tiara/NeoPixel_Tiara.py index af64a5f4e..93108c9a8 100644 --- a/NeoPixel_Tiara/NeoPixel_Tiara.py +++ b/NeoPixel_Tiara/NeoPixel_Tiara.py @@ -1,36 +1,37 @@ +import time + import board import neopixel -import time + try: import urandom as random except ImportError: import random -numpix = 7 # Number of NeoPixels +numpix = 7 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) colors = [ [232, 100, 255], # Purple - [200, 200, 20], # Yellow + [200, 200, 20], # Yellow [30, 200, 200], # Blue ] def flash_random(wait, howmany): - for k in range(howmany): c = random.randint(0, len(colors) - 1) # Choose random color index - j = random.randint(0, numpix - 1) # Choose random pixel - strip[j] = colors[c] # Set pixel to color + j = random.randint(0, numpix - 1) # Choose random pixel + strip[j] = colors[c] # Set pixel to color for i in range(1, 5): - strip.brightness = i / 5.0 # Ramp up brightness + strip.brightness = i / 5.0 # Ramp up brightness time.sleep(wait) for i in range(5, 0, -1): - strip.brightness = i / 5.0 # Ramp down brightness - strip[j] = [0, 0, 0] # Set pixel to 'off' + strip.brightness = i / 5.0 # Ramp down brightness + strip[j] = [0, 0, 0] # Set pixel to 'off' time.sleep(wait) diff --git a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py index dfcf87ebc..2eac70bc9 100644 --- a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py +++ b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py @@ -1,7 +1,7 @@ -from digitalio import DigitalInOut, Direction import board import busio -import time +from digitalio import DigitalInOut, Direction + try: import struct except ImportError: @@ -26,7 +26,7 @@ while True: buffer.pop(0) if len(buffer) > 200: - buffer = [] # avoid an overrun if all bad data + buffer = [] # avoid an overrun if all bad data if len(buffer) < 32: continue @@ -66,4 +66,4 @@ while True: print("---------------------------------------") buffer = buffer[32:] - #print("Buffer ", buffer) + # print("Buffer ", buffer) diff --git a/Remote_Tree_Ornament/main.py b/Remote_Tree_Ornament/main.py index d1f37138f..54afbadab 100644 --- a/Remote_Tree_Ornament/main.py +++ b/Remote_Tree_Ornament/main.py @@ -77,7 +77,7 @@ while True: except adafruit_irremote.IRNECRepeatException: # unusual short code! print("NEC repeat!") command = last_command - except adafruit_irremote.IRDecodeException as e: # failed to decode + except adafruit_irremote.IRDecodeException as e: # failed to decode print("Failed to decode:", e) except MemoryError as e: print("Memory error: ", e) From 08cb52fbea7013f122c4ec2b9d29eae590f5d7b0 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 19:44:28 +0100 Subject: [PATCH 30/83] Fix formatting issues --- LED_Candles/LED_Candles.py | 26 ++++++++--------- LED_Masquerade_Masks/Audio_Reactive.py | 2 +- LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py | 15 +++++----- LED_Trampoline/LED_Trampoline.py | 3 +- .../Logans_Run_Hand_Jewel_LED.py | 8 +++--- NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py | 4 +-- .../NeoPixel_Jewel_10_Minute_Necklace.py | 28 +++++++++---------- NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py | 11 ++++---- NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py | 5 ---- NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py | 5 ---- NeoPixel_Tiara/NeoPixel_Tiara.py | 2 +- NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py | 16 +++++------ .../Sound_Reactive_NeoPixel_Peace_Pendant.py | 5 ++-- raver_bandolier/raver_bandolier.py | 6 ++-- 14 files changed, 63 insertions(+), 73 deletions(-) diff --git a/LED_Candles/LED_Candles.py b/LED_Candles/LED_Candles.py index 601d7fae2..dbd76bf9b 100644 --- a/LED_Candles/LED_Candles.py +++ b/LED_Candles/LED_Candles.py @@ -70,9 +70,9 @@ state = bright def set_color(index): index = max(min(index, index_max), index_bottom) - if (index >= index_min): + if index >= index_min: strip[0] = [index, int((index * 3) / 8), 0] - elif (index < index_min): + elif index < index_min: strip[0] = [index, int((index * 3.25) / 8), 0] @@ -83,13 +83,13 @@ while True: current_time = time.monotonic() # BRIGHT - if (state == bright): + if state == bright: flicker_msecs = random.randint( 0, down_max_msecs - down_min_msecs) + down_min_msecs flicker_start = current_time index_start = index_end - if ((index_start > index_bottom) and (random.randint(0, 100) < index_bottom_percent)): + if (index_start > index_bottom) and (random.randint(0, 100) < index_bottom_percent): index_end = random.randint( 0, index_start - index_bottom) + index_bottom else: @@ -98,7 +98,7 @@ while True: state = down # DIM - elif (state == dim): + elif state == dim: flicker_msecs = random.randint( 0, up_max_msecs - up_min_msecs) + up_min_msecs flicker_start = current_time @@ -107,25 +107,25 @@ while True: state = down # DIM_HOLD - elif (state == dim_hold): + elif state == dim_hold: # dividing flicker_msecs by 1000 to convert to milliseconds - if (current_time >= (flicker_start + (flicker_msecs / 1000))): - if (state == bright_hold): + if current_time >= (flicker_start + (flicker_msecs / 1000)): + if state == bright_hold: state = bright else: state = dim # DOWN - elif (state == down): + elif state == down: # dividing flicker_msecs by 1000 to convert to milliseconds - if (current_time < (flicker_start + (flicker_msecs / 1000))): + if current_time < (flicker_start + (flicker_msecs / 1000)): set_color(index_start + int(((index_end - index_start) * (((current_time - flicker_start) * 1.0) / flicker_msecs)))) else: set_color(index_end) - if (state == down): - if (random.randint(0, 100) < dim_hold_percent): + if state == down: + if random.randint(0, 100) < dim_hold_percent: flicker_start = current_time flicker_msecs = random.randint( 0, dim_hold_max_msecs - dim_hold_min_msecs) + dim_hold_min_msecs @@ -133,7 +133,7 @@ while True: else: state = dim else: - if (random.randint(0, 100) < bright_hold_percent): + if random.randint(0, 100) < bright_hold_percent: flicker_start = current_time flicker_msecs = random.randint( 0, bright_hold_max_msecs - bright_hold_min_msecs) + bright_hold_min_msecs diff --git a/LED_Masquerade_Masks/Audio_Reactive.py b/LED_Masquerade_Masks/Audio_Reactive.py index b0127d6df..ec72415e8 100644 --- a/LED_Masquerade_Masks/Audio_Reactive.py +++ b/LED_Masquerade_Masks/Audio_Reactive.py @@ -16,7 +16,7 @@ while True: signalMin = 65535 signalMax = 0 startTime = time.monotonic() - while ((time.monotonic() - startTime) < sampleWindow): + while (time.monotonic() - startTime) < sampleWindow: signal = mic.value if signal < signalMin: signalMin = signal diff --git a/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py b/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py index 08dbab1c3..186ad9988 100644 --- a/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py +++ b/LED_Masquerade_Masks/NeoPixel_Gemma_Mask.py @@ -1,10 +1,11 @@ -import board -import neopixel import time -numpix = 5 # Number of NeoPixels +import board +import neopixel + +numpix = 5 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected -hue = 0 # Starting color +hue = 0 # Starting color strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.4) @@ -13,9 +14,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return [0, 0, 0] - elif (pos < 85): + elif pos < 85: return [int(pos * 3), int(255 - (pos * 3)), 0] - elif (pos < 170): + elif pos < 170: pos -= 85 return [int(255 - pos * 3), 0, int(pos * 3)] else: @@ -27,5 +28,5 @@ while True: # Loop forever... for i in range(numpix): strip[i] = wheel((hue + i * 8) & 255) strip.write() - time.sleep(0.02) # 20 ms = ~50 fps + time.sleep(0.02) # 20 ms = ~50 fps hue = (hue + 1) & 255 # Increment hue and 'wrap around' at 255 diff --git a/LED_Trampoline/LED_Trampoline.py b/LED_Trampoline/LED_Trampoline.py index 6e757995c..42406147b 100644 --- a/LED_Trampoline/LED_Trampoline.py +++ b/LED_Trampoline/LED_Trampoline.py @@ -122,8 +122,7 @@ while True: if mode == 1 and not vibration_switch.value: print("Sparkle mode activate!") pixels.brightness = 1 - sparkle_color_index = ( - sparkle_color_index + 1) % len(sparkle_color_list) + sparkle_color_index = (sparkle_color_index + 1) % len(sparkle_color_list) sparkle_code(sparkle_color_list[sparkle_color_index]) if mode == 2 and not vibration_switch.value: print("Chase mode activate!") diff --git a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py index bc673c4fa..557facb15 100644 --- a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py +++ b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py @@ -19,14 +19,14 @@ strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) def lerp(x, x0, x1, y0, y1): # Clamp x within x0 and x1 bounds. - if (x > x1): + if x > x1: x = x1 - if (x < x0): + if x < x0: x = x0 # Calculate linear interpolation of y value. - return (y0 + (y1 - y0) * ((x - x0) / (x1 - x0))) + return y0 + (y1 - y0) * ((x - x0) / (x1 - x0)) # Set all pixels to the specified color. @@ -67,7 +67,7 @@ def animate_gradient_fill(start_r, start_g, start_b, end_r, end_g, end_b, durati # Main animation loop. delta = time.monotonic() - start - while (delta < duration_ms): + while delta < duration_ms: # Calculate how far along we are in the duration as a position 0...1.0 pos = delta / duration_ms # Get the gradient color and fill all the pixels with it. diff --git a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py index d4b6dadcc..c77af09f8 100644 --- a/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py +++ b/NeoPixel_Blinkendisc/NeoPixel_Blinkendisc.py @@ -7,7 +7,7 @@ import neopixel try: import urandom as random # for v1.0 API support -except: +except ImportError: import random num_leds = 24 # 24 LED NeoPixel ring @@ -60,7 +60,7 @@ while True: # Loop forever... last_vibration = t # Save last trigger time # Stretch out frames if nothing has happened in a couple of seconds: - if ((t - last_vibration) > cooldown_at): + if (t - last_vibration) > cooldown_at: frame_len += 0.001 # Add 1 ms if frame_len > max_frame_len: frame_len = min_frame_len diff --git a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py index 8fab2753b..d5412c51f 100644 --- a/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py +++ b/NeoPixel_Jewel_10_Minute_Necklace/NeoPixel_Jewel_10_Minute_Necklace.py @@ -24,14 +24,14 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) - else: - pos -= 170 - return (0, int(pos * 3), int(255 - pos * 3)) + + pos -= 170 + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): @@ -45,9 +45,9 @@ def rainbow_cycle(wait): def rainbow(wait): for j in range(255): - for i in range(len(pixels)): - idx = int(i + j) - pixels[i] = wheel(idx & 255) + for index in range(len(pixels)): + idx = int(index + j) + pixels[index] = wheel(idx & 255) pixels.write() time.sleep(wait) @@ -72,26 +72,26 @@ def rainbow_hold(wait): while True: - if (mode == 0): # rainbow hold + if mode == 0: # rainbow hold rainbow_hold(0.02) time.sleep(.5) - elif (mode == 1): # rainbow cycle slow + elif mode == 1: # rainbow cycle slow rainbow_cycle_slow(0.02) time.sleep(0.05) - elif (mode == 2): # rainbow cycle fast + elif mode == 2: # rainbow cycle fast rainbow_cycle(0.005) time.sleep(0.050) t = time.monotonic() - if ((t - prevtime) > 8): # Every 8 seconds... + if (t - prevtime) > 8: # Every 8 seconds... mode += 1 # Next mode - if (mode > 2): # End of modes? + if mode > 2: # End of modes? mode = 0 # Start modes over - if (rgb_idx > 2): # reset R-->G-->B rotation + if rgb_idx > 2: # reset R-->G-->B rotation rgb_idx = 0 color = rgb_colors[rgb_idx] # next color assignment diff --git a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py index 937b0b40a..b5fc792f0 100644 --- a/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py +++ b/NeoPixel_Punk_Collar/NeoPixel_Punk_Collar.py @@ -24,14 +24,14 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) - else: - pos -= 170 - return (0, int(pos * 3), int(255 - pos * 3)) + + pos -= 170 + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): @@ -47,6 +47,7 @@ def rainbow(wait): for i in range(len(strip)): idx = int(i + j) strip[i] = wheel(idx & 255) + time.sleep(wait) while True: diff --git a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py index 556a22a46..c230e4330 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Figure_Eight.py @@ -3,11 +3,6 @@ import time import board import neopixel -try: - import urandom as random -except ImportError: - import random - numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) diff --git a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py index fdc293d57..82d757573 100644 --- a/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py +++ b/NeoPixel_Ring_Bangle_Bracelet/Sine_Wave.py @@ -3,11 +3,6 @@ import time import board import neopixel -try: - import urandom as random # for v1.0 API support -except ImportError: - import random - numpix = 64 # Number of NeoPixels pixpin = board.D1 # Pin where NeoPixels are connected strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.15) diff --git a/NeoPixel_Tiara/NeoPixel_Tiara.py b/NeoPixel_Tiara/NeoPixel_Tiara.py index 93108c9a8..f0fa5f014 100644 --- a/NeoPixel_Tiara/NeoPixel_Tiara.py +++ b/NeoPixel_Tiara/NeoPixel_Tiara.py @@ -19,7 +19,7 @@ colors = [ def flash_random(wait, howmany): - for k in range(howmany): + for _ in range(howmany): c = random.randint(0, len(colors) - 1) # Choose random color index j = random.randint(0, numpix - 1) # Choose random pixel diff --git a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py index c902c7e88..bc208c360 100644 --- a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py +++ b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py @@ -36,27 +36,27 @@ while True: gcolor = 0 bcolor = 0 - if (showcolor == 0): # Garden PINK + if showcolor == 0: # Garden PINK rcolor = 242 gcolor = 90 bcolor = 255 - elif (showcolor == 1): # Pixie GOLD + elif showcolor == 1: # Pixie GOLD rcolor = 255 gcolor = 222 bcolor = 30 - elif (showcolor == 2): # Alchemy BLUE + elif showcolor == 2: # Alchemy BLUE rcolor = 50 gcolor = 255 bcolor = 255 - elif (showcolor == 3): # Animal ORANGE + elif showcolor == 3: # Animal ORANGE rcolor = 255 gcolor = 100 bcolor = 0 - elif (showcolor == 4): # Tinker GREEN + elif showcolor == 4: # Tinker GREEN rcolor = 0 gcolor = 255 bcolor = 40 @@ -84,17 +84,17 @@ while True: newstate = button.value # Check if state changed from high to low (button press). - if (newstate and not oldstate): + if newstate and not oldstate: # Short delay to debounce button. time.sleep(0.020) # Check if button is still low after debounce. newstate = button.value - if (newstate == False): + if not newstate: showcolor += 1 - if (showcolor > 4): + if showcolor > 4: showcolor = 0 # Set the last button state to the old state. diff --git a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py index 1a8aefc90..7c9e933e5 100644 --- a/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py +++ b/Sound_Reactive_NeoPixel_Peace_Pendant/Sound_Reactive_NeoPixel_Peace_Pendant.py @@ -37,9 +37,8 @@ def wheel(pos): elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) - else: - pos -= 170 - return (0, int(pos * 3), int(255 - pos * 3)) + pos -= 170 + return (0, int(pos * 3), int(255 - pos * 3)) def remap_range(value, leftMin, leftMax, rightMin, rightMax): diff --git a/raver_bandolier/raver_bandolier.py b/raver_bandolier/raver_bandolier.py index ef47032d6..c3aa47d9e 100644 --- a/raver_bandolier/raver_bandolier.py +++ b/raver_bandolier/raver_bandolier.py @@ -29,9 +29,9 @@ def wheel(pos): elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) - else: - pos -= 170 - return (0, int(pos * 3), int(255 - pos * 3)) + + pos -= 170 + return (0, int(pos * 3), int(255 - pos * 3)) def rainbow_cycle(wait): From df581b6d7fd489f65fe4076d49fad8a9556c183b Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 19:59:12 +0100 Subject: [PATCH 31/83] Fix Flake8 issues --- Introducing_Gemma_M0/Gemma_HIDkeyboard.py | 2 +- Introducing_Gemma_M0/Gemma_NeoPixel.py | 4 ++-- Introducing_Gemma_M0/Gemma_UART.py | 4 ++-- .../Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py | 19 +++++++------------ .../Larson_Scanner_Shades.py | 8 ++++---- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/Introducing_Gemma_M0/Gemma_HIDkeyboard.py b/Introducing_Gemma_M0/Gemma_HIDkeyboard.py index 0bfa30d42..52aa9cabc 100644 --- a/Introducing_Gemma_M0/Gemma_HIDkeyboard.py +++ b/Introducing_Gemma_M0/Gemma_HIDkeyboard.py @@ -51,7 +51,7 @@ while True: pass # wait for it to be released! # type the keycode or string k = buttonkeys[i] # get the corresp. keycode/str - if type(k) is str: + if isinstance(k, str): layout.write(k) else: kbd.press(controlkey, k) # press... diff --git a/Introducing_Gemma_M0/Gemma_NeoPixel.py b/Introducing_Gemma_M0/Gemma_NeoPixel.py index 6f61a7fd6..863abb2fc 100644 --- a/Introducing_Gemma_M0/Gemma_NeoPixel.py +++ b/Introducing_Gemma_M0/Gemma_NeoPixel.py @@ -16,9 +16,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: diff --git a/Introducing_Gemma_M0/Gemma_UART.py b/Introducing_Gemma_M0/Gemma_UART.py index f33d45666..b5112051a 100644 --- a/Introducing_Gemma_M0/Gemma_UART.py +++ b/Introducing_Gemma_M0/Gemma_UART.py @@ -1,8 +1,8 @@ # Gemma IO demo - USB/Serial echo import busio -from board import * -from digitalio import * +from board import D0, D2, D13 +from digitalio import DigitalInOut, Direction led = DigitalInOut(D13) led.direction = Direction.OUTPUT diff --git a/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py b/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py index 03626c933..6bd075ec0 100644 --- a/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py +++ b/Kaleidoscope_Eyes_NeoPixel_LED_Goggles/Kaleidoscope_Eyes_NeoPixel_LED_Goggles.py @@ -27,19 +27,14 @@ prevtime = 0 pixels = neopixel.NeoPixel(pixpin, numpix, brightness=.3, auto_write=False) - -def setup(): - prevtime = time.monotonic() - - -setup() +prevtime = time.monotonic() while True: i = 0 t = 0 # Random sparks - just one LED on at a time! - if (mode == 0): + if mode == 0: i = random.randint(0, (numpix - 1)) pixels[i] = color pixels.write() @@ -47,12 +42,12 @@ while True: pixels[i] = (0, 0, 0) # Spinny wheels (8 LEDs on at a time) - elif (mode == 1): + elif mode == 1: for i in range(0, numpix): c = 0 # 4 pixels on... - if (((offset + i) & 7) < 2): + if ((offset + i) & 7) < 2: c = color pixels[i] = c # First eye @@ -64,12 +59,12 @@ while True: t = time.monotonic() - if ((t - prevtime) > 8): # Every 8 seconds... + if (t - prevtime) > 8: # Every 8 seconds... mode += 1 # Next mode - if (mode > 1): # End of modes? + if mode > 1: # End of modes? mode = 0 # Start modes over - if (rgb_idx > 2): # reset R-->G-->B rotation + if rgb_idx > 2: # reset R-->G-->B rotation rgb_idx = 0 color = rgb_colors[rgb_idx] # next color assignment diff --git a/Larson_Scanner_Shades/Larson_Scanner_Shades.py b/Larson_Scanner_Shades/Larson_Scanner_Shades.py index e75881e8d..d55638c5d 100644 --- a/Larson_Scanner_Shades/Larson_Scanner_Shades.py +++ b/Larson_Scanner_Shades/Larson_Scanner_Shades.py @@ -15,7 +15,7 @@ while True: strip[pos] = ([255, 48, 0]) # brightest strip[pos + 1] = ([128, 0, 0]) # Medium red - if ((pos + 2) < numpix): + if (pos + 2) < numpix: # Dark red, do not exceed number of pixels strip[pos + 2] = ([16, 0, 0]) @@ -26,14 +26,14 @@ while True: # it's easier to erase it all and draw a new one next time. for j in range(-2, 2): strip[pos + j] = (0, 0, 0) - if ((pos + 2) < numpix): + if (pos + 2) < numpix: strip[pos + 2] = (0, 0, 0) # Bounce off ends of strip pos += direction - if (pos < 0): + if pos < 0: pos = 1 direction = -direction - elif (pos >= (numpix - 1)): + elif pos >= (numpix - 1): pos = numpix - 2 direction = -direction From 5f208c804dd608dd5bbc024884059f1af27a8778 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 20:03:40 +0100 Subject: [PATCH 32/83] Fix Flake8 issues --- .../CircuitPlaygroundExpress_DigitalIO.py | 2 +- Introducing_Gemma_M0/Gemma_DotStar.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py index 35b256bc7..c9feb639e 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_DigitalIO.py @@ -13,7 +13,7 @@ button.direction = Direction.INPUT button.pull = Pull.DOWN while True: - if button.value == True: # button is pushed + if button.value: # button is pushed led.value = True else: led.value = False diff --git a/Introducing_Gemma_M0/Gemma_DotStar.py b/Introducing_Gemma_M0/Gemma_DotStar.py index d8b847412..c1448e99b 100644 --- a/Introducing_Gemma_M0/Gemma_DotStar.py +++ b/Introducing_Gemma_M0/Gemma_DotStar.py @@ -14,9 +14,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: From 27843a8a27ea4439fb537e10a2f3acb48189bb30 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 20:35:56 +0100 Subject: [PATCH 33/83] Fix Flake8 issues --- .../3D_Printed_LED_Microphone_Flag.py | 52 ++++++++----------- .../3D_Printed_NeoPixel_Ring_Hair_Dress.py | 36 ++++++------- EPROM_Emulator/debouncer.py | 2 +- .../Gemma_Firewalker_Lite_Sneakers.py | 30 +++++------ .../CircuitPlaygroundExpress_SoundMeter.py | 6 +-- 5 files changed, 60 insertions(+), 66 deletions(-) diff --git a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py index f6b3ab4c2..c735c9c9f 100644 --- a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py +++ b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py @@ -57,9 +57,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: @@ -81,18 +81,13 @@ def remapRange(value, leftMin, leftMax, rightMin, rightMax): def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): - originalrange = 0 - newrange = 0 - zerorefcurval = 0 - normalizedcurval = 0 - rangedvalue = 0 invflag = 0 # condition curve parameter # limit range - if (curve > 10): + if curve > 10: curve = 10 - if (curve < -10): + if curve < -10: curve = -10 # - invert and scale - @@ -103,16 +98,16 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): curve = pow(10, curve) # Check for out of range inputValues - if (inputvalue < originalmin): + if inputvalue < originalmin: inputvalue = originalmin - if (inputvalue > originalmax): + if inputvalue > originalmax: inputvalue = originalmax # Zero Refference the values originalrange = originalmax - originalmin - if (newend > newbegin): + if newend > newbegin: newrange = newend - newbegin else: newrange = newbegin - newend @@ -124,27 +119,25 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): # Check for originalMin > originalMax # -the math for all other cases # i.e. negative numbers seems to work out fine - if (originalmin > originalmax): - return (0) + if originalmin > originalmax: + return 0 - if (invflag == 0): + if invflag == 0: rangedvalue = (pow(normalizedcurval, curve) * newrange) + newbegin else: # invert the ranges rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange) - return (rangedvalue) + return rangedvalue def drawLine(fromhere, to): - fromheretemp = 0 - - if (fromhere > to): + if fromhere > to: fromheretemp = fromhere fromhere = to to = fromheretemp - for i in range(fromhere, to): - strip[i] = (0, 0, 0) + for index in range(fromhere, to): + strip[index] = (0, 0, 0) while True: @@ -157,16 +150,16 @@ while True: y = 0 # collect data for length of sample window (in seconds) - while ((time.monotonic() - time_start) < sample_window): + while (time.monotonic() - time_start) < sample_window: # convert to arduino 10-bit [1024] fromhere 16-bit [65536] sample = mic_pin.value / 64 - if (sample < 1024): # toss out spurious readings + if sample < 1024: # toss out spurious readings - if (sample > signalmax): + if sample > signalmax: signalmax = sample # save just the max levels - elif (sample < signalmin): + elif sample < signalmin: signalmin = sample # save just the min levels peaktopeak = signalmax - signalmin # max - min = peak-peak amplitude @@ -178,11 +171,11 @@ while True: # Scale the input logarithmically instead of linearly c = fscale(input_floor, input_ceiling, (n_pixels - 1), 0, peaktopeak, 2) - if (c < peak): + if c < peak: peak = c # keep dot on top dothangcount = 0 # make the dot hang before falling - if (c <= n_pixels): # fill partial column with off pixels + if c <= n_pixels: # fill partial column with off pixels drawLine(n_pixels, n_pixels - int(c)) # Set the peak dot to match the rainbow gradient @@ -191,8 +184,9 @@ while True: strip.write() # Frame based peak dot animation - if (dothangcount > peak_hang): # Peak pause length - if (++dotcount >= peak_fall): # Fall rate + if dothangcount > peak_hang: # Peak pause length + dotcount += 1 + if dotcount >= peak_fall: # Fall rate peak += 1 dotcount = 0 else: diff --git a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py index 62142e369..c5cd5a459 100644 --- a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py +++ b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py @@ -162,7 +162,7 @@ def nextspectrumcolor(): global spectrum_part, color_idx, curr_color_granularity, color # spectral wipe from green to red - if (spectrum_part == 2): + if spectrum_part == 2: color = (color_idx, 0, 255 - color_idx) color_idx += curr_color_granularity if (color_idx > 255): @@ -170,18 +170,18 @@ def nextspectrumcolor(): color_idx = 0 # spectral wipe from blue to green - elif (spectrum_part == 1): + elif spectrum_part == 1: color = (0, 255 - color_idx, color_idx) color_idx += curr_color_granularity - if (color_idx > 255): + if color_idx > 255: spectrum_part = 2 color_idx = 0 # spectral wipe from red to blue - elif (spectrum_part == 0): + elif spectrum_part == 0: color = (255 - color_idx, color_idx, 0) color_idx += curr_color_granularity - if (color_idx > 255): + if color_idx > 255: spectrum_part = 1 color_idx = 0 @@ -206,7 +206,7 @@ def nextrandomcolor(): def nextcolor(): # save some RAM for more animation actions - if (curr_color_gen & COL_RANDOM): + if curr_color_gen & COL_RANDOM: nextrandomcolor() else: nextspectrumcolor() @@ -228,7 +228,7 @@ setup() while True: # Loop forever... # do we need to load the next action? - if ((time.monotonic() - action_timer) > curr_action_duration): + if (time.monotonic() - action_timer) > curr_action_duration: curr_action_duration = theactionlist[curr_action_idx][action_duration] curr_action = theactionlist[curr_action_idx][action_and_color_gen] & 0x3F curr_action_step_duration = theactionlist[curr_action_idx][action_step_duration] @@ -242,16 +242,16 @@ while True: # Loop forever... action_timer = time.monotonic() # do we need to change to the next color? - if ((time.monotonic() - color_timer) > curr_color_interval): + if (time.monotonic() - color_timer) > curr_color_interval: nextcolor() color_timer = time.monotonic() # do we need to step up the current action? - if ((time.monotonic() - action_step_timer) > curr_action_step_duration): + if (time.monotonic() - action_step_timer) > curr_action_step_duration: - if (curr_action): + if curr_action: - if (curr_action == ACT_NOP): + if curr_action == ACT_NOP: # rather trivial even tho this will be repeated as long as the # NOP continues - i could have prevented it from repeating # unnecessarily, but that would mean more code and less @@ -259,14 +259,14 @@ while True: # Loop forever... for i in range(0, numpix): strip[i] = (0, 0, 0) - elif (curr_action == ACT_SIMPLE_RING): + elif curr_action == ACT_SIMPLE_RING: # even more trivial - just set the new color, if there is one for i in range(0, numpix): strip[i] = color - elif (curr_action == (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW)): + elif curr_action == (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW): # spin the ring clockwise or anti clockwise - if (curr_action == ACT_CYCLING_RING_ACLK): + if curr_action == ACT_CYCLING_RING_ACLK: idx += 1 else: idx -= 1 @@ -277,17 +277,17 @@ while True: # Loop forever... # set the new color, if there is one strip[idx] = color - elif (curr_action == ACT_WHEEL_ACLK or ACT_WHEEL_CLKW): + elif curr_action == ACT_WHEEL_ACLK or ACT_WHEEL_CLKW: # switch on / off the appropriate pixels according to # the current offset for idx in range(0, numpix): - if (((offset + idx) & 7) < 2): + if ((offset + idx) & 7) < 2: strip[idx] = color else: strip[idx] = (0, 0, 0) # advance the offset and thus, spin the wheel - if (curr_action == ACT_WHEEL_CLKW): + if curr_action == ACT_WHEEL_CLKW: offset += 1 else: offset -= 1 @@ -295,7 +295,7 @@ while True: # Loop forever... # prevent overflows or underflows offset %= numpix - elif (curr_action == ACT_SPARKLING_RING): + elif curr_action == ACT_SPARKLING_RING: # switch current pixel off strip[idx] = (0, 0, 0) # pick a new pixel diff --git a/EPROM_Emulator/debouncer.py b/EPROM_Emulator/debouncer.py index 2f5b60322..1513020da 100644 --- a/EPROM_Emulator/debouncer.py +++ b/EPROM_Emulator/debouncer.py @@ -46,7 +46,7 @@ class Debouncer(object): self.state = 0x00 self.pin = digitalio.DigitalInOut(pin) self.pin.direction = digitalio.Direction.INPUT - if mode != None: + if mode is not None: self.pin.pull = mode if self.pin.value: self.__set_state(Debouncer.DEBOUNCED_STATE | diff --git a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py index e4871c5c9..14fbe57cc 100644 --- a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py +++ b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py @@ -92,7 +92,7 @@ def h2rgb(hue): hue %= 90 h = hue_table[hue >> 1] - if (hue & 1): + if hue & 1: ret = h & 15 else: ret = (h >> 4) @@ -116,15 +116,15 @@ def wave_setup(): def vibration_detector(): - while (True): + while True: if not pin.value: - return (True) + return True -while (True): +while True: # wait for vibration sensor to trigger - if (ramping_up == False): + if ramping_up == False: ramping_up = vibration_detector() wave_setup() @@ -137,7 +137,7 @@ while (True): brightness = int(((brightness * 7) + 207) / 8) count += 1 - if (count == (circumference + num_leds + 5)): + if count == (circumference + num_leds + 5): ramping_up = False count = 0 @@ -147,7 +147,7 @@ while (True): wave[w][center] += wave[w][speed] # Hue not currently changing? - if (wave[w][hue] == wave[w][hue_target]): + if wave[w][hue] == wave[w][hue_target]: # There's a tiny random chance of picking a new hue... if (not random.randint(frames_per_second * 4, 255)): @@ -158,13 +158,13 @@ while (True): # This wave's hue is currently shifting... else: - if (wave[w][hue] < wave[w][hue_target]): + if wave[w][hue] < wave[w][hue_target]: wave[w][hue] += 1 # Move up or else: wave[w][hue] -= 1 # down as needed # Reached destination? - if (wave[w][hue] == wave[w][hue_target]): + if wave[w][hue] == wave[w][hue_target]: wave[w][hue] = 90 + wave[w][hue] % 90 # Clamp to 90-180 range wave[w][hue_target] = wave[w][hue] # Copy to target @@ -200,7 +200,7 @@ while (True): # that 'wraps around' the ends of the strip as # necessary...it's a contiguous ring, and waves # can move smoothly across the gap. - if (d2 < d1): + if d2 < d1: d1 = d2 # d1 is pixel-to-wave-center distance # d2 distance, relative to wave width, is then @@ -208,14 +208,14 @@ while (True): # pixel (basic linear y=mx+b stuff). # Is distance within wave's influence? # d2 is opposite; distance to wave's end - if (d1 < wave[w][width]): + if d1 < wave[w][width]: d2 = wave[w][width] - d1 y = int(brightness * d2 / wave[w][width]) # 0 to 200 # y is a brightness scale value -- # proportional to, but not exactly equal # to, the resulting RGB value. - if (y < 128): # Fade black to RGB color + if y < 128: # Fade black to RGB color # In HSV colorspace, this would be # tweaking 'value' n = int(y * 2 + 1) # 1-256 @@ -235,11 +235,11 @@ while (True): # r,g,b are 16-bit types that accumulate brightness # from all waves that affect this pixel; may exceed # 255. Now clip to 0-255 range: - if (r > 255): + if r > 255: r = 255 - if (g > 255): + if g > 255: g = 255 - if (b > 255): + if b > 255: b = 255 # Store resulting RGB value and we're done with diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py index bdf45a254..09297d704 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py @@ -65,11 +65,11 @@ def normalized_rms(values): def mean(values): - return (sum(values) / len(values)) + return sum(values) / len(values) -def volume_color(i): - return (200, i * (255 // NUM_PIXELS), 0) +def volume_color(volume): + return 200, volume * (255 // NUM_PIXELS), 0 # Main program From 5a23e531c8a265bb4816fdd7395fad531761119c Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 20:44:03 +0100 Subject: [PATCH 34/83] Fix Flake8 issues --- .../CircuitPlaygroundExpress_SoundMeter.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py index 09297d704..a5fa58466 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py @@ -53,7 +53,9 @@ def constrain(value, floor, ceiling): def log_scale(input_value, input_min, input_max, output_min, output_max): normalized_input_value = (input_value - input_min) / \ (input_max - input_min) - return output_min + math.pow(normalized_input_value, SCALE_EXPONENT) * (output_max - output_min) + return output_min + \ + math.pow(normalized_input_value, SCALE_EXPONENT) \ + * (output_max - output_min) # Remove DC bias before computing RMS. @@ -61,7 +63,9 @@ def log_scale(input_value, input_min, input_max, output_min, output_max): def normalized_rms(values): minbuf = int(mean(values)) - return math.sqrt(sum(float(sample - minbuf) * (sample - minbuf) for sample in values) / len(values)) + samples_sum = sum(float(sample - minbuf) * (sample - minbuf) for sample in values) + + return math.sqrt(samples_sum / len(values)) def mean(values): From 852e9affb0008445bcf0654d4432f40cbf3fc96e Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 20:56:51 +0100 Subject: [PATCH 35/83] Fix Flake8 issues --- .../gemma_m0_clockwork_goggles.py | 6 ++--- .../Gemma_Firewalker_Lite_Sneakers.py | 27 +++++++++---------- Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py | 4 +-- Gemma_LightTouch/gemma_lighttouch.py | 4 +-- .../CircuitPlaygroundExpress_HIDKeyboard.py | 2 +- 5 files changed, 20 insertions(+), 23 deletions(-) diff --git a/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py b/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py index 3e9357ead..c0a7c3b55 100644 --- a/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py +++ b/GemmaM0_Clockwork_Goggles/gemma_m0_clockwork_goggles.py @@ -31,11 +31,11 @@ def cog(pos): if (pos < 8) or (pos > 250): # return (120, 0, 0, 0) #first color, red: for RGBW NeoPixels return (120, 0, 0) # first color, red: for RGB NeoPixels - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) # return (125, 35, 0, 0) #second color, brass: for RGBW NeoPixels - return (125, 35, 0) # second color, brass: for RGB NeoPixels - elif (pos < 170): + # return (125, 35, 0) # second color, brass: for RGB NeoPixels + elif pos < 170: pos -= 85 # return (int(255 - pos*3), 0, int(pos*3), 0)#: for RGBW NeoPixels return (int(255 - pos * 3), 0, int(pos * 3)) # : for RGB NeoPixels diff --git a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py index 14fbe57cc..0fa0c2b1e 100644 --- a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py +++ b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py @@ -85,19 +85,16 @@ gammas = [ 215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255] -def h2rgb(hue): - # return value - ret = 0 +def h2rgb(colour_hue): + colour_hue %= 90 + h = hue_table[colour_hue >> 1] - hue %= 90 - h = hue_table[hue >> 1] - - if hue & 1: + if colour_hue & 1: ret = h & 15 else: ret = (h >> 4) - return (ret * 17) + return ret * 17 def wave_setup(): @@ -108,11 +105,11 @@ def wave_setup(): [0, 7, 30, 0, 0, 0, 0, 0]] # assign random starting colors to waves - for w in range(n_waves): - wave[w][hue] = wave[w][hue_target] = 90 + random.randint(0, 90) - wave[w][red] = h2rgb(wave[w][hue] - 30) - wave[w][green] = h2rgb(wave[w][hue]) - wave[w][blue] = h2rgb(wave[w][hue] + 30) + for wave_index in range(n_waves): + wave[wave_index][hue] = wave[wave_index][hue_target] = 90 + random.randint(0, 90) + wave[wave_index][red] = h2rgb(wave[wave_index][hue] - 30) + wave[wave_index][green] = h2rgb(wave[wave_index][hue]) + wave[wave_index][blue] = h2rgb(wave[wave_index][hue] + 30) def vibration_detector(): @@ -124,7 +121,7 @@ def vibration_detector(): while True: # wait for vibration sensor to trigger - if ramping_up == False: + if not ramping_up: ramping_up = vibration_detector() wave_setup() @@ -150,7 +147,7 @@ while True: if wave[w][hue] == wave[w][hue_target]: # There's a tiny random chance of picking a new hue... - if (not random.randint(frames_per_second * 4, 255)): + if not random.randint(frames_per_second * 4, 255): # Within 1/3 color wheel wave[w][hue_target] = random.randint( wave[w][hue] - 30, wave[w][hue] + 30) diff --git a/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py b/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py index b7c3d0f46..ef048b94f 100644 --- a/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py +++ b/Gemma_Hoop_Earrings/Gemma_Hoop_Earrings.py @@ -21,9 +21,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return [0, 0, 0] - elif (pos < 85): + elif pos < 85: return [int(pos * 3), int(255 - (pos * 3)), 0] - elif (pos < 170): + elif pos < 170: pos -= 85 return [int(255 - pos * 3), 0, int(pos * 3)] else: diff --git a/Gemma_LightTouch/gemma_lighttouch.py b/Gemma_LightTouch/gemma_lighttouch.py index d92d753b1..edb899a72 100644 --- a/Gemma_LightTouch/gemma_lighttouch.py +++ b/Gemma_LightTouch/gemma_lighttouch.py @@ -34,10 +34,10 @@ def cycle_sequence(seq): def rainbow_cycle(seq): """Rainbow cycle generator""" - rainbow = cycle_sequence(seq) + rainbow_sequence = cycle_sequence(seq) while True: # pylint: disable=stop-iteration-return - led[0] = (wheel(next(rainbow))) + led[0] = (wheel(next(rainbow_sequence))) yield diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py index 1f8afd474..5d4273d86 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_HIDKeyboard.py @@ -54,7 +54,7 @@ while True: pass # wait for it to be released! # type the keycode or string k = buttonkeys[i] # get the corresp. keycode/str - if type(k) is str: + if isinstance(k, str): layout.write(k) else: kbd.press(controlkey, k) # press... From 33a13cbb3bc81309ee3b2b1799f30af4faf84e03 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 21:06:02 +0100 Subject: [PATCH 36/83] Fix Flake8 issues --- Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py index fa3ea8b1b..44dc0c1c2 100644 --- a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py +++ b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py @@ -49,10 +49,10 @@ class Grain: def __init__(self): """Initialize grain position and velocity.""" - x = 0 - y = 0 - vx = 0 - vy = 0 + self.x = 0 + self.y = 0 + self.vx = 0 + self.vy = 0 grains = [Grain() for _ in range(N_GRAINS)] From 1cde6aa8894e9f6c5f81ce2beb508a2046aadee6 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 21:37:40 +0100 Subject: [PATCH 37/83] Fix Flake8 issues --- .../Arcade_Button_Control_Box.py | 2 +- CircuitPy_OTP/main.py | 7 +++-- CircuitPython_Painter/main.py | 4 +-- EPROM_Emulator/directory_node.py | 24 +++++++++------ Labo_Piano_Light_FX/code.py | 2 +- Minecraft_Gesture_Controller/main.py | 30 +++++++++---------- Pi_Hole_Ad_Blocker/stats.py | 5 ++-- 7 files changed, 41 insertions(+), 33 deletions(-) diff --git a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py index a0d2e53f5..7a7e33e80 100644 --- a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py +++ b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py @@ -3,7 +3,7 @@ import time import digitalio from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode -from board import * +from board import D12, D11, D10, D9, D6, D5, A0, A1, A2, A3, A4, A5 # A simple neat keyboard demo in circuitpython diff --git a/CircuitPy_OTP/main.py b/CircuitPy_OTP/main.py index 1b556ed15..6d84a2e23 100644 --- a/CircuitPy_OTP/main.py +++ b/CircuitPy_OTP/main.py @@ -8,7 +8,8 @@ import ntptime import ubinascii import uhashlib -totp = [("Discord ", 'JBSWY3DPEHPK3PXP'), # https://github.com/pyotp/pyotp exmple +# https://github.com/pyotp/pyotp example +totp = [("Discord ", 'JBSWY3DPEHPK3PXP'), ("Gmail ", 'abcdefghijklmnopqrstuvwxyz234567'), ("Accounts", 'asfdkwefoaiwejfa323nfjkl')] ssid = 'my_wifi_ssid' @@ -164,7 +165,7 @@ t = None while not t: try: t = ntptime.time() - except: + except Exception: pass time.sleep(0.1) @@ -195,7 +196,7 @@ while ALWAYS_ON or (countdown > 0): print(name + " OTP output: ", otp) # serial debugging output oled.text(name + ": " + str(otp), 0, y) # display name & OTP on OLED y += 10 # Go to next line on OLED - # We'll display a little bar that 'counts down' how many seconds you have left + # Display a little bar that 'counts down' how many seconds you have left oled.framebuf.line(0, 31, 128 - (unix_time % 30) * 4, 31, True) oled.show() # We'll update every 1/4 second, we can hash very fast so its no biggie! diff --git a/CircuitPython_Painter/main.py b/CircuitPython_Painter/main.py index fd6634c71..c604803db 100644 --- a/CircuitPython_Painter/main.py +++ b/CircuitPython_Painter/main.py @@ -96,9 +96,9 @@ try: except OSError as e: if e.args[0] == 28: - halt("OS Error 28", 0.25) + raise OSError("OS Error 28 0.25") else: - halt("OS Error ", 0.5) + raise OSError("OS Error 0.5") except BMPError as e: print("Failed to parse BMP: " + e.args[0]) diff --git a/EPROM_Emulator/directory_node.py b/EPROM_Emulator/directory_node.py index 6664c67c5..73b1f0f29 100644 --- a/EPROM_Emulator/directory_node.py +++ b/EPROM_Emulator/directory_node.py @@ -96,7 +96,8 @@ class DirectoryNode(object): def __get_files(self): """Return a list of the files in this directory. - If this is not the top directory on the SD card, a ".." entry is the first element. + If this is not the top directory on the SD card, a + ".." entry is the first element. Any directories have a slash appended to their name.""" if len(self.files) == 0: self.files = os.listdir(self.__path()) @@ -112,7 +113,9 @@ class DirectoryNode(object): if self.top_offset != self.old_top_offset: self.__get_files() self.display.fill(0) - for i in range(self.top_offset, min(self.top_offset + 4, self.__number_of_files())): + min_offset = min(self.top_offset + 4, self.__number_of_files()) + + for i in range(self.top_offset, min_offset): self.display.text(self.files[i], 10, (i - self.top_offset) * 8) self.display.show() self.old_top_offset = self.top_offset @@ -121,10 +124,12 @@ class DirectoryNode(object): """Update the selected file lighlight if required.""" if self.selected_offset != self.old_selected_offset: if self.old_selected_offset > -1: - self.display.text( - ">", 0, (self.old_selected_offset - self.top_offset) * 8, 0) - self.display.text( - ">", 0, (self.selected_offset - self.top_offset) * 8, 1) + old_offset = (self.old_selected_offset - self.top_offset) * 8 + + self.display.text(">", 0, old_offset, 0) + + new_offset = (self.selected_offset - self.top_offset) * 8 + self.display.text(">", 0, new_offset, 1) self.display.show() self.old_selected_offset = self.selected_offset @@ -153,8 +158,8 @@ class DirectoryNode(object): self.__update_selection() def down(self): - """Move down in the file list if possible, adjusting the selected file indicator - and scrolling the display as required.""" + """Move down in the file list if possible, adjusting the selected file + indicator and scrolling the display as required.""" if self.selected_offset < self.__number_of_files() - 1: self.selected_offset += 1 if self.selected_offset == self.top_offset + 4: @@ -174,7 +179,8 @@ class DirectoryNode(object): def click(self): """Handle a selection and return the new current directory. - If the selected file is the parent, i.e. "..", return to the parent directory. + If the selected file is the parent, i.e. "..", return to the parent + directory. If the selected file is a directory, go into it.""" if self.selected_filename == "..": if self.parent: diff --git a/Labo_Piano_Light_FX/code.py b/Labo_Piano_Light_FX/code.py index ea46e97b4..1fe0d066e 100644 --- a/Labo_Piano_Light_FX/code.py +++ b/Labo_Piano_Light_FX/code.py @@ -68,6 +68,6 @@ while True: vlvl = remapRangeSafe(lvl, 0, 255, wheelStart, wheelEnd) for i in range(0, len(strip)): strip[i] = wheel(vlvl) - # Set strip brightness based on audio level + # Set strip brightness based oncode audio level strip.brightness = float(remapRangeSafe(lvl, 50, 255, 0, maxbrt)) / 255.0 strip.show() diff --git a/Minecraft_Gesture_Controller/main.py b/Minecraft_Gesture_Controller/main.py index f2b8e75e2..48b3832ab 100644 --- a/Minecraft_Gesture_Controller/main.py +++ b/Minecraft_Gesture_Controller/main.py @@ -75,8 +75,8 @@ def Move(upDown_axis, isBackward): # If you are touching A4, walk backwards, else walk forwards if isBackward: print("backwards") # Debugging - if (axis_new > 1.2): # walk threshold - if (axis_new > 2.5): # run threshold + if axis_new > 1.2: # walk threshold + if axis_new > 2.5: # run threshold kbd.press(Keycode.LEFT_CONTROL, Keycode.S) time.sleep(0.1) kbd.release_all() @@ -85,8 +85,8 @@ def Move(upDown_axis, isBackward): time.sleep(0.1) kbd.release_all() else: - if (axis_new > 1.2): # walk threshold - if (axis_new > 2.5): # run threshold + if axis_new > 1.2: # walk threshold + if axis_new > 2.5: # run threshold kbd.press(Keycode.LEFT_CONTROL) time.sleep(0.1) kbd.release_all() @@ -96,12 +96,12 @@ def Move(upDown_axis, isBackward): kbd.release_all() -def Turn(upDown_axis, frontBack_axis, leftRight_axis, lookUp): +def Turn(upDown_axis, leftRight_axis, lookUp): leftRight_adj = int(leftRight_axis) # currently z_axis upDown_adj = int(upDown_axis) # currently y_axis leftRight_new = Map(leftRight_adj, -3, 3, -100, 100) - if (lookUp and abs(upDown_adj) < 1.2): + if lookUp and abs(upDown_adj) < 1.2: upDown_new = Map(upDown_adj, -1, 1, -100, 100) else: upDown_new = 0 @@ -113,7 +113,7 @@ def Turn(upDown_axis, frontBack_axis, leftRight_axis, lookUp): def Jump(upDown_axis): upDown = abs(upDown_axis) - if (upDown > 3): + if upDown > 3: kbd.press(Keycode.SPACE, Keycode.W) kbd.release_all() @@ -121,7 +121,7 @@ def Jump(upDown_axis): def Give(upDown_axis, frontBack_axis): frontBack_new = abs(frontBack_axis) if abs(upDown_axis) < 1: - if (frontBack_new > 2): + if frontBack_new > 2: print("give") mouse.click(Mouse.RIGHT_BUTTON) mouse.release_all() @@ -163,7 +163,7 @@ def readAxes(): ########################### while True: # Read accelerometer values (in G). Returns a 3-tuple of x, y, x axis - x, y, z = readAxes() + pos_x, pos_y, pos_z = readAxes() # Read finger pads and act accordingly if touch_a1.value: @@ -175,14 +175,14 @@ while True: if touch_a3.value: ESC() - isBackward = touch_a4.value - lookUp = touch_a4.value + is_backward = touch_a4.value + look_up = touch_a4.value # Run through the motions! .. literally :) - Move(y, isBackward) - Turn(y, x, z, lookUp) - Jump(y) - Give(y, x) + Move(pos_y, is_backward) + Turn(pos_y, pos_z, look_up) + Jump(pos_y) + Give(pos_y, pos_x) # Small delay to keep things responsive but give time for interrupt processing. time.sleep(0.01) diff --git a/Pi_Hole_Ad_Blocker/stats.py b/Pi_Hole_Ad_Blocker/stats.py index 11a2aec94..2db7c4db0 100644 --- a/Pi_Hole_Ad_Blocker/stats.py +++ b/Pi_Hole_Ad_Blocker/stats.py @@ -71,7 +71,8 @@ while True: # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) - # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load + # Shell scripts for system monitoring from here : + # https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" IP = subprocess.check_output(cmd, shell=True) cmd = "hostname" @@ -90,7 +91,7 @@ while True: DNSQUERIES = data['dns_queries_today'] ADSBLOCKED = data['ads_blocked_today'] CLIENTS = data['unique_clients'] - except: + except KeyError: time.sleep(1) continue From ef9cc08b5a679810ea170dba0c818efb933464de Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 16:57:38 -0400 Subject: [PATCH 38/83] Fixes Flake 8 Issues Animated NeoPixel Glow Fur Scarf --- .../Animated_NeoPixel_Glow_Fur_Scarf.py | 51 +++++++++---------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py index c15318bf8..932860742 100644 --- a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py +++ b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py @@ -3,15 +3,15 @@ import board import neopixel from digitalio import DigitalInOut, Direction, Pull -led_pin = board.D1 # which pin your pixels are connected to -num_leds = 78 # how many LEDs you have -brightness = 1.0 # 0-1, higher number is brighter -saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color -steps = 0.01 # how wide the bands of color are. -offset = 0 # cummulative steps -fadeup = True # start with fading up - increase steps until offset reaches 1 -index = 8 # midway color selection -blend = True # color blending between palette indices +led_pin = board.D1 # which pin your pixels are connected to +num_leds = 78 # how many LEDs you have +brightness = 1.0 # 0-1, higher number is brighter +saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color +steps = 0.01 # how wide the bands of color are. +offset = 0 # cummulative steps +fadeup = True # start with fading up - increase steps until offset reaches 1 +index = 8 # midway color selection +blend = True # color blending between palette indices # initialize list with all pixels off palette = [0] * num_leds @@ -68,9 +68,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): - return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + if pos < 85: + return (int(pos * 3), int(255 - (pos*3)), 0) + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: @@ -91,11 +91,10 @@ def remapRange(value, leftMin, leftMax, rightMin, rightMax): def shortkeypress(color_palette): color_palette += 1 - if (color_palette > 6): + if color_palette > 6: color_palette = 1 - return (color_palette) - + return color_palette while True: @@ -103,38 +102,38 @@ while True: currkeystate = button.value # button press, move to next pattern - if ((prevkeystate == False) and (currkeystate == True)): + if (prevkeystate != True) and currkeystate: ledmode = shortkeypress(ledmode) # save button press state prevkeystate = currkeystate # Fire Colors [ HEAT ] - if (ledmode == 1): + if ledmode == 1: palette = heat_colors # Forest - elif (ledmode == 2): + elif ledmode == 2: palette = forest # Ocean - elif (ledmode == 3): + elif ledmode == 3: palette = ocean # Purple Lovers - elif (ledmode == 4): + elif ledmode == 4: palette = purple # All the colors! - elif (ledmode == 5): + elif ledmode == 5: palette = rainbow # Rainbow stripes - elif (ledmode == 6): + elif ledmode == 6: palette = rainbow_stripe # All the colors except the greens, washed out - elif (ledmode == 7): + elif ledmode == 7: palette = washed_out for i in range(num_leds): @@ -143,11 +142,11 @@ while True: strip[i] = color.pack() strip.show() - if (fadeup): + if fadeup: offset += steps - if (offset >= 1): + if offset >= 1: fadeup = False else: offset -= steps - if (offset <= 0): + if offset <= 0: fadeup = True From e209493de0aa5098e45049412a13a39b2c80a4a6 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 21:59:35 +0100 Subject: [PATCH 39/83] Fix PEP8 compliance --- EPROM_Emulator/debouncer.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/EPROM_Emulator/debouncer.py b/EPROM_Emulator/debouncer.py index 1513020da..c18a2905a 100644 --- a/EPROM_Emulator/debouncer.py +++ b/EPROM_Emulator/debouncer.py @@ -40,8 +40,10 @@ class Debouncer(object): def __init__(self, pin, mode=None, interval=0.010): """Make am instance. :param int pin: the pin (from board) to debounce - :param int mode: digitalio.Pull.UP or .DOWN (default is no pull up/down) - :param int interval: bounce threshold in seconds (default is 0.010, i.e. 10 milliseconds) + :param int mode: digitalio.Pull.UP or .DOWN (default is no + pull up/down) + :param int interval: bounce threshold in seconds (default is 0.010, + i.e. 10 milliseconds) """ self.state = 0x00 self.pin = digitalio.DigitalInOut(pin) @@ -70,7 +72,8 @@ class Debouncer(object): return (self.state & bits) != 0 def update(self): - """Update the debouncer state. Must be called before using any of the properties below""" + """Update the debouncer state. Must be called before using any of + the properties below""" self.__unset_state(Debouncer.CHANGED_STATE) current_state = self.pin.value if current_state != self.__get_state(Debouncer.UNSTABLE_STATE): @@ -78,7 +81,8 @@ class Debouncer(object): self.__toggle_state(Debouncer.UNSTABLE_STATE) else: if time.monotonic() - self.previous_time >= self.interval: - if current_state != self.__get_state(Debouncer.DEBOUNCED_STATE): + debounced_state = self.__get_state(Debouncer.DEBOUNCED_STATE) + if current_state != debounced_state: self.previous_time = time.monotonic() self.__toggle_state(Debouncer.DEBOUNCED_STATE) self.__set_state(Debouncer.CHANGED_STATE) @@ -90,10 +94,14 @@ class Debouncer(object): @property def rose(self): - """Return whether the debounced input went from low to high at the most recent update.""" - return self.__get_state(self.DEBOUNCED_STATE) and self.__get_state(self.CHANGED_STATE) + """Return whether the debounced input went from low to high at + the most recent update.""" + return self.__get_state(self.DEBOUNCED_STATE) \ + and self.__get_state(self.CHANGED_STATE) @property def fell(self): - """Return whether the debounced input went from high to low at the most recent update.""" - return (not self.__get_state(self.DEBOUNCED_STATE)) and self.__get_state(self.CHANGED_STATE) + """Return whether the debounced input went from high to low at + the most recent update.""" + return (not self.__get_state(self.DEBOUNCED_STATE)) \ + and self.__get_state(self.CHANGED_STATE) From 0da6d60d5b95f7b449ba0dde1f4856b1d1d046d5 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:00:29 +0100 Subject: [PATCH 40/83] Fix PEP8 compliance --- EPROM_Emulator/emulator.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/EPROM_Emulator/emulator.py b/EPROM_Emulator/emulator.py index 0bdf37a75..056e3f75b 100644 --- a/EPROM_Emulator/emulator.py +++ b/EPROM_Emulator/emulator.py @@ -104,7 +104,8 @@ class Emulator(object): self.address_clock_pin.value = CLOCK_INACTIVE def __output_on_port_a(self, data_byte): - """A hack to get around the limitation of the 23017 library to use 8-bit ports""" + """A hack to get around the limitation of the 23017 + library to use 8-bit ports""" self.mcp.gpio = (self.mcp.gpio & 0xFF00) | (data_byte & 0x00FF) def enter_program_mode(self): @@ -113,7 +114,8 @@ class Emulator(object): self.led_pin.value = LED_OFF def enter_emulate_mode(self): - """Enter emulate mode, giving control of the emulator ram to the host.""" + """Enter emulate mode, giving control of the emulator + ram to the host.""" self.mode_pin.value = EMULATE_USE self.led_pin.value = LED_ON From c7086527c4127c929d840ec2434459fb42fb8be7 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:12:24 +0100 Subject: [PATCH 41/83] Fix PEP8 compliance --- .../CircuitPython_NeoPixel_RGBW.py | 4 +- CircuitPython_Essentials/PWM_Test_Script.py | 2 +- .../CircuitPython_NeoPixel_RGBW.py | 3 +- CircuitPython_Quick_Starts/PWM_Test_Script.py | 2 +- .../DataLogger.py | 6 ++- Giant_Mechanical_Keyboard/code.py | 14 +++--- Minecraft_Gesture_Controller/main.py | 46 ++++++++----------- Pi_Hole_Ad_Blocker/stats.py | 12 +++-- 8 files changed, 45 insertions(+), 44 deletions(-) diff --git a/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py b/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py index 8347e62f7..289efca21 100644 --- a/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py +++ b/CircuitPython_Essentials/CircuitPython_NeoPixel_RGBW.py @@ -1,6 +1,7 @@ # CircuitPython demo - NeoPixel RGBW import time + import board import neopixel @@ -8,7 +9,8 @@ pixel_pin = board.A1 num_pixels = 8 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, - brightness=0.3, auto_write=False, pixel_order=(1, 0, 2, 3)) + brightness=0.3, auto_write=False, + pixel_order=(1, 0, 2, 3)) def wheel(pos): diff --git a/CircuitPython_Essentials/PWM_Test_Script.py b/CircuitPython_Essentials/PWM_Test_Script.py index 91cb90107..d1a9f47c6 100644 --- a/CircuitPython_Essentials/PWM_Test_Script.py +++ b/CircuitPython_Essentials/PWM_Test_Script.py @@ -9,5 +9,5 @@ for pin_name in dir(board): print("PWM on:", pin_name) # Prints the valid, PWM-capable pins! except ValueError: # This is the error returned when the pin is invalid. print("No PWM on:", pin_name) # Prints the invalid pins. - except RuntimeError: # This is the error returned when there is a timer conflict. + except RuntimeError: # Timer conflict error. print("Timers in use:", pin_name) # Prints the timer conflict pins. diff --git a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py index ad88e5ef9..289efca21 100644 --- a/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py +++ b/CircuitPython_Quick_Starts/CircuitPython_NeoPixel_RGBW.py @@ -9,7 +9,8 @@ pixel_pin = board.A1 num_pixels = 8 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, - brightness=0.3, auto_write=False, pixel_order=(1, 0, 2, 3)) + brightness=0.3, auto_write=False, + pixel_order=(1, 0, 2, 3)) def wheel(pos): diff --git a/CircuitPython_Quick_Starts/PWM_Test_Script.py b/CircuitPython_Quick_Starts/PWM_Test_Script.py index 91cb90107..d1a9f47c6 100644 --- a/CircuitPython_Quick_Starts/PWM_Test_Script.py +++ b/CircuitPython_Quick_Starts/PWM_Test_Script.py @@ -9,5 +9,5 @@ for pin_name in dir(board): print("PWM on:", pin_name) # Prints the valid, PWM-capable pins! except ValueError: # This is the error returned when the pin is invalid. print("No PWM on:", pin_name) # Prints the invalid pins. - except RuntimeError: # This is the error returned when there is a timer conflict. + except RuntimeError: # Timer conflict error. print("Timers in use:", pin_name) # Prints the timer conflict pins. diff --git a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py index 2d3bd5c7d..cb0ea5949 100644 --- a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py +++ b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py @@ -42,8 +42,10 @@ while True: print("Humidity:", humidity) print("VBat voltage: {:.2f}".format(battery_voltage)) print() - sdc.write("{}, {}, {}, {:.2f}\n".format(int(time_stamp), temperature, - humidity, battery_voltage)) + sdc.write("{}, {}, {}, {:.2f}\n".format( + int(time_stamp), temperature, + humidity, battery_voltage) + ) time.sleep(3) except OSError: pass diff --git a/Giant_Mechanical_Keyboard/code.py b/Giant_Mechanical_Keyboard/code.py index 5a9b89ec5..d09d5e8e8 100644 --- a/Giant_Mechanical_Keyboard/code.py +++ b/Giant_Mechanical_Keyboard/code.py @@ -59,16 +59,16 @@ print("Waiting for button presses") def pressbutton(i): - l = leds[i] # find the switch LED + switch_led = leds[i] # find the switch LED k = buttonkeys[i] # get the corresp. keycode/str - l.value = True # turn on LED + switch_led.value = True # turn on LED kbd.press(k) # send keycode def releasebutton(i): - l = leds[i] # find the switch LED + switch_led = leds[i] # find the switch LED k = buttonkeys[i] # get the corresp. keycode/str - l.value = False # turn on LED + switch_led.value = False # turn on LED kbd.release(k) # send keycode @@ -98,15 +98,15 @@ while True: # check each button for button in buttons: i = buttons.index(button) - if button.value == False: # button is pressed? + if button.value is False: # button is pressed? buttonspressed[i] = True # save pressed button # was button not pressed last time? - if buttonspressedlast[i] == False: + if buttonspressedlast[i] is False: print("Pressed #%d" % i) pressbutton(i) else: buttonspressed[i] = False # button was not pressed - if buttonspressedlast[i] == True: # was button pressed last time? + if buttonspressedlast[i] is True: # was button pressed last time? print("Released #%d" % i) releasebutton(i) lightneopixels() diff --git a/Minecraft_Gesture_Controller/main.py b/Minecraft_Gesture_Controller/main.py index 48b3832ab..2882d0099 100644 --- a/Minecraft_Gesture_Controller/main.py +++ b/Minecraft_Gesture_Controller/main.py @@ -1,4 +1,3 @@ -############################################### # Minecraft Gesture Controller # # Written by @@ -7,11 +6,9 @@ # Super awesome thanks to: # Richard Albritton, Tony DiCola, John Parker # All the awesome people who wrote the libraries -################################################ -########################## -## Libraries ## -########################## +# Libraries + import time @@ -27,9 +24,7 @@ from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode from adafruit_hid.mouse import Mouse -####################### -# CPX Setup # -####################### +# CPX Setup touch_a1 = touchio.TouchIn(board.A1) touch_a1.threshold = 2000 touch_a2 = touchio.TouchIn(board.A2) @@ -39,9 +34,8 @@ touch_a3.threshold = 2000 touch_a4 = touchio.TouchIn(board.A4) touch_a4.threshold = 2000 -############################ -# Keyboard & Mouse Setup # -############################ +# Keyboard & Mouse Setup + # The keyboard object! kbd = Keyboard() # we're americans :) @@ -49,25 +43,23 @@ layout = KeyboardLayoutUS(kbd) # The mouse object! mouse = Mouse() -####################### -# Accelerometer Setup # -####################### +# Accelerometer Setup + # Initialize Accelerometer i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=25) -# Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G). +# Set range of accelerometer +# (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G). lis3dh.range = adafruit_lis3dh.RANGE_8_G -########################### -## Controller Functions ## -########################### +# Controller Functions # A helper to 'remap' an input range to an output range - - def Map(x, in_min, in_max, out_min, out_max): - return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) + return int( + (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min + ) def Move(upDown_axis, isBackward): @@ -158,9 +150,7 @@ def readAxes(): return (x / 9.806, y / 9.806, z / 9.806) # 9.806 m/s^2 per G -########################### -## Main Function ## -########################### +# Main Function while True: # Read accelerometer values (in G). Returns a 3-tuple of x, y, x axis pos_x, pos_y, pos_z = readAxes() @@ -184,11 +174,13 @@ while True: Jump(pos_y) Give(pos_y, pos_x) - # Small delay to keep things responsive but give time for interrupt processing. + # Small delay to keep things responsive but + # give time for interrupt processing. time.sleep(0.01) - ## Debugging Ahead!! ## - # Use the following 2 lines to figure out which axis is upDown, frontBack, or LeftRight + # Debugging Ahead!! + # Use the following 2 lines to figure out which + # axis is upDown, frontBack, or LeftRight # and also for debugging! # print('x = {}G, y = {}G, z = {}G'.format(x, y, z)) # time.sleep(0.3) diff --git a/Pi_Hole_Ad_Blocker/stats.py b/Pi_Hole_Ad_Blocker/stats.py index 2db7c4db0..9076bc2da 100644 --- a/Pi_Hole_Ad_Blocker/stats.py +++ b/Pi_Hole_Ad_Blocker/stats.py @@ -61,7 +61,8 @@ draw.rectangle((0, 0, width, height), outline=0, fill=0) padding = -2 top = padding bottom = height - padding -# Move left to right keeping track of the current x position for drawing shapes. +# Move left to right keeping track of the current x position +# for drawing shapes. x = 0 # Load nice silkscreen font @@ -77,11 +78,14 @@ while True: IP = subprocess.check_output(cmd, shell=True) cmd = "hostname" HOST = subprocess.check_output(cmd, shell=True) - cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'" + cmd = "top -bn1 | grep load | awk " \ + "'{printf \"CPU Load: %.2f\", $(NF-2)}'" CPU = subprocess.check_output(cmd, shell=True) - cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'" + cmd = "free -m | awk 'NR==2{printf " \ + "\"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'" MemUsage = subprocess.check_output(cmd, shell=True) - cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'" + cmd = "df -h | awk '$NF==\"/\"{printf " \ + "\"Disk: %d/%dGB %s\", $3,$2,$5}'" Disk = subprocess.check_output(cmd, shell=True) # Pi Hole data! From a13d13226c3b2a486ded006c86e3be8878870891 Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:13:57 -0400 Subject: [PATCH 42/83] Fixes Flake 8 Breath_Tester --- Breath_Tester/Breath_Tester.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Breath_Tester/Breath_Tester.py b/Breath_Tester/Breath_Tester.py index d0855a0af..8f33e82f7 100644 --- a/Breath_Tester/Breath_Tester.py +++ b/Breath_Tester/Breath_Tester.py @@ -25,7 +25,7 @@ def warmup_message(): print() print("Warming Up [%d seconds]..." % warmup_time) - while (warmup_counter <= 20): + while warmup_counter <= 20: print('.', end='') time.sleep(1) warmup_counter += 1 @@ -44,7 +44,7 @@ def get_breath_reading(): input(" *** Press a key when ready. *** ") print() - while (breath_counter <= breath_time): + while breath_counter <= breath_time: co2eq, tvoc = sgp30.iaq_measure() breath_saves[breath_counter] = tvoc print(tvoc, ', ', end='') @@ -54,7 +54,7 @@ def get_breath_reading(): breath_saves = sorted(breath_saves) highest_breath_result = breath_saves[breath_counter - 1] - return (highest_breath_result) + return highest_breath_result # show the highest reading recorded From c9ad539ab919a65202e4a0642ae9c1d6e2d1c77c Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:23:44 +0100 Subject: [PATCH 43/83] Fix PEP8 compliance --- .../CPX_Left_Rotation_State_Machine.py | 11 +++- .../CPX_Spoka_Motion_Lamp.py | 12 +++- Introducing_Gemma_M0/Default Files/main.py | 60 +++++++++---------- Introducing_Trinket_M0/Trinket_UART.py | 2 +- LED_Trampoline/LED_Trampoline.py | 5 +- .../HSV_FancyLED_NeoPixel_Dailer.py | 5 +- NeoPixel_Dialer/RGB_NeoPixel_Dialer.py | 5 +- 7 files changed, 58 insertions(+), 42 deletions(-) diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py index 58f021d8d..3b79994a7 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py @@ -7,11 +7,18 @@ from adafruit_circuitplayground.express import cpx def upright(x, y, z): - return abs(x) < accel_threshold and abs(y) < accel_threshold and abs(9.8 - z) < accel_threshold + x_up = abs(x) < accel_threshold + y_up = abs(x) < accel_threshold + z_up = abs(9.8 - z) < accel_threshold + return x_up and y_up and z_up def left_side(x, y, z): - return abs(9.8 - x) < accel_threshold and abs(y) < accel_threshold and abs(z) < accel_threshold + x_side = abs(9.8 - x) < accel_threshold + y_side = abs(y) < accel_threshold + z_side = abs(z) < accel_threshold + + return x_side and y_side and z_side state = None diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py index 2684e3c69..00ee9791f 100755 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Spoka_Motion_Lamp.py @@ -19,15 +19,21 @@ def wheel(pos): # pylint: disable=redefined-outer-name def upright(x, y, z): - return abs(x) < accel_threshold and abs(y) < accel_threshold and abs(9.8 - z) < accel_threshold + return abs(x) < accel_threshold \ + and abs(y) < accel_threshold \ + and abs(9.8 - z) < accel_threshold def right_side(x, y, z): - return abs(-9.8 - x) < accel_threshold and abs(y) < accel_threshold and abs(z) < accel_threshold + return abs(-9.8 - x) < accel_threshold \ + and abs(y) < accel_threshold \ + and abs(z) < accel_threshold def left_side(x, y, z): - return abs(9.8 - x) < accel_threshold and abs(y) < accel_threshold and abs(z) < accel_threshold + return abs(9.8 - x) < accel_threshold \ + and abs(y) < accel_threshold \ + and abs(z) < accel_threshold # pylint: enable=redefined-outer-name diff --git a/Introducing_Gemma_M0/Default Files/main.py b/Introducing_Gemma_M0/Default Files/main.py index 9c729ba00..ee5f27f79 100644 --- a/Introducing_Gemma_M0/Default Files/main.py +++ b/Introducing_Gemma_M0/Default Files/main.py @@ -1,14 +1,12 @@ # Gemma IO demo # Welcome to CircuitPython 2.0.0 :) -import board -import time -from digitalio import DigitalInOut, Direction, Pull -from analogio import AnalogIn, AnalogOut -from touchio import TouchIn -from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode import adafruit_dotstar as dotstar +import board +from adafruit_hid.keyboard import Keyboard +from analogio import AnalogIn, AnalogOut +from digitalio import DigitalInOut, Direction +from touchio import TouchIn # One pixel connected internally! dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) @@ -29,50 +27,52 @@ touch2 = TouchIn(board.A2) # Used if we do HID output, see below kbd = Keyboard() -######################### HELPERS ############################## + +# Helpers # Helper to convert analog input to voltage def getVoltage(pin): return (pin.value * 3.3) / 65536 + # Helper to give us a nice color swirl def wheel(pos): # Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. - if (pos < 0): + if pos < 0: return [0, 0, 0] - if (pos > 255): + if pos > 255: return [0, 0, 0] - if (pos < 85): - return [int(pos * 3), int(255 - (pos*3)), 0] - elif (pos < 170): + if pos < 85: + return [int(pos * 3), int(255 - (pos * 3)), 0] + elif pos < 170: pos -= 85 - return [int(255 - pos*3), 0, int(pos*3)] + return [int(255 - pos * 3), 0, int(pos * 3)] else: pos -= 170 - return [0, int(pos*3), int(255 - pos*3)] + return [0, int(pos * 3), int(255 - pos * 3)] -######################### MAIN LOOP ############################## + +# Main Loop i = 0 while True: - # spin internal LED around! - dot[0] = wheel(i) - dot.show() + # spin internal LED around! + dot[0] = wheel(i) + dot.show() - # set analog output to 0-3.3V (0-65535 in increments) - aout.value = i * 256 + # set analog output to 0-3.3V (0-65535 in increments) + aout.value = i * 256 - # Read analog voltage on A1 - print("A1: %0.2f" % getVoltage(analog1in)) + # Read analog voltage on A1 + print("A1: %0.2f" % getVoltage(analog1in)) - # use A2 as capacitive touch to turn on internal LED - if touch2.value: + # use A2 as capacitive touch to turn on internal LED + if touch2.value: print("A2 touched!") # optional! uncomment below & save to have it sent a keypress - #kbd.press(Keycode.A) - #kbd.release_all() - led.value = touch2.value + # kbd.press(Keycode.A) + # kbd.release_all() + led.value = touch2.value - - i = (i+1) % 256 # run from 0 to 255 + i = (i + 1) % 256 # run from 0 to 255 diff --git a/Introducing_Trinket_M0/Trinket_UART.py b/Introducing_Trinket_M0/Trinket_UART.py index 3f1cf3d82..442631755 100644 --- a/Introducing_Trinket_M0/Trinket_UART.py +++ b/Introducing_Trinket_M0/Trinket_UART.py @@ -14,7 +14,7 @@ while True: data = uart.read(32) # read up to 32 bytes # print(data) # this is a bytearray type - if data != None: + if data is not None: led.value = True # convert bytearray to string diff --git a/LED_Trampoline/LED_Trampoline.py b/LED_Trampoline/LED_Trampoline.py index 42406147b..cf78455ea 100644 --- a/LED_Trampoline/LED_Trampoline.py +++ b/LED_Trampoline/LED_Trampoline.py @@ -9,7 +9,7 @@ pixel_pin = board.D10 # The pin the NeoPixels are connected to button_switch_pin = board.D9 # Pin button is attached to vibration_switch_pin = board.D7 # Pin vibration switch is attached to. pixel_count = 40 # Number of pixels in your strip -chase_color_duration = 3 # Time in seconds each color lasts in the color chase mode +chase_color_duration = 3 # Seconds each color lasts in the color chase mode pixels = neopixel.NeoPixel(pixel_pin, pixel_count, brightness=.4, auto_write=False) @@ -122,7 +122,8 @@ while True: if mode == 1 and not vibration_switch.value: print("Sparkle mode activate!") pixels.brightness = 1 - sparkle_color_index = (sparkle_color_index + 1) % len(sparkle_color_list) + sparkle_color_index = (sparkle_color_index + 1) \ + % len(sparkle_color_list) sparkle_code(sparkle_color_list[sparkle_color_index]) if mode == 2 and not vibration_switch.value: print("Chase mode activate!") diff --git a/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py b/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py index 5578c2e54..8378b7fa9 100644 --- a/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py +++ b/NeoPixel_Dialer/HSV_FancyLED_NeoPixel_Dailer.py @@ -16,8 +16,9 @@ lcd_d4 = digitalio.DigitalInOut(board.D9) lcd_columns = 16 lcd_rows = 2 -lcd = adafruit_character_lcd.Character_LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, - lcd_d7, lcd_columns, lcd_rows) +lcd = adafruit_character_lcd.Character_LCD( + lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows +) potH = AnalogIn(board.A0) # pot for hue potS = AnalogIn(board.A1) # pot for saturation diff --git a/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py b/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py index 99b85f864..9f27de529 100644 --- a/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py +++ b/NeoPixel_Dialer/RGB_NeoPixel_Dialer.py @@ -16,8 +16,9 @@ lcd_d4 = digitalio.DigitalInOut(board.D9) lcd_columns = 16 lcd_rows = 2 -lcd = adafruit_character_lcd.Character_LCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, - lcd_d7, lcd_columns, lcd_rows) +lcd = adafruit_character_lcd.Character_LCD( + lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows +) potR = AnalogIn(board.A0) # pot pin for R val potG = AnalogIn(board.A1) # pot pin for G val From 4f8a3b17764679b2edbfc6c57099f1be3ccf7b56 Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:25:54 -0400 Subject: [PATCH 44/83] Fixes Flake 8 issue CircuitPython_Painter --- CircuitPython_Painter/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CircuitPython_Painter/main.py b/CircuitPython_Painter/main.py index c604803db..0d8e7a37c 100644 --- a/CircuitPython_Painter/main.py +++ b/CircuitPython_Painter/main.py @@ -75,7 +75,7 @@ try: databuf = bytearray(bmpWidth * bmpHeight * 4) for row in range(bmpHeight): # For each scanline... - if (flip): # Bitmap is stored bottom-to-top order (normal BMP) + if flip: # Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize else: # Bitmap is stored top-to-bottom pos = bmpImageoffset + row * rowSize From c8a61175a2c76e06337448863f4c81990797a2ca Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:27:17 +0100 Subject: [PATCH 45/83] Fix PEP8 compliance --- Introducing_Gemma_M0/Gemma_UART.py | 2 +- Larson_Scanner_Shades/Larson_Scanner_Shades.py | 2 +- NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py | 2 +- PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py | 4 +++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Introducing_Gemma_M0/Gemma_UART.py b/Introducing_Gemma_M0/Gemma_UART.py index b5112051a..64be6153a 100644 --- a/Introducing_Gemma_M0/Gemma_UART.py +++ b/Introducing_Gemma_M0/Gemma_UART.py @@ -13,7 +13,7 @@ while True: data = uart.read(32) # read up to 32 bytes # print(data) # this is a bytearray type - if data != None: + if data is not None: led.value = True # convert bytearray to string diff --git a/Larson_Scanner_Shades/Larson_Scanner_Shades.py b/Larson_Scanner_Shades/Larson_Scanner_Shades.py index d55638c5d..b579cc84a 100644 --- a/Larson_Scanner_Shades/Larson_Scanner_Shades.py +++ b/Larson_Scanner_Shades/Larson_Scanner_Shades.py @@ -4,7 +4,7 @@ import board import neopixel numpix = 22 # Number of NeoPixels -pixpin = board.D1 # Pin where NeoPixels are connected Gemma M0 = D1 | Trinket M0 = D4 +pixpin = board.D1 # NeoPixels pin. For Gemma M0 = D1, Trinket M0 = D4 strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) pos = 0 # position direction = 1 # direction of "eye" diff --git a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py index bc208c360..cf704130b 100644 --- a/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py +++ b/NeoPixie_Dust_Bag/NeoPixie_Dust_Bag.py @@ -13,7 +13,7 @@ except ImportError: import random neo_pin = board.D0 # DIGITAL IO pin for NeoPixel OUTPUT from GEMMA -touch_pin = board.D2 # DIGITAL IO pin for momentary touch sensor INPUT to GEMMA +touch_pin = board.D2 # DIGITAL IO pin for momentary touch sensor to GEMMA pixel_count = 30 # Number of NeoPixels connected to GEMMA delay_sec = .010 # delay between blinks, smaller numbers are faster delay_mult = 8 # Randomization multiplier, delay speed of the effect diff --git a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py index 2eac70bc9..51ed7d164 100644 --- a/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py +++ b/PMS5003_Air_Quality_Sensor/PMS5003_CircuitPython/main.py @@ -41,7 +41,9 @@ while True: frame = struct.unpack(">HHHHHHHHHHHHHH", bytes(buffer[4:])) - pm10_standard, pm25_standard, pm100_standard, pm10_env, pm25_env, pm100_env, particles_03um, particles_05um, particles_10um, particles_25um, particles_50um, particles_100um, skip, checksum = frame + pm10_standard, pm25_standard, pm100_standard, pm10_env, \ + pm25_env, pm100_env, particles_03um, particles_05um, particles_10um, \ + particles_25um, particles_50um, particles_100um, skip, checksum = frame check = sum(buffer[0:30]) From e207c2e5dff5ed161ffb892be955a628637def66 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:28:29 +0100 Subject: [PATCH 46/83] Fix PEP8 compliance --- Introducing_Gemma_M0/dht22.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Introducing_Gemma_M0/dht22.py b/Introducing_Gemma_M0/dht22.py index 8d727b31e..d25b585d7 100644 --- a/Introducing_Gemma_M0/dht22.py +++ b/Introducing_Gemma_M0/dht22.py @@ -10,7 +10,7 @@ while True: temperature = dht.temperature humidity = dht.humidity # Print what we got to the REPL - print("Temp: {:.1f} *C \t Humidity: {}% ".format(temperature, humidity)) + print("Temp: {:.1f} *C \t Humidity: {}%".format(temperature, humidity)) except RuntimeError as e: # Reading doesn't always work! Just print error and we'll try again print("Reading from DHT failure: ", e.args) From 4ae30df65955628561c464b96559f85f97d88362 Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:31:02 -0400 Subject: [PATCH 47/83] Fixes Flake 8 Issue Close_Encounter_Hat --- Close_Encounters_Hat/Close_Encounters_Hat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Close_Encounters_Hat/Close_Encounters_Hat.py b/Close_Encounters_Hat/Close_Encounters_Hat.py index 3945c0ab4..d57c20b1d 100644 --- a/Close_Encounters_Hat/Close_Encounters_Hat.py +++ b/Close_Encounters_Hat/Close_Encounters_Hat.py @@ -90,5 +90,5 @@ while True: # turn lights and audio on when dark # (less than 50% light on analog pin) - if (photocell.value > darkness_min): + if photocell.value > darkness_min: alien() # close Encounters Loop From 7c92f04bb0992b140eb0cc2e6a510889440c203f Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:35:38 -0400 Subject: [PATCH 48/83] Fixes Flake 8 issues Cyberpunk_Spikes --- Cyberpunk_Spikes/Cyberpunk_Spikes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cyberpunk_Spikes/Cyberpunk_Spikes.py b/Cyberpunk_Spikes/Cyberpunk_Spikes.py index 5431af710..d0afcdfa7 100644 --- a/Cyberpunk_Spikes/Cyberpunk_Spikes.py +++ b/Cyberpunk_Spikes/Cyberpunk_Spikes.py @@ -60,9 +60,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: From a01003f643d50bd31046b4bc9b8f971bfb420017 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:35:42 +0100 Subject: [PATCH 49/83] Fix PEP8 compliance --- LED_Candles/LED_Candles.py | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/LED_Candles/LED_Candles.py b/LED_Candles/LED_Candles.py index dbd76bf9b..e678cd1c6 100644 --- a/LED_Candles/LED_Candles.py +++ b/LED_Candles/LED_Candles.py @@ -10,7 +10,7 @@ except ImportError: import random wick_pin = board.D0 # The data-in pin of the NeoPixel -unconnected_pin = board.A0 # Any unconnected pin, to try to generate a random seed +unconnected_pin = board.A0 # Any unconnected pin, to generate random seed # The LED can be in only one of these states at any given time bright = 0 @@ -28,25 +28,25 @@ index_bottom = 128 index_min = 192 index_max = 255 # Maximum red value -# Decreasing brightness will take place over a number of milliseconds in this range +# Decreasing brightness will take place over a number of milliseconds down_min_msecs = 20 down_max_msecs = 250 -# Increasing brightness will take place over a number of milliseconds in this range +# Increasing brightness will take place over a number of milliseconds up_min_msecs = 20 up_max_msecs = 250 # Percent chance the color will hold unchanged after brightening bright_hold_percent = 20 -# When holding after brightening, hold for a number of milliseconds in this range +# When holding after brightening, hold for a number of milliseconds bright_hold_min_msecs = 0 bright_hold_max_msecs = 100 # Percent chance the color will hold unchanged after dimming dim_hold_percent = 5 -# When holding after dimming, hold for a number of milliseconds in this range +# When holding after dimming, hold for a number of milliseconds dim_hold_min_msecs = 0 dim_hold_max_msecs = 50 @@ -89,7 +89,9 @@ while True: flicker_start = current_time index_start = index_end - if (index_start > index_bottom) and (random.randint(0, 100) < index_bottom_percent): + is_index_in_range = index_start > index_bottom + is_random_in_range = random.randint(0, 100) < index_bottom_percent + if is_index_in_range and is_random_in_range: index_end = random.randint( 0, index_start - index_bottom) + index_bottom else: @@ -119,24 +121,32 @@ while True: elif state == down: # dividing flicker_msecs by 1000 to convert to milliseconds if current_time < (flicker_start + (flicker_msecs / 1000)): - set_color(index_start + int(((index_end - index_start) * - (((current_time - flicker_start) * 1.0) / flicker_msecs)))) + index_range = index_end - index_start + time_range = (current_time - flicker_start) * 1.0 + + set_color(index_start + int( + (index_range * (time_range / flicker_msecs)))) else: set_color(index_end) if state == down: if random.randint(0, 100) < dim_hold_percent: flicker_start = current_time + + dim_max = dim_hold_max_msecs - dim_hold_min_msecs flicker_msecs = random.randint( - 0, dim_hold_max_msecs - dim_hold_min_msecs) + dim_hold_min_msecs + 0, dim_max + ) + dim_hold_min_msecs state = dim_hold else: state = dim else: if random.randint(0, 100) < bright_hold_percent: flicker_start = current_time + + max_flicker = bright_hold_max_msecs - bright_hold_min_msecs flicker_msecs = random.randint( - 0, bright_hold_max_msecs - bright_hold_min_msecs) + bright_hold_min_msecs + 0, max_flicker) + bright_hold_min_msecs state = bright_hold else: state = bright From 84936e2355e7f9d098031f0bd12499a14cd011a5 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:39:22 +0100 Subject: [PATCH 50/83] Fix PEP8 compliance --- Annoy_O_Matic/main.py | 88 +++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/Annoy_O_Matic/main.py b/Annoy_O_Matic/main.py index 7914fd5e7..4c1089f2b 100644 --- a/Annoy_O_Matic/main.py +++ b/Annoy_O_Matic/main.py @@ -75,45 +75,45 @@ def annoy_ringtone(ringtone, tempo, interval): sixteenth_note = whole_note / 16 # set up note values - A2 = 110 - As2 = 117 # 's' stands for sharp: A#2 - Bb2 = 117 - B2 = 123 + # A2 = 110 + # As2 = 117 # 's' stands for sharp: A#2 + # Bb2 = 117 + # B2 = 123 - C3 = 131 - Cs3 = 139 - Db3 = 139 - D3 = 147 - Ds3 = 156 - Eb3 = 156 - E3 = 165 - F3 = 175 - Fs3 = 185 - Gb3 = 185 - G3 = 196 - Gs3 = 208 - Ab3 = 208 + # C3 = 131 + # Cs3 = 139 + # Db3 = 139 + # D3 = 147 + # Ds3 = 156 + # Eb3 = 156 + # E3 = 165 + # F3 = 175 + # Fs3 = 185 + # Gb3 = 185 + # G3 = 196 + # Gs3 = 208 + # Ab3 = 208 A3 = 220 - As3 = 233 - Bb3 = 233 + # As3 = 233 + # Bb3 = 233 B3 = 247 - C4 = 262 + # C4 = 262 Cs4 = 277 - Db4 = 277 + # Db4 = 277 D4 = 294 - Ds4 = 311 - Eb4 = 311 + # Ds4 = 311 + # Eb4 = 311 E4 = 330 - F4 = 349 + # F4 = 349 Fs4 = 370 - Gb4 = 370 + # Gb4 = 370 G4 = 392 - Gs4 = 415 - Ab4 = 415 - A4 = 440 - As4 = 466 - Bb4 = 466 + # Gs4 = 415 + # Ab4 = 415 + # A4 = 440 + # As4 = 466 + # Bb4 = 466 B4 = 494 C5 = 523 @@ -135,23 +135,23 @@ def annoy_ringtone(ringtone, tempo, interval): B5 = 987 # here's another way to express the note pitch, double the previous octave - C6 = C5 * 2 + # C6 = C5 * 2 Cs6 = Cs5 * 2 - Db6 = Db5 * 2 + # Db6 = Db5 * 2 D6 = D5 * 2 - Ds6 = Ds5 * 2 - Eb6 = Eb5 * 2 + # Ds6 = Ds5 * 2 + # Eb6 = Eb5 * 2 E6 = E5 * 2 - F6 = F5 * 2 - Fs6 = Fs5 * 2 - Gb6 = Gb5 * 2 - G6 = G5 * 2 - Gs6 = Gs5 * 2 - Ab6 = Ab5 * 2 - A6 = A5 * 2 - As6 = As5 * 2 - Bb6 = Bb5 * 2 - B6 = B5 * 2 + # F6 = F5 * 2 + # Fs6 = Fs5 * 2 + # Gb6 = Gb5 * 2 + # G6 = G5 * 2 + # Gs6 = Gs5 * 2 + # Ab6 = Ab5 * 2 + # A6 = A5 * 2 + # As6 = As5 * 2 + # Bb6 = Bb5 * 2 + # B6 = B5 * 2 if ringtone == 1: # Nokia From dd80f52705badf10625a553745e53c5523eded22 Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:39:35 -0400 Subject: [PATCH 51/83] Fixes Flake 8 Issues DataLogger --- Data_Logging_with_Feather_and_CircuitPython/DataLogger.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py index cb0ea5949..662dbc380 100644 --- a/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py +++ b/Data_Logging_with_Feather_and_CircuitPython/DataLogger.py @@ -45,7 +45,7 @@ while True: sdc.write("{}, {}, {}, {:.2f}\n".format( int(time_stamp), temperature, humidity, battery_voltage) - ) + ) time.sleep(3) except OSError: pass From 7f7e92fb827097a6c90ef39469fa57319ce14225 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Mon, 14 May 2018 22:48:57 +0100 Subject: [PATCH 52/83] Fix PEP8 compliance --- Jewel_Hair_Stick/Jewel_Hair_Stick.py | 5 +- .../Trinket_Gemma_Space_Invader_Pendant.py | 100 +++++++++++------- 2 files changed, 63 insertions(+), 42 deletions(-) diff --git a/Jewel_Hair_Stick/Jewel_Hair_Stick.py b/Jewel_Hair_Stick/Jewel_Hair_Stick.py index 1f619b60b..a346db05d 100644 --- a/Jewel_Hair_Stick/Jewel_Hair_Stick.py +++ b/Jewel_Hair_Stick/Jewel_Hair_Stick.py @@ -15,8 +15,9 @@ led.direction = Direction.OUTPUT # defaults to RGB|GRB Neopixels strip = neopixel.NeoPixel(pixpin, numpix, brightness=.1, auto_write=True) -# uncomment the following line for RGBW Neopixels -# strip = neopixel.NeoPixel(pixpin, numpix, bpp=4, brightness=.3, auto_write=True) +# uncomment the following two lines for RGBW Neopixels +# strip = neopixel.NeoPixel( +# pixpin, numpix, bpp=4, brightness=.3, auto_write=True) # You can have fun here changing the colors for the code color1 = (236, 79, 100) # Salmon Pink diff --git a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py index b590aa5fa..ab02bed1c 100644 --- a/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py +++ b/Trinket_Gemma_Space_Invader_Pendant/Trinket_Gemma_Space_Invader_Pendant.py @@ -26,84 +26,104 @@ frame_count = 0 # animation bitmaps animation = [ # frame 0 - alien #1 frame 1 - [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1]], # frame 1 - alien #1 frame 2 - [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 2 - alien #1 frame 1 (duplicate frame 1) - [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1]], # frame 3 - alien #1 frame 2 (duplicate frame 2) - [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 4 - alien #2 frame 1 - [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1]], # frame 5 - alien #2 frame 2 - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], - [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 6 - alien #2 frame 1 (duplicate frame 5) - [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1]], # frame 7 - alien #2 frame 2 (duplicate frame 6) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], - [1, 1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], + [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 8 - alien #3 first frame - [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 9 - alien #3 second frame - [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 10 - alien #3 first frame (duplicate frame 9) - [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], + [[0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 0, 0]], # frame 11 - alien #3 second frame (duplicate frame 10) - [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], - [1, 1, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [[0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0]], # frame 12 - alien #4 first frame - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1, 1], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 13 - alien #4 second frame - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 0, 0, 1, 1, 0, 0, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 14 - alien #4 third frame (not a repeat) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 15 - alien #4 fourth frame (not a repeat) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 16 - alien #4 first frame (duplicate frame 12) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1, 1], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], # frame 17 - alien #4 second frame (duplicate frame 13) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 0, 0, 1, 1, 0, 0, 1], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 18 - alien #4 second frame (duplicate frame 14) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 1, 1, 0, 0], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]], # frame 19 - alien #4 second frame (duplicate frame 15) - [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], - [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], + [[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] ] From de63a8e773611a2a77534ca2171df3453e93a577 Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 17:55:44 -0400 Subject: [PATCH 53/83] Fixes Flake 8 Issues GemmaM0 Vibration Switch Motion Alarm --- GemmaM0_Vibration_Switch_Motion_Alarm/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GemmaM0_Vibration_Switch_Motion_Alarm/main.py b/GemmaM0_Vibration_Switch_Motion_Alarm/main.py index a386af847..a0c6e1665 100644 --- a/GemmaM0_Vibration_Switch_Motion_Alarm/main.py +++ b/GemmaM0_Vibration_Switch_Motion_Alarm/main.py @@ -1,9 +1,9 @@ # Motion Sensor Alarm # uses Gemma M0, vibration sensor on A0/GND, & piezo on D0/GND +import time import pulseio from analogio import AnalogIn import board -import time piezo = pulseio.PWMOut(board.D0, duty_cycle=0, frequency=440, variable_frequency=True) From 41f2032141abbdcdd0eafefa8b4fa45ea7f8cbac Mon Sep 17 00:00:00 2001 From: Aaron Dershem Date: Mon, 14 May 2018 18:04:48 -0400 Subject: [PATCH 54/83] Fixes flake 8 issues Labo Piano Light FX --- Labo_Piano_Light_FX/code.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Labo_Piano_Light_FX/code.py b/Labo_Piano_Light_FX/code.py index 1fe0d066e..0dafa7426 100644 --- a/Labo_Piano_Light_FX/code.py +++ b/Labo_Piano_Light_FX/code.py @@ -24,9 +24,9 @@ def wheel(pos): # The colours are a transition r - g - b - back to r. if (pos < 0) or (pos > 255): return (0, 0, 0) - if (pos < 85): + if pos < 85: return (int(pos * 3), int(255 - (pos * 3)), 0) - elif (pos < 170): + elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: @@ -58,7 +58,7 @@ while True: n = int((mic_pin.value / 65536) * 1000) # 10-bit ADC format n = abs(n - 512 - dc_offset) # Center on zero - if (n >= noise): # Remove noise/hum + if n >= noise: # Remove noise/hum n = n - noise # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) From ee73558edfe25009b27b83f60e0982ce8ef56076 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:45:00 +0100 Subject: [PATCH 55/83] Fix PEP8 compliance --- .../Gemma_Firewalker_Lite_Sneakers.py | 26 ++++++++++++------- .../Logans_Run_Hand_Jewel_LED.py | 9 ++++--- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py index 0fa0c2b1e..3bbb3bf0f 100644 --- a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py +++ b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py @@ -78,11 +78,14 @@ gammas = [ 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, - 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 109, 110, 112, 114, - 115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 138, 140, 142, - 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175, - 177, 180, 182, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213, - 215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255] + 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 109, 110, + 112, 114, 115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, + 135, 137, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, + 160, 162, 164, 167, 169, 171, 173, 175, 177, 180, 182, 184, 186, + 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 213, 215, 218, + 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, + 255 +] def h2rgb(colour_hue): @@ -106,10 +109,13 @@ def wave_setup(): # assign random starting colors to waves for wave_index in range(n_waves): - wave[wave_index][hue] = wave[wave_index][hue_target] = 90 + random.randint(0, 90) - wave[wave_index][red] = h2rgb(wave[wave_index][hue] - 30) - wave[wave_index][green] = h2rgb(wave[wave_index][hue]) - wave[wave_index][blue] = h2rgb(wave[wave_index][hue] + 30) + current_wave = wave[wave_index] + random_offset = random.randint(0, 90) + + current_wave[hue] = current_wave[hue_target] = 90 + random_offset + current_wave[red] = h2rgb(current_wave[hue] - 30) + current_wave[green] = h2rgb(current_wave[hue]) + current_wave[blue] = h2rgb(current_wave[hue] + 30) def vibration_detector(): @@ -221,7 +227,7 @@ while True: g += (wave[w][green] * n) >> 8 b += (wave[w][blue] * n) >> 8 # >>8 is equiv to /256 else: # Fade RGB color to white - # In HSV colorspace, this would be tweaking 'saturation' + # In HSV colorspace, this tweaks 'saturation' n = int((y - 128) * 2) # 0-255 affects white level m = 256 * n n = 256 - n # 1-256 affects RGB level diff --git a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py index 557facb15..4d4a276d7 100644 --- a/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py +++ b/Logans_Run_Hand_Jewel_LED/Logans_Run_Hand_Jewel_LED.py @@ -11,8 +11,10 @@ wait = .5 # 1/2 second color fade duration strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=False) -# uncomment the following line for RGBW Neopixels -# strip = neopixel.NeoPixel(pixpin, numpix, bpp=4, brightness=.3, auto_write=True) +# uncomment the following 3 line for RGBW Neopixels +# strip = neopixel.NeoPixel( +# pixpin, numpix, bpp=4, brightness=.3, auto_write=True +# ) # Linear interpolation of y value given min/max x, min/max y, and x position. @@ -58,7 +60,8 @@ def color_gradient(start_r, start_g, start_b, end_r, end_g, end_b, pos): # Total duration of animation, in milliseconds -def animate_gradient_fill(start_r, start_g, start_b, end_r, end_g, end_b, duration_ms): +def animate_gradient_fill(start_r, start_g, start_b, end_r, end_g, end_b, + duration_ms): start = time.monotonic() # Display start color. From fc8b239fe2c128b3dde524f2a1b28cc16a4fc8ff Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:52:10 +0100 Subject: [PATCH 56/83] Fix PEP8 compliance --- .../3D_Printed_NeoPixel_Ring_Hair_Dress.py | 54 ++++++++++--------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py index e7d460241..ca47db710 100644 --- a/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py +++ b/3D_Printed_NeoPixel_Ring_Hair_Dress/3D_Printed_NeoPixel_Ring_Hair_Dress.py @@ -50,10 +50,10 @@ action_step_duration = 2 # loop in milliseconds - thus, controls the action speed (be # careful not to use values > 2^16-1 - roughly one minute :-) -color_granularity = 3 # controls the increment of the R, G, and B portions of the -# rsp. color. 1 means the increment is 0,1,2,3,..., 10 means -# the increment is 0,10,20,... don't use values > 255, and note -# that even values > 127 wouldn't make much sense... +color_granularity = 3 # controls the increment of the R, G, and B +# portions of the rsp. color. 1 means the increment is 0,1,2,3,..., +# 10 means the increment is 0,10,20,... don't use values > 255, and +# note that even values > 127 wouldn't make much sense... # controls the speed of color changing independently from action color_interval = 4 @@ -80,23 +80,23 @@ spectrum_part = 0 # this array variable must be called theactionlist !!! # # valid actions are: -# ACT_NOP simply do nothing and switch everything off -# ACT_SIMPLE_RING all leds on -# ACT_CYCLING_RING_ACLK anti clockwise cycling colors -# ACT_CYCLING_RING_CLKW clockwise cycling colors acording -# ACT_WHEEL_ACLK anti clockwise spinning wheel -# ACT_WHEEL_CLKW clockwise spinning wheel -# ACT_SPARKLING_RING sparkling effect +# ACT_NOP simply do nothing and switch everything off +# ACT_SIMPLE_RING all leds on +# ACT_CYCLING_RING_ACLK anti clockwise cycling colors +# ACT_CYCLING_RING_CLKW clockwise cycling colors acording +# ACT_WHEEL_ACLK anti clockwise spinning wheel +# ACT_WHEEL_CLKW clockwise spinning wheel +# ACT_SPARKLING_RING sparkling effect # # valid color options are: -# COL_RANDOM colors will be selected randomly, which might -# be not very sufficient due to well known -# limitations of the random generation algorithm -# COL_SPECTRUM colors will be set as cyclic spectral wipe -# R -> G -> B -> R -> G -> B -> R -> ... +# COL_RANDOM colors will be selected randomly, which might +# be not very sufficient due to well known +# limitations of the random generation algorithm +# COL_SPECTRUM colors will be set as cyclic spectral wipe +# R -> G -> B -> R -> G -> B -> R -> ... -# action action name & action step color color change -# duration color generation method duration granularity interval +# action action name & action step color color change +# duration color generation method duration granularity interval theactionlist = [ [5, ACT_SPARKLING_RING | COL_RANDOM, 0.01, 25, 1], [2, ACT_CYCLING_RING_CLKW | COL_RANDOM, @@ -229,12 +229,14 @@ while True: # Loop forever... # do we need to load the next action? if (time.monotonic() - action_timer) > curr_action_duration: - curr_action_duration = theactionlist[curr_action_idx][action_duration] - curr_action = theactionlist[curr_action_idx][action_and_color_gen] & 0x3F - curr_action_step_duration = theactionlist[curr_action_idx][action_step_duration] - curr_color_gen = theactionlist[curr_action_idx][action_and_color_gen] & 0xC0 - curr_color_granularity = theactionlist[curr_action_idx][color_granularity] - curr_color_interval = theactionlist[curr_action_idx][color_interval] + current_action = theactionlist[curr_action_idx] + + curr_action_duration = current_action[action_duration] + curr_action = current_action[action_and_color_gen] & 0x3F + curr_action_step_duration = current_action[action_step_duration] + curr_color_gen = current_action[action_and_color_gen] & 0xC0 + curr_color_granularity = current_action[color_granularity] + curr_color_interval = current_action[color_interval] curr_action_idx += 1 # take care to rotate the action list! @@ -251,6 +253,8 @@ while True: # Loop forever... if curr_action: + is_act_cycling = (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW) + if curr_action == ACT_NOP: # rather trivial even tho this will be repeated as long as the # NOP continues - i could have prevented it from repeating @@ -264,7 +268,7 @@ while True: # Loop forever... for i in range(0, numpix): strip[i] = color - elif curr_action == (ACT_CYCLING_RING_ACLK or ACT_CYCLING_RING_CLKW): + elif curr_action == is_act_cycling: # spin the ring clockwise or anti clockwise if curr_action == ACT_CYCLING_RING_ACLK: idx += 1 From 776440b1bc4114236bb43dfe4eaeadd719aeabc0 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:53:11 +0100 Subject: [PATCH 57/83] Fix PEP8 compliance --- Sensor_Plotting_With_Mu_CircuitPython/color.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sensor_Plotting_With_Mu_CircuitPython/color.py b/Sensor_Plotting_With_Mu_CircuitPython/color.py index 48fbbe5fc..b6beb2446 100644 --- a/Sensor_Plotting_With_Mu_CircuitPython/color.py +++ b/Sensor_Plotting_With_Mu_CircuitPython/color.py @@ -21,5 +21,6 @@ while True: blue = int(raw_blue * (255 / 65535)) pixels.fill((0, 0, 0)) - # Printed to match the color lines on the Mu plotter! The orange line represents red. + # Printed to match the color lines on the Mu plotter! + # The orange line represents red. print((green, blue, red)) From 766c59e8984cd839eb52e0cb1a314fe0f58141bc Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:54:28 +0100 Subject: [PATCH 58/83] Fix PEP8 compliance --- .../CircuitPython_Internal_RGB_LED_colors.py | 3 ++- CircuitPython_Essentials/CircuitPython_PWM_Piezo.py | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py index f3534f272..ba5e8426c 100644 --- a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py +++ b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_colors.py @@ -5,7 +5,8 @@ import board # For Trinket M0, Gemma M0, and ItsyBitsy M0 Express led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) -# For Feather M0 Express, Metro M0 Express, Metro M4 Express, and Circuit Playground Express +# For Feather M0 Express, Metro M0 Express, Metro M4 Express, and Circuit +# Playground Express # led = neopixel.NeoPixel(board.NEOPIXEL, 1) led.brightness = 0.3 diff --git a/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py b/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py index 6061d1a69..7242e1a02 100644 --- a/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py +++ b/CircuitPython_Essentials/CircuitPython_PWM_Piezo.py @@ -7,7 +7,9 @@ import pulseio piezo = pulseio.PWMOut(board.A2, duty_cycle=0, frequency=440, variable_frequency=True) # For Metro M4 Express: -# piezo = pulseio.PWMOut(board.A1, duty_cycle=0, frequency=440, variable_frequency=True) +# piezo = pulseio.PWMOut( +# board.A1, duty_cycle=0, frequency=440, variable_frequency=True +# ) while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): From a52d380bcd223df442c53018c62bce5856f69c8a Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:56:20 +0100 Subject: [PATCH 59/83] Fix PEP8 compliance --- CircuitPython_Essentials/CircuitPython_HID_Mouse.py | 3 ++- .../CircuitPython_Internal_RGB_LED_rainbow.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CircuitPython_Essentials/CircuitPython_HID_Mouse.py b/CircuitPython_Essentials/CircuitPython_HID_Mouse.py index 671170a4e..28e33a4c9 100644 --- a/CircuitPython_Essentials/CircuitPython_HID_Mouse.py +++ b/CircuitPython_Essentials/CircuitPython_HID_Mouse.py @@ -22,7 +22,8 @@ def get_voltage(pin): return (pin.value * 3.3) / 65536 -def steps(axis): # Maps the potentiometer voltage range to 0-20 in whole numbers +def steps(axis): + """ Maps the potentiometer voltage range to 0-20 """ return round((axis - pot_min) / step) diff --git a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py index a22dd1af8..7e31db381 100644 --- a/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py +++ b/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py @@ -7,7 +7,8 @@ import board led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) -# For Feather M0 Express, Metro M0 Express, Metro M4 Express and Circuit Playground Express +# For Feather M0 Express, Metro M0 Express, Metro M4 Express and Circuit +# Playground Express # led = neopixel.NeoPixel(board.NEOPIXEL, 1) From fd95ddf38e079b8a3802ba839f863cc76952b9d0 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 14:58:16 +0100 Subject: [PATCH 60/83] Fix PEP8 compliance --- Cyber_Flower/main.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Cyber_Flower/main.py b/Cyber_Flower/main.py index 71fb90ecb..2b2f4e0af 100644 --- a/Cyber_Flower/main.py +++ b/Cyber_Flower/main.py @@ -25,8 +25,10 @@ # calibrated with your body touching it (making it less accurate). # # Also note this depends on two external modules to be loaded on the Gemma M0: -# - Adafruit CircuitPython DotStar: https://github.com/adafruit/Adafruit_CircuitPython_DotStar -# - Adafruit CircuitPython FancyLED: https://github.com/adafruit/Adafruit_CircuitPython_FancyLED +# - Adafruit CircuitPython DotStar: +# https://github.com/adafruit/Adafruit_CircuitPython_DotStar +# - Adafruit CircuitPython FancyLED: +# https://github.com/adafruit/Adafruit_CircuitPython_FancyLED # # You _must_ have both adafruit_dotstar.mpy and the adafruit_fancyled folder # and files within it on your board for this code to work! If you run into From 38e2c52599867dbb5dcc7e2fbe79f1f136687bfd Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:00:11 +0100 Subject: [PATCH 61/83] Fix PEP8 compliance --- .../digitalsand.py | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py index 44dc0c1c2..51b6ebc1a 100644 --- a/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py +++ b/Digital_Sand_Dotstar_Circuitpython_Edition/digitalsand.py @@ -45,7 +45,8 @@ MAX_Y = HEIGHT * 256 - 1 class Grain: - """A simple struct to hold position and velocity information for a single grain.""" + """A simple struct to hold position and velocity information + for a single grain.""" def __init__(self): """Initialize grain position and velocity.""" @@ -71,7 +72,8 @@ occupied_bits = [False for _ in range(WIDTH * HEIGHT)] def index_of_xy(x, y): - """Convert an x/column and y/row into an index into a linear pixel array. + """Convert an x/column and y/row into an index into + a linear pixel array. :param int x: column value :param int y: row value @@ -82,8 +84,9 @@ def index_of_xy(x, y): def already_present(limit, x, y): """Check if a pixel is already used. - :param int limit: the index into the grain array of the grain being assigned a pixel - Only grains already allocated need to be checks against. + :param int limit: the index into the grain array of + the grain being assigned a pixel Only grains already + allocated need to be checks against. :param int x: proposed clumn value for the new grain :param int y: proposed row valuse for the new grain """ @@ -185,10 +188,12 @@ while True: g.vy //= -2 newidx = oldidx # no pixel change else: # Diagonal intersection is more tricky... - # Try skidding along just one axis of motion if possible (start w/ - # faster axis). Because we've already established that diagonal - # (both-axis) motion is occurring, moving on either axis alone WILL - # change the pixel index, no need to check that again. + # Try skidding along just one axis of motion if + # possible (start w/ faster axis). Because we've + # already established that diagonal (both-axis) + # motion is occurring, moving on either axis alone + # WILL change the pixel index, no need to check + # that again. if abs(g.vx) > abs(g.vy): # x axis is faster newidx = index_of_xy(newx, g.y) # that pixel is free, take it! But... From 206898a811184cb8c2e77a9c1615b79f5a73cc73 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:02:31 +0100 Subject: [PATCH 62/83] Fix PEP8 compliance --- .../CircuitPlaygroundExpress_SoundMeter.py | 7 +++++-- Introducing_CircuitPlaygroundExpress/Playground_808.py | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py index a5fa58466..a0f031e06 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_SoundMeter.py @@ -47,7 +47,7 @@ def constrain(value, floor, ceiling): return max(floor, min(value, ceiling)) -# Scale input_value to be between output_min and output_max, in an exponential way. +# Scale input_value between output_min and output_max, exponentially. def log_scale(input_value, input_min, input_max, output_min, output_max): @@ -63,7 +63,10 @@ def log_scale(input_value, input_min, input_max, output_min, output_max): def normalized_rms(values): minbuf = int(mean(values)) - samples_sum = sum(float(sample - minbuf) * (sample - minbuf) for sample in values) + samples_sum = sum( + float(sample - minbuf) * (sample - minbuf) + for sample in values + ) return math.sqrt(samples_sum / len(values)) diff --git a/Introducing_CircuitPlaygroundExpress/Playground_808.py b/Introducing_CircuitPlaygroundExpress/Playground_808.py index 9aa8fac0a..da25ffb6b 100644 --- a/Introducing_CircuitPlaygroundExpress/Playground_808.py +++ b/Introducing_CircuitPlaygroundExpress/Playground_808.py @@ -7,7 +7,7 @@ import board import touchio from digitalio import DigitalInOut, Direction -bpm = 120 # beats per minute for sustained hold, change this to suit your tempo +bpm = 120 # beats per minute, change this to suit your tempo # enable the speaker spkrenable = DigitalInOut(board.SPEAKER_ENABLE) From f1d408d6b947e824dab2ff04d3c0450f056bfd0d Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:04:28 +0100 Subject: [PATCH 63/83] Fix PEP8 compliance --- .../CircuitPlaygroundExpress_Temperature.py | 5 +++-- Morse_Code_Flasher/main.py | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py index bab712f74..4474549e6 100644 --- a/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py +++ b/Introducing_CircuitPlaygroundExpress/CircuitPlaygroundExpress_Temperature.py @@ -10,7 +10,8 @@ thermistor = adafruit_thermistor.Thermistor( board.TEMPERATURE, 10000, 10000, 25, 3950) while True: - print("Temperature is: %f C and %f F" % (thermistor.temperature, - (thermistor.temperature * 9 / 5 + 32))) + temp_c = thermistor.temperature + temp_f = thermistor.temperature * 9 / 5 + 32 + print("Temperature is: %f C and %f F" % (temp_c, temp_f)) time.sleep(0.25) diff --git a/Morse_Code_Flasher/main.py b/Morse_Code_Flasher/main.py index 89684ba22..0d0212f2d 100644 --- a/Morse_Code_Flasher/main.py +++ b/Morse_Code_Flasher/main.py @@ -67,7 +67,10 @@ class MorseFlasher: def __init__(self, color=(255, 255, 255)): # set the color adjusted for brightness self._color = ( - int(color[0] * brightness), int(color[1] * brightness), int(color[2] * brightness)) + int(color[0] * brightness), + int(color[1] * brightness), + int(color[2] * brightness) + ) def light(self, on=True): if on: From c20d13cdcbc6f2d3a2af9e590f7f61c53ae20ca5 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:06:28 +0100 Subject: [PATCH 64/83] Fix PEP8 compliance and fix remapRange --- .../Animated_NeoPixel_Glow_Fur_Scarf.py | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py index 932860742..e2c66ab73 100644 --- a/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py +++ b/Animated_NeoPixel_Glow_Fur_Scarf/Animated_NeoPixel_Glow_Fur_Scarf.py @@ -3,15 +3,15 @@ import board import neopixel from digitalio import DigitalInOut, Direction, Pull -led_pin = board.D1 # which pin your pixels are connected to -num_leds = 78 # how many LEDs you have -brightness = 1.0 # 0-1, higher number is brighter -saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color -steps = 0.01 # how wide the bands of color are. -offset = 0 # cummulative steps -fadeup = True # start with fading up - increase steps until offset reaches 1 -index = 8 # midway color selection -blend = True # color blending between palette indices +led_pin = board.D1 # which pin your pixels are connected to +num_leds = 78 # how many LEDs you have +brightness = 1.0 # 0-1, higher number is brighter +saturation = 255 # 0-255, 0 is pure white, 255 is fully saturated color +steps = 0.01 # how wide the bands of color are. +offset = 0 # cummulative steps +fadeup = True # start with fading up - increase steps until offset reaches 1 +index = 8 # midway color selection +blend = True # color blending between palette indices # initialize list with all pixels off palette = [0] * num_leds @@ -69,7 +69,7 @@ def wheel(pos): if (pos < 0) or (pos > 255): return (0, 0, 0) if pos < 85: - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) @@ -79,11 +79,14 @@ def wheel(pos): def remapRange(value, leftMin, leftMax, rightMin, rightMax): - # this remaps a value from original (left) range to new (right) range + # this remaps a value fromhere original (left) range to new (right) range # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin + # Convert the left range into a 0-1 range (int) + valueScaled = int(value - leftMin) / int(leftSpan) + # Convert the 0-1 range into a value in the right range. return int(rightMin + (valueScaled * rightSpan)) @@ -96,13 +99,14 @@ def shortkeypress(color_palette): return color_palette + while True: # check for button press currkeystate = button.value # button press, move to next pattern - if (prevkeystate != True) and currkeystate: + if (prevkeystate is not True) and currkeystate: ledmode = shortkeypress(ledmode) # save button press state From e9d5fdb1ffd1aff78eb04e4a4fe6258796956b91 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:07:34 +0100 Subject: [PATCH 65/83] Fix PEP8 compliance --- Labo_Piano_Light_FX/code.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Labo_Piano_Light_FX/code.py b/Labo_Piano_Light_FX/code.py index 0dafa7426..97f109f3e 100644 --- a/Labo_Piano_Light_FX/code.py +++ b/Labo_Piano_Light_FX/code.py @@ -69,5 +69,6 @@ while True: for i in range(0, len(strip)): strip[i] = wheel(vlvl) # Set strip brightness based oncode audio level - strip.brightness = float(remapRangeSafe(lvl, 50, 255, 0, maxbrt)) / 255.0 + brightness = remapRangeSafe(lvl, 50, 255, 0, maxbrt) + strip.brightness = float(brightness) / 255.0 strip.show() From fbc7541830387b35707698456f5203d71ff2b393 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:09:20 +0100 Subject: [PATCH 66/83] Fix PEP8 compliance --- Annoy_O_Matic/main.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Annoy_O_Matic/main.py b/Annoy_O_Matic/main.py index 4c1089f2b..b4845a5e2 100644 --- a/Annoy_O_Matic/main.py +++ b/Annoy_O_Matic/main.py @@ -64,12 +64,12 @@ def annoy_ringtone(ringtone, tempo, interval): # tempo is length of whole note in seconds, e.g. 1.5 # set up time signature whole_note = tempo # adjust this to change tempo of everything - dotted_whole_note = whole_note * 1.5 + # dotted_whole_note = whole_note * 1.5 # these notes are fractions of the whole note - half_note = whole_note / 2 - dotted_half_note = half_note * 1.5 + # half_note = whole_note / 2 + # dotted_half_note = half_note * 1.5 quarter_note = whole_note / 4 - dotted_quarter_note = quarter_note * 1.5 + # dotted_quarter_note = quarter_note * 1.5 eighth_note = whole_note / 8 dotted_eighth_note = eighth_note * 1.5 sixteenth_note = whole_note / 16 @@ -116,22 +116,22 @@ def annoy_ringtone(ringtone, tempo, interval): # Bb4 = 466 B4 = 494 - C5 = 523 + # C5 = 523 Cs5 = 554 - Db5 = 554 + # Db5 = 554 D5 = 587 - Ds5 = 622 - Eb5 = 622 + # Ds5 = 622 + # Eb5 = 622 E5 = 659 - F5 = 698 + # F5 = 698 Fs5 = 740 - Gb5 = 740 - G5 = 784 + # Gb5 = 740 + # G5 = 784 Gs5 = 831 - Ab5 = 831 + # Ab5 = 831 A5 = 880 - As5 = 932 - Bb5 = 932 + # As5 = 932 + # Bb5 = 932 B5 = 987 # here's another way to express the note pitch, double the previous octave From 932d2e1dfdd34dd98e7027040cd939c8fdbd2db3 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:14:10 +0100 Subject: [PATCH 67/83] Fix PEP8 compliance --- Foul_Fowl/main.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/Foul_Fowl/main.py b/Foul_Fowl/main.py index d4c1b66ff..2cc99e43a 100644 --- a/Foul_Fowl/main.py +++ b/Foul_Fowl/main.py @@ -144,23 +144,33 @@ def launch_terminal(): time.sleep(2) layout.write( - " _ _ _____ _ _ ___ _____ ____ ___ _____ _ _ ____") + " _ _ _____ _ _ ___ " + "_____ ____ ___ _____ _ _ ____" + ) kbd.press(Keycode.ENTER) kbd.release_all() layout.write( - "| | | | ____| | | | / _ \ | ___| _ \|_ _| ____| \ | | _ \ ") + "| | | | ____| | | | / _ \ | " + " ___| _ \|_ _| ____| \ | | _ \ " + ) kbd.press(Keycode.ENTER) kbd.release_all() layout.write( - "| |_| | _| | | | | | | | | | |_ | |_) || || _| | \| | | | |") + "| |_| | _| | | | | | | | | | |" + "_ | |_) || || _| | \| | | | |" + ) kbd.press(Keycode.ENTER) kbd.release_all() layout.write( - "| _ | |___| |___| |__| |_| | | _| | _ < | || |___| |\ | |_| |") + "| _ | |___| |___| |__| |_| | | " + " _| | _ < | || |___| |\ | |_| |" + ) kbd.press(Keycode.ENTER) kbd.release_all() layout.write( - "|_| |_|_____|_____|_____\___/ |_| |_| \_\___|_____|_| \_|____/ ") + "|_| |_|_____|_____|_____\___/ |_" + "| |_| \_\___|_____|_| \_|____/ " + ) kbd.press(Keycode.ENTER) kbd.release_all() @@ -189,8 +199,14 @@ def download_image(): # this says where to save image, and where to get it led.value = False + + url = ( + 'https://cdn-learn.adafruit.com/assets/assets/000/051/840/' + 'original/hacks_foulFowl.jpg' + ) layout.write( - 'curl -o ~/Desktop/hackimage.jpg https://cdn-learn.adafruit.com/assets/assets/000/051/840/original/hacks_foulFowl.jpg') + 'curl -o ~/Desktop/hackimage.jpg {}'.format(url) + ) time.sleep(pause) kbd.press(Keycode.ENTER) led.value = True @@ -213,7 +229,11 @@ def replace_background(): # run this after download_image (which ran after launch_terminal) # it uses actionscript to change the background layout.write( - 'osascript -e \'tell application \"System Events\" to set picture of every desktop to (POSIX path of (path to home folder) & \"/Desktop/hackimage.jpg\" as POSIX file as alias)\'') + 'osascript -e \'tell application \"System Events\" ' + 'to set picture of every desktop to (POSIX path of ' + '(path to home folder) & \"/Desktop/hackimage.jpg\" ' + 'as POSIX file as alias)\'' + ) time.sleep(pause) kbd.press(Keycode.ENTER) kbd.release_all() From c66911d04ebd3dbc4d364e4aee3b4832d3ad4722 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:15:04 +0100 Subject: [PATCH 68/83] Fix PEP8 compliance --- Trinket_Gemma_IR_Control/IR_reader.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Trinket_Gemma_IR_Control/IR_reader.py b/Trinket_Gemma_IR_Control/IR_reader.py index f81fa7782..29c9d21b1 100644 --- a/Trinket_Gemma_IR_Control/IR_reader.py +++ b/Trinket_Gemma_IR_Control/IR_reader.py @@ -33,8 +33,8 @@ while True: print("pulse count: ", len(detected)) # print in list form of the pulse duration in microseconds - # typically starts with ~9,000 microseconds followed by a ~4,000 microseconds - # which is standard IR preamble + # typically starts with ~9,000 microseconds followed by a ~4,000 + # microseconds which is standard IR preamble print(detected) print() From ad6c0786bd3b8a1374c199e31533d3dcddf39ce2 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:16:50 +0100 Subject: [PATCH 69/83] Fix PEP8 compliance --- .../3D_Printed_LED_Microphone_Flag.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py index b9fb34347..82a4c771e 100644 --- a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py +++ b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py @@ -40,7 +40,8 @@ sample_window = .1 # Sample window for average level peak_hang = 24 # Time of pause before peak dot falls peak_fall = 4 # Rate of falling peak dot input_floor = 10 # Lower range of analogRead input -# Max range of analogRead input, the lower the value the more sensitive (1023 = max) +# Max range of analogRead input, the lower the value the more sensitive +# (1023 = max) input_ceiling = 300 peak = 16 # Peak level of column; used for falling dots @@ -58,7 +59,7 @@ def wheel(pos): if pos < 0 or pos > 255: return (0, 0, 0) if pos < 85: - return (int(pos * 3), int(255 - (pos*3)), 0) + return (int(pos * 3), int(255 - (pos * 3)), 0) elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) @@ -114,7 +115,8 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): invflag = 1 zerorefcurval = inputvalue - originalmin - normalizedcurval = zerorefcurval / originalrange # normalize to 0 - 1 float + # normalize to 0 - 1 float + normalizedcurval = zerorefcurval / originalrange # Check for originalMin > originalMax # -the math for all other cases @@ -124,7 +126,7 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): if invflag == 0: rangedvalue = (pow(normalizedcurval, curve) * newrange) + newbegin - else: # invert the ranges + else: # invert the ranges rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange) return rangedvalue From 02ba7cfdb8423b43e40a4103bba0e84c42dc67b3 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:19:47 +0100 Subject: [PATCH 70/83] Fix PEP8 compliance --- Arcade_Button_Control_Box/Arcade_Button_Control_Box.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py index 7a7e33e80..bd73e0d05 100644 --- a/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py +++ b/Arcade_Button_Control_Box/Arcade_Button_Control_Box.py @@ -3,7 +3,7 @@ import time import digitalio from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode -from board import D12, D11, D10, D9, D6, D5, A0, A1, A2, A3, A4, A5 +from board import D13, D12, D11, D10, D9, D6, D5, A0, A1, A2, A3, A4, A5 # A simple neat keyboard demo in circuitpython From 0f7391c421ca5b8e0791f36916947fb46135c9f1 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:20:36 +0100 Subject: [PATCH 71/83] Correct typo --- Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py index 3b79994a7..8edb07302 100644 --- a/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py +++ b/Hacking_Ikea_Lamps_With_CPX/CPX_Left_Rotation_State_Machine.py @@ -8,7 +8,7 @@ from adafruit_circuitplayground.express import cpx def upright(x, y, z): x_up = abs(x) < accel_threshold - y_up = abs(x) < accel_threshold + y_up = abs(y) < accel_threshold z_up = abs(9.8 - z) < accel_threshold return x_up and y_up and z_up From 81a255f0d26330cffcfc1257703c20e0851eca37 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:26:06 +0100 Subject: [PATCH 72/83] Remove unused variables --- Breath_Tester/Breath_Tester.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Breath_Tester/Breath_Tester.py b/Breath_Tester/Breath_Tester.py index 8f33e82f7..0f229337f 100644 --- a/Breath_Tester/Breath_Tester.py +++ b/Breath_Tester/Breath_Tester.py @@ -20,7 +20,7 @@ def warmup_message(): warmup_counter = 0 # initial read required to get sensor going - co2eq, tvoc = sgp30.iaq_measure() + sgp30.iaq_measure() print() print("Warming Up [%d seconds]..." % warmup_time) @@ -45,25 +45,25 @@ def get_breath_reading(): print() while breath_counter <= breath_time: - co2eq, tvoc = sgp30.iaq_measure() + _, tvoc = sgp30.iaq_measure() breath_saves[breath_counter] = tvoc print(tvoc, ', ', end='') time.sleep(1) breath_counter += 1 breath_saves = sorted(breath_saves) - highest_breath_result = breath_saves[breath_counter - 1] + result = breath_saves[breath_counter - 1] - return highest_breath_result + return result # show the highest reading recorded -def show_results(highest_breath_result): +def show_results(breath_result): print() print() - print("peak VOC reading:", highest_breath_result) + print("peak VOC reading:", breath_result) print() input("Press any key to test again") print() From b5424c1f8953e74b1020803649e1aa18551bf368 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:35:03 +0100 Subject: [PATCH 73/83] Fix unused variables --- Cyberpunk_Spikes/Cyberpunk_Spikes.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cyberpunk_Spikes/Cyberpunk_Spikes.py b/Cyberpunk_Spikes/Cyberpunk_Spikes.py index d0afcdfa7..06edeba64 100644 --- a/Cyberpunk_Spikes/Cyberpunk_Spikes.py +++ b/Cyberpunk_Spikes/Cyberpunk_Spikes.py @@ -38,6 +38,7 @@ def rainbow(wait): for i in range(len(strip)): idx = int(i + j) strip[i] = wheel(idx & 255) + time.sleep(wait) # Slightly different, this makes the rainbow equally distributed throughout @@ -71,7 +72,7 @@ def wheel(pos): def flash_random(wait, howmany): - for k in range(howmany): + for _ in range(howmany): c = random.randint(0, len(colors) - 1) # Choose random color index j = random.randint(0, numpix - 1) # Choose random pixel From 46afca2a8f4fcf211c3627c58fe1120189f61c9e Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:39:42 +0100 Subject: [PATCH 74/83] Fix comparison --- GemmaM0_Radio_Tuning_Knob/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GemmaM0_Radio_Tuning_Knob/main.py b/GemmaM0_Radio_Tuning_Knob/main.py index 82886fa3e..04ec636f8 100644 --- a/GemmaM0_Radio_Tuning_Knob/main.py +++ b/GemmaM0_Radio_Tuning_Knob/main.py @@ -49,8 +49,8 @@ def spamKey(code): while True: knob = (getVoltage(analog2in)) - if steps(knob) is 5: # the center position is active + if steps(knob) == 5: # the center position is active led.value = True - elif steps(knob) is not 5: + elif steps(knob) != 5: led.value = False spamKey(steps(knob)) From 3627bb0460e3fb59e86d4cfedee7d6de7a3847ca Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:40:07 +0100 Subject: [PATCH 75/83] Fix unused variable --- Introducing_Trinket_M0/Trinket_SDCardList.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Introducing_Trinket_M0/Trinket_SDCardList.py b/Introducing_Trinket_M0/Trinket_SDCardList.py index d77b23671..67e37f0c4 100644 --- a/Introducing_Trinket_M0/Trinket_SDCardList.py +++ b/Introducing_Trinket_M0/Trinket_SDCardList.py @@ -36,7 +36,7 @@ def print_directory(path, tabs=0): sizestr = "%0.1f MB" % (filesize / 1000000) prettyprintname = "" - for i in range(tabs): + for _ in range(tabs): prettyprintname += " " prettyprintname += file if isdir: From a1b5e93ef4ae149c451b83fb6b14fcfaabd27313 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:43:45 +0100 Subject: [PATCH 76/83] Fix duplicate variable name --- Giant_Mechanical_Keyboard/code.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Giant_Mechanical_Keyboard/code.py b/Giant_Mechanical_Keyboard/code.py index d09d5e8e8..cf9254176 100644 --- a/Giant_Mechanical_Keyboard/code.py +++ b/Giant_Mechanical_Keyboard/code.py @@ -58,16 +58,16 @@ statusled.direction = Direction.OUTPUT print("Waiting for button presses") -def pressbutton(i): - switch_led = leds[i] # find the switch LED - k = buttonkeys[i] # get the corresp. keycode/str +def pressbutton(index): + switch_led = leds[index] # find the switch LED + k = buttonkeys[index] # get the corresp. keycode/str switch_led.value = True # turn on LED kbd.press(k) # send keycode -def releasebutton(i): - switch_led = leds[i] # find the switch LED - k = buttonkeys[i] # get the corresp. keycode/str +def releasebutton(index): + switch_led = leds[index] # find the switch LED + k = buttonkeys[index] # get the corresp. keycode/str switch_led.value = False # turn on LED kbd.release(k) # send keycode From d42fdb6fb422b7102b628b0c49f9b0a4d593c31d Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:51:07 +0100 Subject: [PATCH 77/83] rename variable --- Morse_Code_Flasher/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Morse_Code_Flasher/main.py b/Morse_Code_Flasher/main.py index 0d0212f2d..9dddbc4bd 100644 --- a/Morse_Code_Flasher/main.py +++ b/Morse_Code_Flasher/main.py @@ -91,10 +91,10 @@ class MorseFlasher: self.light(False) time.sleep(symbol_gap) - def encode(self, str): + def encode(self, string): output = "" # iterate through string's characters - for c in str: + for c in string: # find morse code for a character for x in morse: if x[0] == c: From 7cd211163963f586c5d390ef2f902aa87106889f Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:54:12 +0100 Subject: [PATCH 78/83] rename variable --- .../Gemma_Firewalker_Lite_Sneakers.py | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py index 3bbb3bf0f..c1e14be75 100644 --- a/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py +++ b/Gemma_Firewalker_Lite_Sneakers/Gemma_Firewalker_Lite_Sneakers.py @@ -191,12 +191,12 @@ while True: r = g = b = 0 # For each item in wave[] array... - for w in range(n_waves): + for w_index in range(n_waves): # Calculate distance from pixel center to wave # center point, using both signed and unsigned # 8-bit integers... - d1 = int(abs(x - wave[w][center])) - d2 = int(abs(x - wave[w][center])) + d1 = int(abs(x - wave[w_index][center])) + d2 = int(abs(x - wave[w_index][center])) # Then take the lesser of the two, resulting in # a distance (0-128) @@ -211,9 +211,9 @@ while True: # pixel (basic linear y=mx+b stuff). # Is distance within wave's influence? # d2 is opposite; distance to wave's end - if d1 < wave[w][width]: - d2 = wave[w][width] - d1 - y = int(brightness * d2 / wave[w][width]) # 0 to 200 + if d1 < wave[w_index][width]: + d2 = wave[w_index][width] - d1 + y = int(brightness * d2 / wave[w_index][width]) # 0 to 200 # y is a brightness scale value -- # proportional to, but not exactly equal @@ -222,18 +222,18 @@ while True: # In HSV colorspace, this would be # tweaking 'value' n = int(y * 2 + 1) # 1-256 - r += (wave[w][red] * n) >> 8 # More fixed-point math + r += (wave[w_index][red] * n) >> 8 # More fixed-point math # Wave color is scaled by 'n' - g += (wave[w][green] * n) >> 8 - b += (wave[w][blue] * n) >> 8 # >>8 is equiv to /256 + g += (wave[w_index][green] * n) >> 8 + b += (wave[w_index][blue] * n) >> 8 # >>8 is equiv to /256 else: # Fade RGB color to white # In HSV colorspace, this tweaks 'saturation' n = int((y - 128) * 2) # 0-255 affects white level m = 256 * n n = 256 - n # 1-256 affects RGB level - r += (m + wave[w][red] * n) >> 8 - g += (m + wave[w][green] * n) >> 8 - b += (m + wave[w][blue] * n) >> 8 + r += (m + wave[w_index][red] * n) >> 8 + g += (m + wave[w_index][green] * n) >> 8 + b += (m + wave[w_index][blue] * n) >> 8 # r,g,b are 16-bit types that accumulate brightness # from all waves that affect this pixel; may exceed From e43369e5ae2029edd10f05e1e3c9cd90d3df5e1f Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 15:56:39 +0100 Subject: [PATCH 79/83] Rename variables --- Foul_Fowl/main.py | 2 +- FruitBox_Sequencer/main.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Foul_Fowl/main.py b/Foul_Fowl/main.py index 2cc99e43a..978f00ebe 100644 --- a/Foul_Fowl/main.py +++ b/Foul_Fowl/main.py @@ -135,7 +135,7 @@ def launch_terminal(): time.sleep(pause) # type a message a few times - for i in range(3): + for _ in range(3): layout.write("HELLO FRIEND") # time.sleep(pause) kbd.press(Keycode.ENTER) diff --git a/FruitBox_Sequencer/main.py b/FruitBox_Sequencer/main.py index 1aad432e3..d50caf38f 100644 --- a/FruitBox_Sequencer/main.py +++ b/FruitBox_Sequencer/main.py @@ -42,11 +42,11 @@ step_pixel = [9, 8, 7, 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] step_col = [WHITE, RED, YELLOW, GREEN, AQUA, BLUE, PURPLE, BLACK] -def prog_mode(i): - cpx.play_file(audio_files[i]) - step_note[step] = i +def prog_mode(index): + cpx.play_file(audio_files[index]) + step_note[step] = index cpx.pixels[step_pixel[step]] = step_col[step_note[step]] - print("playing file " + audio_files[i]) + print("playing file " + audio_files[index]) while True: From fec32eae660c095916db6cf790bf4378c21e2996 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 16:07:13 +0100 Subject: [PATCH 80/83] Remove unused variables --- Cyber_Flower/main_simple.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Cyber_Flower/main_simple.py b/Cyber_Flower/main_simple.py index 22d3baf3a..986ca2c2e 100644 --- a/Cyber_Flower/main_simple.py +++ b/Cyber_Flower/main_simple.py @@ -149,9 +149,6 @@ for i in range(len(gamma8)): def HSV_to_RGB(h, s, v): - r = 0 - g = 0 - b = 0 if s == 0.0: r = v g = v From f63045e96b3694fcebf34eaf05e24249ed6b6e35 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 16:13:14 +0100 Subject: [PATCH 81/83] Rename variables that have builtin names --- CircuitPy_OTP/main.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/CircuitPy_OTP/main.py b/CircuitPy_OTP/main.py index 6d84a2e23..f3c602831 100644 --- a/CircuitPy_OTP/main.py +++ b/CircuitPy_OTP/main.py @@ -120,11 +120,13 @@ def int_to_bytestring(i, padding=8): # https://github.com/pyotp/pyotp/blob/master/src/pyotp/otp.py -def generate_otp(input, secret, digits=6): - if input < 0: +def generate_otp(int_input, secret_key, digits=6): + if int_input < 0: raise ValueError('input must be positive integer') hmac_hash = bytearray( - HMAC(bytes(base32_decode(secret)), int_to_bytestring(input)).digest()) + HMAC(bytes(base32_decode(secret_key)), + int_to_bytestring(int_input)).digest() + ) offset = hmac_hash[-1] & 0xf code = ((hmac_hash[offset] & 0x7f) << 24 | (hmac_hash[offset + 1] & 0xff) << 16 | From 2d5a67097e96118453b507a494557e097faf0061 Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 16:16:00 +0100 Subject: [PATCH 82/83] Rename unused variable --- Annoy_O_Matic/main.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Annoy_O_Matic/main.py b/Annoy_O_Matic/main.py index b4845a5e2..09782e242 100644 --- a/Annoy_O_Matic/main.py +++ b/Annoy_O_Matic/main.py @@ -34,7 +34,7 @@ ringtone_tempo = 1.6 # suggested Nokia 0.9 , iPhone 1.3 , Rickroll 2.0 def annoy_beep(frequency, length, repeat, rest, interval): - for r in range(repeat): + for _ in range(repeat): piezo.frequency = frequency # 2600 is a nice choice piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(length) # sound on @@ -211,8 +211,8 @@ def annoy_ringtone(ringtone, tempo, interval): def annoy_crickets(repeat, interval): - for i in range(repeat): - for r in range(6): + for _ in range(repeat): + for _ in range(6): piezo.frequency = 8000 # 2600 is a nice choice piezo.duty_cycle = 65536 // 2 # on 50% time.sleep(0.02) # sound on @@ -231,17 +231,17 @@ def annoy_teen_tone(interval): while True: - if annoy_mode is 1: + if annoy_mode == 1: annoy_beep(frequency, length, repeat, rest, interval) - elif annoy_mode is 2: + elif annoy_mode == 2: annoy_doorbell(interval) - elif annoy_mode is 3: + elif annoy_mode == 3: annoy_ringtone(ringtone, ringtone_tempo, interval) - elif annoy_mode is 4: + elif annoy_mode == 4: annoy_crickets(repeat, interval) - elif annoy_mode is 5: + elif annoy_mode == 5: annoy_teen_tone(interval) - elif annoy_mode is 6: + elif annoy_mode == 6: annoy_beep(5000, 0.2, 2, 0.05, 3) annoy_doorbell(3) annoy_ringtone(1, 0.9, 3) From 3149b549380515c89ce62d0428370f8ddf64dd4e Mon Sep 17 00:00:00 2001 From: Craig Richardson Date: Tue, 15 May 2018 16:16:12 +0100 Subject: [PATCH 83/83] Remove unreachable code --- 3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py | 1 - 1 file changed, 1 deletion(-) diff --git a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py index 82a4c771e..6923310ec 100644 --- a/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py +++ b/3D_Printed_LED_Microphone_Flag/3D_Printed_LED_Microphone_Flag.py @@ -130,7 +130,6 @@ def fscale(originalmin, originalmax, newbegin, newend, inputvalue, curve): rangedvalue = newbegin - (pow(normalizedcurval, curve) * newrange) return rangedvalue - return rangedvalue def drawLine(fromhere, to):