To test the new Enviro PHAT color sensor, i though i could couple it with the Unicorn-PHAT with its RGB-LEDs.
You need:
- 2 Raspberry Pi (i tested with two pi zero)
- Enviro PHAT
- Unicorn PHAT
Install the needed libraries, put both Raspberry Pi on a network.
Script for the Unicorn-PHAT Raspberry Pi (server side):
import SocketServer
import unicornhat as u
u.set_layout(u.PHAT)
def set_color(r, g, b):
for x, y in [divmod(i, 4) for i in xrange(32)]:
u.set_pixel(x, y, int(r), int(g), int(b))
u.show()
class ColorHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
data = self.request[0].strip()
r, g, b = data.split(",")
set_color(r, g, b)
except Exception, e:
print "Bullshit received!", e
server = SocketServer.UDPServer(("0", 2000), ColorHandler)
server.serve_forever()
Code on the Enviro-PHAT Raspberry Pi (client):
import envirophat as e
import time, socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);sock.connect(("server-hostname-or-ip", 2000))
while True:
time.sleep(0.1)
sock.sendall("{0},{1},{2}\n".format(*e.light.rgb()))
sock.close()
Now try some light of different colors on the Enviro-PHAT and see the unicorn PHAT illuminate in that color.
Note that the code is very simple, you should not catch all Exception
s without proper handling on the server side and provide some reaonable socket closing on the client side (like catching KeyboardInterrupt
). But it works for basic testing of both hats.