Recently I’ve discover a new store fill with Raspberry PI goodies – Pimoroni – that has a lot of kits with the Raspberry PI Zero W .  And the Mood Light kit caught my eye !

I’m astonished to why I can’t buy Raspberry PIs Zero W in Portugal… No store has them… I wonder why…

One of the kits I stumble upon was Mood Light – a kit that resembles a light bulb with a Raspberry PI W and a unicorn pHat. The instructions for the assemble of the kit are straightforward and in no time, we have a Raspberry PI light bulb(ish) ready.

One of the things I love is that Pimoroni, for everything pHat has a Python library to work with.

A few years back I discovered Cheerlights – a collaborative IOT project “that allows people’s lights all across the world to synchronize to one color set by twitter” – It’s really interesting. Just imagine that, at any given time, your light turns RED and everybody’s lights also turn RED somewhere in the world. It’s really awesome.

So, I’ve decided to put the cheerlights project into the Mood Light. Part of the code is borrowed from Pimoroni’s examples for the Blinkt! board with a few changes.

In my case, I’ve decided to smooth the transitions of colors, instead of just change from one color to the other.

Here’s the code

import time
from sys import exit
import requests
import unicornhat as uh

# set the layout
uh.set_layout(uh.PHAT)

# brightness
uh.brightness(0.5)

#number of transitions
steps = 20

# If you need proxy
proxies = {
	'http': '<proxy_address>:<port>',
	'https': '<proxy_address>:<port>'
}

def lightitup(oldr, oldg, oldb, r, g, b):
	curStep = 0

	# next we need to calculate the amount to increment (or decrement) 
	# for each individual color (R G B) from the old color to the new color in the number
	# of steps (transistions) defined above
	# ie:
		# old R color value: 146
		# new R color value: 16
		# abs is used to have positive values
		# stepa = abs (16 - 146) / 20 = 100 / 20 = 5
		# Which means, in each one of the 20 transistions, we will remove 5 from 146 - to arrive at 16 in 20 loops
	# This way, we will have a kind of gradient effect when changing colors
	
	stepa = abs(r - oldr) / steps
	stepg = abs(g - oldg) / steps
	stepb = abs(b - oldb) / steps
	
	# This is ugly, but I don't know the terneary operator in Python.
	# every attempt I've made did not work... 
	while (curStep < steps):
		if (oldr > r):
			oldr -= stepa
		else:
			oldr += stepa
		if (oldg > g):
			oldg -= stepg
		else:
			oldg += stepg
		if (oldb > b):
			oldb -= stepb
		else:
			oldb += stepb
		#print ("step: %s %s %s" % (oldr, oldg, oldb))
		for x in range(8):
			for y in range(4):
				uh.set_pixel(x, y, oldr, oldg, oldb)
		uh.show()
		time.sleep(0.01)
		curStep += 1

#borrowed from Pimoroni's Cheerlights from blink examples
def hex_to_rgb(col_hex):
	"""Convert hex color to rgb"""
	col_hex = col_hex.lstrip("#")
	return bytearray.fromhex(col_hex)

# first time, have to set colors
r = 0
b = 0
g = 0
while True:
	 # with proxy
        try:
#               print ("Inside while")
                req = requests.get("http://api.thingspeak.com/channels/1417/field/2/last.json", timeout=5,proxies=proxies)
#               print ("after request")
                # without proxy
                #req = requests.get("http://api.thingspeak.com/channels/1417/field/2/last.json", timeout=2)
                # save old colors
                oldr = r
                oldg = g
                oldb = b
                r, g, b = hex_to_rgb(req.json()["field2"])

        #       print ("old colors: %s %s %s" % (oldr,oldg,oldb))
        #       print ("New colors: %s %s %s" % (r,g,b))

                lightitup(oldr, oldg, oldb, r, g, b)
                # Wait 10s before another request to the API - be friendly
                time.sleep(20)
        #except req.exceptions.RequestException as e:
        #       print (e)
        # except requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout, requests.exceptions.Timeout:
        except requests.exceptions.Timeout:
                time.sleep(10)
                print ("no connection")
                continue

You can check the code at my bitbucket account.

To start the script:

sudo python cheerlights.py

NOTE: We need sudo because the unicorn pHAT requires root to access the device

If you want to put the script starting automatically on Raspberry PI start, just add the following line to the crontab (as root):

sudo crontab -e
@reboot /usr/bin/python /home/pi/cheerlights/cheerlights.py &

 

And here, a small video showing the transitions of colors