Skip to content

Commit

Permalink
Shakeup examples and fix README links.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gadgetoid committed Nov 23, 2023
1 parent 8134ffa commit 6fbac41
Show file tree
Hide file tree
Showing 28 changed files with 147 additions and 209 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
![Blinkt!](blinkt-logo.png)

[![Build Status](https://travis-ci.com/pimoroni/blinkt.svg?branch=master)](https://travis-ci.com/pimoroni/blinkt)
[![Build Status](https://img.shields.io/github/actions/workflow/status/pimoroni/blinkt/test.yml?branch=main)](https://github.com/pimoroni/blinkt/actions/workflows/test.yml)
[![Coverage Status](https://coveralls.io/repos/github/pimoroni/blinkt/badge.svg?branch=master)](https://coveralls.io/github/pimoroni/blinkt?branch=master)
[![PyPi Package](https://img.shields.io/pypi/v/blinkt.svg)](https://pypi.python.org/pypi/blinkt)
[![Python Versions](https://img.shields.io/pypi/pyversions/blinkt.svg)](https://pypi.python.org/pypi/blinkt)
Expand Down
2 changes: 1 addition & 1 deletion examples/1d_tetris.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,5 @@ def main():
update()


if __name__ == '__main__':
if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

@anvil.server.callable
def set_color(color_string):
print("Setting LEDs to {}".format(color_string))
print(f"Setting LEDs to {color_string}")
c = Color(color_string)
blinkt.set_all(c.red * 255, c.green * 255, c.blue * 255, 1.0)
blinkt.show()
Expand All @@ -45,7 +45,7 @@ def clear():


# Display the URL where you can control the Blinkt LEDS
print("Control your Blinkt LEDs at {}".format(app.origin))
print(f"Control your Blinkt LEDs at {app.origin}")
print("Press Ctrl-C to exit")

# Keep the script running until the user exits with Ctrl-C
Expand Down
10 changes: 2 additions & 8 deletions examples/binary_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
MODE_HOUR = 0
MODE_MIN = 1
MODE_SEC = 2
MODE_NAMES = {MODE_HOUR: 'Hour mode',
MODE_MIN: 'Minute mode',
MODE_SEC: 'Seconds mode'}
MODE_NAMES = {MODE_HOUR: "Hour mode", MODE_MIN: "Minute mode", MODE_SEC: "Seconds mode"}

time_to_stay_in_mode = 3
time_in_mode = 0
Expand Down Expand Up @@ -62,11 +60,7 @@
blinkt.set_pixel(7 - x, r, g, b)

blinkt.show()
print('{h:2d}:{m:02d}:{s:02d}; mode: {mode}; time in mode: {tim}'.format(h=h,
m=m,
s=s,
mode=MODE_NAMES[mode],
tim=time_in_mode))
print(f"{h:2d}:{m:02d}:{s:02d}; mode: {MODE_NAMES[mode]}; time in mode: {time_in_mode}")

time_in_mode += 1
if time_in_mode == time_to_stay_in_mode:
Expand Down
4 changes: 2 additions & 2 deletions examples/binary_clock_meld.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import blinkt

print('Hour = Red, Minute = Green, Second = Blue')
print("Hour = Red, Minute = Green, Second = Blue")

blinkt.set_clear_on_exit()

Expand All @@ -16,7 +16,7 @@
t = localtime()
h, m, s = t.tm_hour, t.tm_min, t.tm_sec

print('{h:2d}:{m:02d}:{s:02d}'.format(h=h, m=m, s=s))
print(f"{h:2d}:{m:02d}:{s:02d}")

blinkt.clear()

Expand Down
23 changes: 9 additions & 14 deletions examples/blinkt_thermo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,35 @@
# Data from OpenWeatherMap
# show_graph function adapted from cpu_temp.py

from sys import exit
from time import sleep

try:
import requests
except ImportError:
exit('This script requires the requests module\nInstall with: sudo pip install requests')
raise ImportError("This script requires the requests module\nInstall with: python3 -m pip install requests")

import blinkt

# Grab your API key here: http://openweathermap.org
# List of city ID city.list.json.gz can be downloaded here http://bulk.openweathermap.org/sample/
API_KEY = ''
CITY_ID = ''
API_KEY = ""
CITY_ID = ""

url = 'http://api.openweathermap.org/data/2.5/weather'
url = "http://api.openweathermap.org/data/2.5/weather"

temp = 0


def update_weather():
global temp
payload = {
'id': CITY_ID,
'units': 'metric',
'appid': API_KEY
}
payload = {"id": CITY_ID, "units": "metric", "appid": API_KEY}
try:
r = requests.get(url=url, params=payload)
temp = r.json().get('main').get('temp')
print('Temperture = ' + str(temp) + ' C')
temp = r.json().get("main").get("temp")
print("Temperture = " + str(temp) + " C")

except requests.exceptions.ConnectionError:
print('Connection Error')
print("Connection Error")


def show_graph(v, r, g, b):
Expand All @@ -54,7 +49,7 @@ def show_graph(v, r, g, b):
def draw_thermo(temp):
v = temp
v /= 40
v += (1 / 8)
v += 1 / 8
show_graph(v, 255, 0, 0)


Expand Down
3 changes: 1 addition & 2 deletions examples/candle.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import colorsys
import time
from sys import exit

try:
import numpy as np
except ImportError:
exit('This script requires the numpy module\nInstall with: python3 -m pip install numpy')
raise ImportError("This script requires the numpy module\nInstall with: python3 -m pip install numpy")

import blinkt

Expand Down
12 changes: 6 additions & 6 deletions examples/cheerlights.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
try:
import requests
except ImportError:
exit('This script requires the requests module\nInstall with: sudo pip install requests')
exit("This script requires the requests module\nInstall with: python3 -m pip install requests")

import blinkt

Expand All @@ -14,20 +14,20 @@

def hex_to_rgb(col_hex):
"""Convert a hex colour to an RGB tuple."""
col_hex = col_hex.lstrip('#')
col_hex = col_hex.lstrip("#")
return bytearray.fromhex(col_hex)


while True:
r = requests.get('http://api.thingspeak.com/channels/1417/field/2/last.json', timeout=2)
r = requests.get("http://api.thingspeak.com/channels/1417/field/2/last.json", timeout=2)
json = r.json()

if 'field2' not in json:
print('Error {status}: {error}'.format(status=json['status'], error=json['error']))
if "field2" not in json:
print(f"Error {json['status']}: {json['error']}")
time.sleep(5)
continue

r, g, b = hex_to_rgb(json['field2'])
r, g, b = hex_to_rgb(json["field2"])

for i in range(blinkt.NUM_PIXELS):
blinkt.set_pixel(i, r, g, b)
Expand Down
3 changes: 1 addition & 2 deletions examples/cpu_load.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env python
import time
from sys import exit

try:
import psutil
except ImportError:
exit('This script requires the psutil module\nInstall with: sudo apt install python3-psutil')
raise ImportError("This script requires the psutil module\nInstall with: sudo apt install python3-psutil")

import blinkt

Expand Down
4 changes: 2 additions & 2 deletions examples/cpu_temp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@


def get_cpu_temperature():
process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
process = Popen(["vcgencmd", "measure_temp"], stdout=PIPE)
output, _error = process.communicate()
output = output.decode()

pos_start = output.index('=') + 1
pos_start = output.index("=") + 1
pos_end = output.rindex("'")

temp = float(output[pos_start:pos_end])
Expand Down
11 changes: 5 additions & 6 deletions examples/extra_examples/drum_hits.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,27 @@
import glob
import os
import time
from sys import exit

try:
import drumhat
except ImportError:
exit('This script requires the drumhat module\nInstall with: sudo pip install drumhat')
raise ImportError("This script requires the drumhat module\nInstall with: python3 -m pip install drumhat")

try:
import pygame
except ImportError:
exit('This script requires the pygame module\nInstall with: sudo pip install pygame')
raise ImportError("This script requires the pygame module\nInstall with: python3 -m pip install pygame")

import blinkt

DRUM_FOLDER = 'drums2'
DRUM_FOLDER = "drums2"

BANK = os.path.join(os.path.dirname(__file__), DRUM_FOLDER)

pygame.mixer.init(44100, -16, 1, 512)
pygame.mixer.set_num_channels(16)

files = glob.glob(os.path.join(BANK, '*.wav'))
files = glob.glob(os.path.join(BANK, "*.wav"))
files.sort()

samples = [pygame.mixer.Sound(f) for f in files]
Expand All @@ -40,7 +39,7 @@ def show_all(state):
def handle_hit(event):
samples[event.channel].play(loops=0)
show_all(1)
print('You hit pad {}, playing: {}'.format(event.pad, files[event.channel]))
print(f"You hit pad {event.pad}, playing: {files[event.channel]}")


def handle_release():
Expand Down
5 changes: 2 additions & 3 deletions examples/extra_examples/pov_rainbow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import time
from colorsys import hsv_to_rgb
from sys import exit

try:
from envirophat import motion
except ImportError:
exit('This script requires the envirophat module\nInstall with: sudo pip install envirophat')
raise ImportError("This script requires the envirophat module\nInstall with: python3 -m pip install envirophat")

import blinkt

Expand Down Expand Up @@ -42,7 +41,7 @@ def millis():
if len(t) > 0:
total_time = float(sum(t)) / len(t)

offset = ((millis() - t_start) / total_time)
offset = (millis() - t_start) / total_time

# offset += direction * 10

Expand Down
3 changes: 1 addition & 2 deletions examples/extra_examples/spirit_level.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python

import time
from sys import exit

try:
from envirophat import motion
except ImportError:
exit('This script requires the envirophat module\nInstall with: sudo pip install envirophat')
raise ImportError("This script requires the envirophat module\nInstall with: python3 -m pip install envirophat")

import blinkt

Expand Down
6 changes: 3 additions & 3 deletions examples/eyedropper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@

import blinkt

print('Press Ctrl-C to quit.')
print("Press Ctrl-C to quit.")

try:
while True:
x, y = pyautogui.position()
im = ImageGrab.grab(bbox=(x - 1, y, x, y + 1))
rawrgb = list(im.getdata())
rgb = str(rawrgb)[2:-2]
r, g, b = rgb.split(', ')
r, g, b = rgb.split(", ")
blinkt.set_all(r, g, b)
blinkt.set_brightness(1)
blinkt.show()
time.sleep(0.01)
except KeyboardInterrupt:
print('\n')
print("\n")
16 changes: 8 additions & 8 deletions examples/kitt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@

import blinkt # so we can talk to our blinkt lights!

BRIGHTNESS = 0.2 # range is 0.0 to 1.0
MAX_COLOUR = 255 # range is 0 to 255
DECAY_FACTOR = 1.5 # how quickly should MAX_COLOUR fade? (1.5 works well)
TIME_SLEEP = 0.04 # seconds (0.04 works well)
BRIGHTNESS = 0.2 # range is 0.0 to 1.0
MAX_COLOUR = 255 # range is 0 to 255
DECAY_FACTOR = 1.5 # how quickly should MAX_COLOUR fade? (1.5 works well)
TIME_SLEEP = 0.04 # seconds (0.04 works well)

PIXELS = blinkt.NUM_PIXELS # usually 8, can use fewer if you like!

blinkt.clear # make all pixels blank / black
blinkt.clear # make all pixels blank / black
blinkt.set_brightness(BRIGHTNESS)

brightpixel = -1
direction = 1

print('Hello Michael.\nHow are you today?')
print("Hello Michael.\nHow are you today?")

while True:
# decay all pixels
Expand All @@ -31,12 +31,12 @@

if brightpixel >= PIXELS - 1:
brightpixel = PIXELS - 1
direction = - abs(direction)
direction = -abs(direction)
if brightpixel <= 0:
brightpixel = 0
direction = abs(direction)

blinkt.set_pixel(brightpixel, MAX_COLOUR, 0, 0)

blinkt.show() # draw the lights!
blinkt.show() # draw the lights!
time.sleep(TIME_SLEEP) # wait a bit before working on next frame
12 changes: 6 additions & 6 deletions examples/larson_hue.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
start_time = time.time()

while True:
delta = (time.time() - start_time)
delta = time.time() - start_time

# Offset is a sine wave derived from the time delta
# we use this to animate both the hue and larson scan
Expand All @@ -34,13 +34,13 @@
sat = 1.0

val = max_val - (abs(offset - x) * FALLOFF)
val /= float(max_val) # Convert to 0.0 to 1.0
val = max(val, 0.0) # Ditch negative values
val /= float(max_val) # Convert to 0.0 to 1.0
val = max(val, 0.0) # Ditch negative values

xhue = hue # Grab hue for this pixel
xhue = hue # Grab hue for this pixel
xhue += (1 - val) * 10 # Use the val offset to give a slight colour trail variation
xhue %= 360 # Clamp to 0-359
xhue /= 360.0 # Convert to 0.0 to 1.0
xhue %= 360 # Clamp to 0-359
xhue /= 360.0 # Convert to 0.0 to 1.0

r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(xhue, sat, val)]

Expand Down
3 changes: 1 addition & 2 deletions examples/mem_load.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python

import time
from sys import exit

try:
import psutil
except ImportError:
exit('This script requires the psutil module\nInstall with: python3 -m pip install psutil')
raise ImportError("This script requires the psutil module\nInstall with: python3 -m pip install psutil")

import blinkt

Expand Down
Loading

0 comments on commit 6fbac41

Please sign in to comment.