class InfoMatrix(object): def __init__(self): self._matrix = Adafruit_RGBmatrix(32, 1) self._font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 12) @staticmethod def _image_draw(): image = Image.new('RGB', (32, 32), 'black') draw = ImageDraw.Draw(image) return image, draw def update_weather(self, temp, percip): image, draw = self._image_draw() draw.text( (1, 0), '{0} f'.format(int(round(temp))), (255, 0, 0), font=self._font) draw.text( (1, 13), percip, (255, 0, 0), font=self._font) self._matrix.Clear() self._matrix.SetImage(image.im.id, 0, 0) def write_bus(self, route, prediction): image, draw = self._image_draw() draw.text((0, 0), '{0}:'.format(route), (255, 0, 0), font=self._font) draw.text((0, 13), prediction, (255, 0, 0), font=self._font) self._matrix.Clear() self._matrix.SetImage(image.im.id, 0, 0)
def main(argv): # init led matrix matrix = Adafruit_RGBmatrix(32, 1) matrix.Clear() # file name inputfile = '' try: opts, args = getopt.getopt(argv, "hi:o:", ["ifile="]) except getopt.GetoptError: print 'test.py -i <inputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg # play print 'Input file is ', inputfile image = Image.open(inputfile) image.load() matrix.SetImage(image.im.id, 0, 1) time.sleep(10.0) matrix.Clear()
def main(): frames = processImage('/home/pi/rpi-matrix-gif/myGIF.gif') matrix = Adafruit_RGBmatrix(32, 1) while True: for f in frames: matrix.SetImage(f.im.id, 0, 0) time.sleep(0.1)
def launch_matrix(message_queue): #setup the matrix and screen buffer matrix = Adafruit_RGBmatrix(height, chain_len) # rows, chain length image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) message_list = [] #initialize the message_list to empty. # Make two message slots (two rows of text) message_slots = [] for y in xrange(0, 2): message_slots.append(MessageSlot(0, y * font_height, StillFrames)) # Set times for frame counting current_time = 0.0 prev_time = 0.0 # Delay frames from when last message was shown to put default up frame_delay = 40 # Frames since last message was displayed frames_since_message = frame_delay while True: # Draw empty background rectangle draw.rectangle((0, 0, width, height), fill=(0, 0, 0)) # Empty the inbound queue while (not message_queue.empty()): message_list.append(message_queue.get()) # Find out if we are displaying anything and draw if we are. displaying_messages = False for message_slot in message_slots: if (message_slot.has_message()): displaying_messages = True message_slot.draw(draw) message_slot.advance() else: if (message_list): message_slot.set_message(message_list.pop()) if displaying_messages: frames_since_message = 0 else: frames_since_message += 1 if (frames_since_message >= frame_delay): draw_default(draw) current_time = time.time() time_delta = (1.0 / fps) - (current_time - prev_time) if (time_delta > 0.0): time.sleep(time_delta) prev_time = current_time # Copy the offscreen buffer to the screen. matrix.SetImage(image.im.id, 0, 0)
class RGB_Matrix(Device): """ Handles output to the Adafruit RGB Matrix """ def __init__(self): self.capabilities(MATRIX_WIDTH, MATRIX_HEIGHT, mode="RGB") # Use Adafruit's RGB Matrix class from rgbmatrix import Adafruit_RGBmatrix self._matrix = Adafruit_RGBmatrix(32, 1) def display(self): self._matrix.SetImage(self.image.im.id) def clear(self): self._matrix.Clear() self.image = Image.new(self.mode, self.size)
def main(): if len(sys.argv) != 2: sys.exit('usage: {} <src_dir>'.format(sys.argv[0])) if not os.path.isdir(sys.argv[1]): sys.exit('{} is not a directory'.format(sys.argv[1])) dir_src = os.path.normpath(sys.argv[1]) images = sorted(list_files_with_ext(dir_src, JPEG)) matrix = Adafruit_RGBmatrix(MATRIX_SIZE, MATRIX_CHAIN) try: while True: for image in images: im = Image.open(image) im.load() matrix.SetImage(im.im.id, 0, 0) time.sleep(SLEEP) except KeyboardInterrupt: pass matrix.Clear()
class AmpView(object): """ This is the Amp View, which displays reciever details on the Adafruit RGB matrix. It's set up for a 32x64 RGB display. """ RED = (255, 0, 0) DIM_RED = (128, 0, 0) GREEN = (0, 255, 0) DIM_GREEN = (0, 128, 0) BLUE = (155, 48, 255) DIM_BLUE = (77, 24, 128) FONT1 = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' FONT2 = '/home/pi/rpi-rgb-led-matrix-master/fonts/5x7.pil' FONT3 = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' PANEL_HEIGHT = 32 PANELS = 2 PANEL_WIDTH = 64 def __init__(self): """ Initialise a new twitter display """ self.logger = logging.getLogger(self.__class__.__name__) self.logger.info("Initialising the Amp View") self.matrix = Adafruit_RGBmatrix(AmpView.PANEL_HEIGHT, AmpView.PANELS) self.__load_fonts() self.volume = "" self.source = "" self.timer = None self.model = None def callback(self, model): """ This is the only public method, the entry point to updating the display.""" self.model = model self.__refresh_display_vol(model.volumne) self.__refresh_display_front_line(model.display) self.__refresh_display_source(model.source) self.__refresh_display_input_res(model.input_resolution) self.__refresh_display_speakers( self.model.input_left_channel, self.model.input_center_channel, self.model.input_right_channel, self.model.input_left_back_channel, self.model.input_right_back_channel, self.model.input_lfe_channel, self.model.output_left_channel, self.model.output_center_channel, self.model.output_right_channel, self.model.output_left_back_channel, self.model.output_right_back_channel, self.model.output_sub_channel) self.timer = Timer(5, self.__dim) self.timer.start() def clear(self): """ Clear the matrix display and reset the timer """ self.logger.debug('Clear called') self.matrix.Clear() self.model = None self.timer = None self.matrix = None def __load_fonts(self): """ Load the fonts that will be used by the display """ self.font1 = ImageFont.truetype(AmpView.FONT1, 10) self.font2 = ImageFont.load(AmpView.FONT2) self.font3 = ImageFont.truetype(AmpView.FONT3, 8) def __refresh_display_vol(self, msg): self.logger.debug("refresh vol: " + msg) self.__clear_region(0) self.__show_text(self.font3, msg, 0, AmpView.BLUE) def __refresh_display_front_line(self, msg): self.logger.debug("refresh front line: " + msg) self.__clear_region(9) self.__show_text(self.font1, msg, 9, AmpView.RED) def __refresh_display_source(self, msg): self.logger.debug("refresh source: " + msg) self.__clear_region(20) self.__show_text(self.font1, msg, 20, AmpView.GREEN) def __refresh_display_input_res(self, msg): self.logger.debug("refresh input resolution: " + msg) self.__clear_region(0, 25, 32, 8) self.__show_text(self.font3, msg, 0, AmpView.BLUE, 25) def __refresh_display_speakers( self, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel): """ The 5.1 channel speaker display """ self.__draw_speakers(8, 1, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel) def __refresh_display_vol_dim(self, msg): """ The db volume display """ self.logger.debug("dim vol: " + msg) self.__clear_region(0) self.__show_text(self.font3, msg, 0, AmpView.DIM_BLUE) def __refresh_display_frontline_dim(self, msg): self.logger.debug("dim front line: " + msg) self.__clear_region(9) self.__show_text(self.font1, msg, 9, AmpView.DIM_RED) def __refresh_display_source_dim(self, msg): self.logger.debug("dim source: " + msg) self.__clear_region(20) self.__show_text(self.font1, msg, 20, AmpView.DIM_GREEN) def __refresh_display_input_res_dim(self, msg): self.logger.debug("dim input resolution: " + msg) self.__clear_region(0, 25, 32, 8) self.__show_text(self.font3, msg, 0, AmpView.DIM_BLUE, 25) def __refresh_display_inputfreq_dim(self, msg): self.logger.debug("dim input frequency: " + msg) #self.clear_region(0,25,32,8) #self.show_text(self.font3, msg, 0, AmpView.DIM_BLUE, 25) def __refresh_display_speakers_dim( self, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel): self.__draw_speakers(8, 1, input_left_channel, input_center_channel, input_right_channel, input_left_back_channel, input_right_back_channel, input_lfe_channel, output_left_channel, output_center_channel, output_right_channel, output_left_back_channel, output_right_back_channel, output_sub_channel) def __clear_region(self, row, col=0, width=64, height=12): image = Image.new("RGB", (width, height), "black") ImageDraw.Draw(image) self.matrix.SetImage(image.im.id, col, row) def __show_text(self, font, msg, row, colour, col=0): msg = msg.strip() image = ImageText(font, msg, colour) self.matrix.SetImage(image.image.im.id, col, row) if len(msg) > 2: if ord(msg[0]) == 5 and ord(msg[1]) == 6: self.__draw_dolby_image(11, 0, colour) if len(msg) > 5: if ord(msg[4]) == 8: self.__draw_prologic_image(11, 26, colour) def __dim(self): self.__refresh_display_vol_dim(self.model.volumne) self.__refresh_display_frontline_dim(self.model.display) self.__refresh_display_source_dim(self.model.source) self.__refresh_display_input_res_dim(self.model.input_resolution) self.__refresh_display_inputfreq_dim(self.model.input_frequency) self.__refresh_display_speakers_dim( self.model.input_left_channel, self.model.input_center_channel, self.model.input_right_channel, self.model.input_left_back_channel, self.model.input_right_back_channel, self.model.input_lfe_channel, self.model.output_left_channel, self.model.output_center_channel, self.model.output_right_channel, self.model.output_left_back_channel, self.model.output_right_back_channel, self.model.output_sub_channel) self.timer.cancel() def __draw_dolby_image(self, row, column, colour): """ draw the dolby double DD image """ image = Image.new("RGB", (12, 10), "black") draw = ImageDraw.Draw(image) draw.line([0, 0, 4, 0], fill=colour) draw.line([0, 0, 0, 6], fill=colour) draw.line([0, 6, 4, 6], fill=colour) draw.line([4, 6, 4, 0], fill=colour) draw.point([3, 1], fill=colour) draw.point([3, 5], fill=colour) draw.line([6, 0, 10, 0], fill=colour) draw.line([6, 0, 6, 6], fill=colour) draw.line([6, 6, 10, 6], fill=colour) draw.line([10, 6, 10, 0], fill=colour) draw.point([7, 1], fill=colour) draw.point([7, 5], fill=colour) self.matrix.SetImage(image.im.id, column, row) def __draw_prologic_image(self, row, column, colour): image = Image.new("RGB", (5, 10), "black") draw = ImageDraw.Draw(image) draw.line([0, 0, 4, 0], fill=colour) draw.line([1, 0, 1, 6], fill=colour) draw.line([0, 6, 4, 6], fill=colour) draw.line([3, 6, 3, 0], fill=colour) self.matrix.SetImage(image.im.id, column, row) def __draw_speakers(self, row, column, l, c, r, lb, rb, lfe, output_l, output_c, output_r, output_lb, output_rb, output_sub): """ Draw the speakers using on pixel each. It's configured for 5.1 layout """ image = Image.new("RGB", (14, 3), "black") draw = ImageDraw.Draw(image) if l: draw.point([0, 0], fill=(25, 25, 112)) if c: draw.point([1, 0], fill=(25, 25, 112)) if r: draw.point([2, 0], fill=(25, 25, 112)) if lb: draw.point([0, 1], fill=(25, 25, 112)) if rb: draw.point([2, 1], fill=(25, 25, 112)) if lfe: draw.point([3, 1], fill=(25, 25, 112)) if output_l: draw.point([6, 0], fill=(25, 25, 112)) if output_c: draw.point([7, 0], fill=(25, 25, 112)) if output_r: draw.point([8, 0], fill=(25, 25, 112)) if output_lb: draw.point([6, 1], fill=(25, 25, 112)) if output_rb: draw.point([8, 1], fill=(25, 25, 112)) if output_sub: draw.point([9, 1], fill=(25, 25, 112)) self.matrix.SetImage(image.im.id, column, row)
class Skeeball: buttons = 0 score = 0 highscore = 0 balls = 0 BUTTON = { 'B1000L': int("0001", 16), 'B1000R': int("0002", 16), 'B500': int("0004", 16), 'B400': int("0008", 16), 'B300': int("0010", 16), 'B200': int("0020", 16), 'B100': int("0040", 16), 'BRET': int("0080", 16), 'SELECT': int("0100", 16), 'START': int("0200", 16), 'SCORED': int("003F", 16), 'ANY': int("FFFF", 16) } MODE = {'ATTRACT': 0, 'POST': 1, 'GAME': 2} def __init__(self): self.__initSerial() self.game_mode = self.MODE['ATTRACT'] self.matrix = Adafruit_RGBmatrix(32, 2, 3) self.image = Image.new("RGB", (96, 64)) self.draw = ImageDraw.Draw(self.image) font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 14) self.draw.text((20, 10), "LOADING", font=font, fill=(255, 60, 5)) self.draw.text((18, 30), "SKEEBALL", font=font, fill=(255, 60, 5)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id, 0, 0) time.sleep(1) def __initSerial(self): if True: self.serial = serial.Serial(port='/dev/arduino', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=.1, rtscts=False, dsrdtr=False) #self.serial=None def __drawScore(self): font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 14) self.draw.rectangle([(0, 0), (96, 64)], fill=(0, 0, 0)) self.draw.text((20, 10), "Score", font=font, fill=(255, 60, 5)) self.draw.text((18, 30), str(self.score), font=font, fill=(255, 60, 5)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id, 0, 0) def __updateButtons(self): self.serial.write("B") buttons = self.serial.read(2) if buttons != None and buttons != '': print buttons.encode('hex') self.buttons = int(buttons.encode('hex'), 16) def __releaseBalls(self): self.serial.write("R\n") def __isPressed(self, button): return self.buttons & button def __start(self): self.score = 0 self.balls = 6 self.game_mode = self.MODE['GAME'] self.__releaseBalls() def __update(self): self.__updateButtons() if self.game_mode == self.MODE['ATTRACT']: if self.__isPressed(self.BUTTON['START']): self.__start() return if self.game_mode == self.MODE['POST']: self.__doPost() if self.game_mode == self.MODE['GAME']: self.__doGame() def __doGame(self): if self.balls > 0: if self.__isPressed(self.BUTTON['B1000L']) or self.__isPressed( self.BUTTON['B1000R']): self.score += 1000 if self.__isPressed(self.BUTTON['B500']): self.score += 500 if self.__isPressed(self.BUTTON['B400']): self.score += 400 if self.__isPressed(self.BUTTON['B300']): self.score += 300 if self.__isPressed(self.BUTTON['B200']): self.score += 200 if self.__isPressed(self.BUTTON['B100']): self.score += 100 if self.__isPressed(self.BUTTON['BRET']): self.balls -= 1 if self.__isPressed(self.BUTTON['SCORED']): self.__drawScore() else: self.game_mode = self.MODE['POST'] self.__startPost() def __startPost(self): return def loop(self): while 1: self.__update() time.sleep(.2)
import ImageDraw import time import ImageFont from rgbmatrix import Adafruit_RGBmatrix import ImageOps import pickle with open("emojiemotionlist.txt", "rb") as fp: # Unpickling emojilist = pickle.load(fp) print(len(emojilist)) # print(emojilist[0:10]) matrix = Adafruit_RGBmatrix(32, 4) num = len(emojilist) rep = 4 im = Image.new("RGB", (32 * num * rep, 32)) size = 32, 32 for n in range(0, rep * num, 1): print(emojilist[n % num]) emoji = Image.open(emojilist[n % num]) emoji.thumbnail(size, Image.ANTIALIAS) emoji.load() # Must do this before SetImage() calls im.paste(emoji, (n * 32 + 1, 0)) print(im.size[0]) for n in range(128, -im.size[0], -1): # Scroll R to L matrix.SetImage(im.im.id, n, 0) time.sleep(0.002)
import Image import ImageDraw import ImageColor import time from rgbmatrix import Adafruit_RGBmatrix # Rows and chain length are both required parameters: matrix = Adafruit_RGBmatrix(32, 1) matrix.SetWriteCycles(4) # Bitmap example w/graphics prims image = Image.new("RGB", (32, 32)) # Can be larger than matrix if wanted!! draw = ImageDraw.Draw(image) #color = PIL.ImageColor.rgb(0,0,255) draw.rectangle((0,0,31,31),fill=(0,255,255),outline=1) draw.line((0,0,31,31),fill=1) matrix.SetImage(image.im.id,0,0) time.sleep(2.0) print "---------------" matrix.Clear() image = Image.open("circle_gif.gif") image.load() matrix.Fill((0,0,255)) image0 = Image.new("RGB", (32,32)) image1 = Image.new("RGB", (32,32)) image2 = Image.new("RGB", (32,32)) image0 = Image.open("Targeting1.png") image0.load() image1 = Image.open("Targeting2.png") image1.load() image2 = Image.open("Targeting3.png")
import Image import ImageDraw import time from rgbmatrix import Adafruit_RGBmatrix import cv2 import time matrix = Adafruit_RGBmatrix(32, 2) cap = cv2.VideoCapture('./FTPDownload/video.mp4') total_frame = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT) count = 1 while (True): _, frame = cap.read() cv2.waitKey(24) pil_im = Image.fromarray(frame) matrix.SetImage(pil_im.im.id, 0, 0) count += 1 if count >= total_frame - 1: cap.set(1, 1) count = 1 matrix.Clear() cap.release() # Rows and chain length are both required parameters: # Bitmap example w/graphics prims # Draw some shapes into image (no immediate effect on matrix)... # Then scroll image across matrix... # 8-bit paletted GIF scrolling example #
import socket import os from telecommande import * from rgbmatrix import Adafruit_RGBmatrix socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 8192)) #couple (hostname,port) matrix = Adafruit_RGBmatrix(32,2) logo = Image.open("logo.png") logo.load() matrix.SetImage(logo.im.id,0,0) while True: socket.listen(0) #Nombre de connexions en attente client, address = socket.accept() print "{} connected".format( address ) try: thread_telecommande = Telecommande() thread_telecommande.setDaemon(True) thread_telecommande.matrix = matrix thread_telecommande.logo = logo quit = 0 thread_telecommande.start() while quit == 0: message = client.recv(255) #Taille buffer message = message.replace('\n', '') donnees = message.split(",") thread_telecommande.name = donnees[0] thread_telecommande.debut = donnees[1] thread_telecommande.fin = donnees[2]
print(im2.size) im1.thumbnail(size, Image.ANTIALIAS) im1.load() im2.thumbnail(size, Image.ANTIALIAS) im2.load() print(im1.size) # Must do this before SetImage() calls # matrix.Fill(0x6F85FF) # Fill screen to sky color # for m in range(1,6,1): # for n in range(128, -image.size[0], -1): # Scroll R to L # matrix.SetImage(image.im.id, n, 0) # time.sleep(0.025) # matrix.Clear() for m in range(1, 6, 1): for n in range(128, 64, -1): # Scroll R to L matrix.SetImage(im1.im.id, n, 0) matrix.SetImage(im2.im.id, -(n - 128 + im2.size[0]), 0) time.sleep(0.025) matrix.Clear() for n in range(64, 128, 1): # Scroll R to L matrix.SetImage(im1.im.id, n, 0) matrix.SetImage(im2.im.id, -(n - 128 + im2.size[0]), 0) time.sleep(0.025) matrix.Clear() # # 24-bit RGB scrolling example. # # The adafruit.png image has a couple columns of black pixels at # # the right edge, so erasing after the scrolled image isn't necessary. matrix.Clear()
# Rows and chain length are both required parameters: matrix = Adafruit_RGBmatrix(32, 1) # Bitmap example w/graphics prims image = Image.new("1", (32, 32)) # Can be larger than matrix if wanted!! draw = ImageDraw.Draw(image) # Declare Draw instance before prims # Draw some shapes into image (no immediate effect on matrix)... draw.rectangle((0, 0, 31, 31), fill=0, outline=1) draw.line((0, 0, 31, 31), fill=1) draw.line((0, 31, 31, 0), fill=1) # Then scroll image across matrix... for n in range(-32, 33): # Start off top-left, move off bottom-right matrix.Clear() # IMPORTANT: *MUST* pass image ID, *NOT* image object! matrix.SetImage(image.im.id, n, n) time.sleep(0.05) # 8-bit paletted GIF scrolling example image = Image.open("cloud.gif") image.load() # Must do this before SetImage() calls matrix.Fill(0x6F85FF) # Fill screen to sky color time.sleep(1) for n in range(32, -image.size[0], -1): # Scroll R to L matrix.SetImage(image.im.id, n, 0) time.sleep(0.025) # 24-bit RGB scrolling example. # The adafruit.png image has a couple columns of black pixels at # the right edge, so erasing after the scrolled image isn't necessary. matrix.Clear()
hexa = os.listdir( "/home/pi/Documents/LEDMatrix/rpi-rgb-led-matrix-master/Color")[0] curDate = datetime.datetime.now().strftime("%H:%M") image = Image.new("1", (30, 12)) # Can be larger than matrix if wanted!! image = image.convert("RGBA") draw = ImageDraw.Draw(image) # Declare Draw instance before prims draw.text((0, 0), curDate, fill=hex_to_rgb(hexa)) # draw.text((0, 0), curDate, fill=(int(float(r)), int(float(g)), int(float(b)))) # matrix.Clear() matrix.SetImage(image.im.id, 0, 0) for n in range(1, len(gifDirectory) + 1): pict = Image.open( "/home/pi/Documents/LEDMatrix/rpi-rgb-led-matrix-master/gifDirectory/" + gif + "/" + str(n) + ".jpg") pict.load() # Must do this before SetImage() calls matrix.SetImage(pict.im.id, 31, 0) time.sleep(gifSpeed * 0.01) del pict del draw del image else: matrix.Clear()
class Skeeball: buttons = 0 score = 0 highscore = 0 balls = 0 BUTTON = { 'B1000L': int("0001",16), 'B1000R': int("0002",16), 'B500': int("0004",16), 'B400': int("0008",16), 'B300': int("0010",16), 'B200': int("0020",16), 'B100': int("0040",16), 'BRET': int("0080",16), 'SELECT': int("0100",16), 'START': int("0200",16), 'SCORED': int("003F",16), 'ANY': int("FFFF",16) } MODE = { 'ATTRACT': 0, 'POST': 1, 'GAME': 2 } FONTS = { 'Score': ImageFont.truetype("fonts/GameCube.ttf", 20), 'GameOver': ImageFont.truetype("fonts/GameCube.ttf", 16), 'Balls': ImageFont.truetype("fonts/GameCube.ttf", 16), } def __init__(self): #self.__initSerial() self.game_mode = self.MODE['ATTRACT'] self.matrix = Adafruit_RGBmatrix(32,2,3) self.image = Image.new("RGB", (96, 64)) self.draw = ImageDraw.Draw(self.image) image = Image.open("imgs/penis.png") image.load() # Must do this before SetImage() calls self.matrix.SetImage(image.im.id,0,0) time.sleep(5) self.__start() def __initSerial(self): if True: self.serial = serial.Serial( port='/dev/arduino', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=.1, rtscts=False, dsrdtr=False ) #self.serial=None def __drawScore(self): font = self.FONTS['Score'] self.draw.rectangle([(0, 0), (96, 64)],fill=(0,0,0)) self.draw.text((34, 05), "%02d" % self.balls,font=self.FONTS['Balls'],fill=(0,255,50)) self.draw.text((12, 25), "%04d" % self.score ,font=font,fill=(100,0,255)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id,0,0) def __updateButtons(self): self.serial.write("B") buttons = self.serial.read(2) if buttons != None and buttons != '': print buttons.encode('hex') self.buttons = int(buttons.encode('hex'), 16) def __releaseBalls(self): self.serial.write("R\n") def __isPressed(self,button): return self.buttons & button def __start(self): self.score = 0 self.balls = 6 self.game_mode = self.MODE['GAME'] #self.__releaseBalls() def __update(self): #self.__updateButtons() if self.game_mode == self.MODE['ATTRACT']: if self.__isPressed(self.BUTTON['START']): self.__start() return if self.game_mode == self.MODE['POST']: self.__doPost() if self.game_mode == self.MODE['GAME']: self.__doGame() def __doGame(self): self.score += 150 self.balls-=1 self.__drawScore() if self.balls > 0: if self.__isPressed(self.BUTTON['B1000L']) or self.__isPressed(self.BUTTON['B1000R']): self.score += 1000 if self.__isPressed(self.BUTTON['B500']): self.score += 500 if self.__isPressed(self.BUTTON['B400']): self.score += 400 if self.__isPressed(self.BUTTON['B300']): self.score += 300 if self.__isPressed(self.BUTTON['B200']): self.score += 200 if self.__isPressed(self.BUTTON['B100']): self.score += 100 if self.__isPressed(self.BUTTON['BRET']): self.balls-=1 if self.__isPressed(self.BUTTON['SCORED']): self.__drawScore() else: self.game_mode = self.MODE['POST'] self.__startPost() def __startPost(self): font=self.FONTS['GameOver'] self.draw.rectangle([(0, 0), (96, 64)],fill=(0,0,0)) self.draw.text((8, 2), "GAME",font=font,fill=(255,0,0)) self.draw.text((14, 16), "OVER",font=font,fill=(255,0,0)) self.draw.text((10,32), "%04d" % self.score,font=self.FONTS['Score'],fill=(255,200,10)) self.matrix.Clear() self.matrix.SetImage(self.image.im.id,0,0) time.sleep(5) return def __doPost(self): return def loop(self): while 1: self.__update() #time.sleep(.2) time.sleep(1)
class ThreadingExample(object): """ Threading example class The run() method will be started and it will run in the background until the application exits. """ def __init__(self, interval=3): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval self.channel_data = dict() self.histogram_data = list() self.showlight = False for i in chanlookup: self.channel_data[i] = dict() # Rows and chain length are both required parameters: if args.nolights is False: self.matrix = Adafruit_RGBmatrix(16, 1) # use a bitmap font if args.nolights is False: self.font = ImageFont.load("rpi-rgb-led-matrix/fonts/4x6.pil") if args.nolights is False: self.font2 = ImageFont.load("rpi-rgb-led-matrix/fonts/5x7.pil") thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): """ Method that runs forever """ counter = 0 switchval = 1 while True: if self.showlight is True: if args.ratio is False: self.flash_state_summary() else: if switchval == 1: self.ratio_summary() elif switchval == 2: self.histogram_summary() else: self.flash_state_summary() #if args.verbose is True: if args.verbose is True: print self.get_state_summary() if args.verbose is True: print time.time() time.sleep(0.5) counter += 1 if (counter / switchval) >= 20: if switchval == 1: switchval = 2 elif switchval == 2: switchval = 3 else: switchval = 1 counter = 0 pass def histogram_summary(self): if args.nolights is False: scaled_hist = scale16(proc_hist_3(self.histogram_data)) self.matrix.Clear() for idx, val in enumerate(scaled_hist): #print(idx, val) for i in range(15): if i + 1 <= val: self.point(idx, 16 - (i + 1), 50, 50, 200) else: self.point(idx, 16 - (i + 1), 0, 0, 0) def ratio_summary(self): summary = self.get_state_summary() strand = 0 single = 0 if "strand" in summary.keys(): strand = int(summary["strand"]) if "good_single" in summary.keys(): single = int(summary["good_single"]) print "Seen Good Single", single total = strand + single if strand == 0: percentage = 0 else: percentage = (strand / total) * 100 perc = "%.1f" % percentage texttowrite1 = str(strand) + "/" + str(total) texttowrite2 = str(perc) + "%" color1 = "blue" color2 = "blue" if perc <= 90.0: color2 = "red" if strand <= 256: color1 = "red" self.write_text_inst_two(str(texttowrite1), color1, str(texttowrite2), color2) def write_text_inst_two(self, message1, color1, message2, color2): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message1, font=self.font, fill=color1) draw.text((0, 9), message2, font=self.font2, fill=color2) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) def flash_state_summary(self): for key, value in self.channel_data.items(): #print key,value (r, g, b) = (0, 0, 0) try: (r, g, b) = colourlookup[value["state"]] except: pass (x, y) = chanlookup[int(key)] self.point(x, y, r, g, b) def get_state_summary(self): state_dict = dict() for key, value in self.channel_data.items(): #print value,type(value) try: if value["state"] in state_dict: state_dict[value["state"]] += 1 else: state_dict[value["state"]] = 1 except: pass #print(key, len([item for item in value if item])) return state_dict def logitem(self, channel, state): self.channel_data[channel]["state"] = state def point(self, x, y, r, g, b): if args.nolights is False: if args.brightness is True: self.matrix.SetPixel(x, y, int(r / 3), int(g / 3), int(b / 3)) else: self.matrix.SetPixel(x, y, r, g, b) else: if args.verbose is True: print "would do:", x, y, r, g, b def write_text_inst(self, message, color): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message, font=self.font, fill=color) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) def write_text(self, message, color, showtime): if args.nolights is False: image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), message, font=self.font, fill=color) self.matrix.Clear() self.matrix.SetImage(image.im.id, 1, 0) time.sleep(showtime) self.matrix.Clear() def write_time(self, color): if args.nolights is False: timestring = time.strftime("%H:%M:%S", time.gmtime()) image = Image.new("1", (320, 200)) image = image.convert("RGBA") draw = ImageDraw.Draw(image) draw.text((0, 0), timestring, font=self.font, fill=color) #self.matrix.Clear() self.matrix.SetImage(image.im.id, 0, 0)
', ' * (maxPredictions - 1) + # comma+space between times '')[0] # 1 space + 'minutes' at end w = font.getsize('No Predictions')[0] # Label when no times are available if w > tileWidth: # If that's wider than the route tileWidth = w # description, use as tile width. predictList = [] # Clear list for s in stops: # For each item in stops[] list... predictList.append(predict(s)) # Create object, add to predictList[] w = font.getsize(s[1] + ' ' + s[3])[0] # Route label if (w > tileWidth): # If widest yet, tileWidth = w # keep it tileWidth += 6 # Allow extra space between tiles time.sleep(5) while True: for prediction in predictList: print(prediction.predictions) image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) draw.text((0, -2), text=prediction.data[1] + '', font=font, fill=routeColor) times = ','.join( [str(sec / 60) for sec in prediction.predictions[0:3]]) draw.text((0, 6), text=times, font=font, fill=routeColor) matrix.SetImage(image.im.id, 0, 0) sleep(5) matrix.Clear # HI AGAIN!!
import Image import ImageDraw import time import ImageFont from rgbmatrix import Adafruit_RGBmatrix # Rows and chain length are both required parameters: matrix = Adafruit_RGBmatrix(32, 4) font = ImageFont.load_default() font = ImageFont.truetype("DejaVuSerif.ttf", size=14) text1 = "Reading status" img = Image.new('RGB', (128, 32)) d = ImageDraw.Draw(img) d.text((0, 0), text1, fill=(0, 200, 200), font=font) matrix.SetImage(img.im.id, 0, 0) time.sleep(0.2) text2 = "." img = Image.new('RGB', (128, 32)) d = ImageDraw.Draw(img) d.text((0, 0), text2, fill=(0, 200, 200), font=font) for m in range(1, 6, 1): for n in range(106, 120, 3): matrix.SetImage(img.im.id, n, 0) time.sleep(0.3) time.sleep(2) matrix.Clear()
class RGBMatrixDisplay: def __init__(self): self.curFileName = "" self.matrix = None self.alloc_matrix() self.font = Font() self.font.setColor(1,255,1) self.num = 0 thread.start_new_thread(self.keythread,()) def alloc_matrix(self): self.matrix = Adafruit_RGBmatrix(32, 2) def free_matrix(self): self.matrix.Clear() self.matrix = None def checkExtension(self, filename, extension): file_len = len(filename) ext_len = len(extension) + 1 if str.upper(filename[file_len - ext_len:]) == "." + str.upper(extension): return True else: return False def keythread(self): serv = MSGserver("localhost", 5000) serv.listen() self.num = 0 while True: data = serv.recv() if data == "start": self.num = 1 elif data == "key": self.num +=1 elif data == "end": self.num = 0 elif data == "err": sys.exit() def show(self): global playFileName self.curFileName = playFileName while True: if self.checkExtension(self.curFileName,"mp4") or self.checkExtension(self.curFileName,"avi"): cap = cv2.VideoCapture(self.curFileName) total_frame = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT) count = 1 while (True): if self.curFileName != playFileName: self.curFileName = str(playFileName) break _, frame = cap.read() cv2.waitKey(24) pil_im = Image.fromarray(frame) self.matrix.SetImage(pil_im.im.id, 0, 0) # draw combo combo = self.num if combo >0: s = str(combo) sl = len(s) x_start_pos =32-int((sl*6)/2.0) for index,n in enumerate(s): self.font.drawNumber(self.matrix,x_start_pos+(index*6),13,int(n)) else: pass count += 1 if count >= total_frame - 1: cap.set(1, 1) count = 1 cap.release()
timeind = [] maxhast = 0.01 breakpoint1 = 100 breakpoint2 = 50 for n in range(1, len(pos) - breakpoint1, 1): timeind.append(maxhast / len(pos) * n) for n in range(len(pos) - breakpoint1, len(pos) - breakpoint2): timeind.append(maxhast / len(pos) * (len(pos) - (breakpoint1 - 1))) for n in range(len(pos) - breakpoint2, len(pos) + 1, 1): timeind.append(maxhast / len(pos) * (len(pos) - (breakpoint2 - 1))) print(len(pos)) print(len(timeind)) # print(timeind[-100:-1]) for n in range(0, len(pos), 1): matrix.SetImage(im.im.id, 0, pos[n]) time.sleep(timeind[n]) matrix.Clear() matrix.SetImage(im.im.id, 0, pos[-1]) time.sleep(1) print(font.getsize(text[0])) for n in range(18, 40): font = ImageFont.truetype("DejaVuSerif.ttf", size=n) text = names[-2] if (font.getsize(text)[0] > 128) or (font.getsize(text)[1] > 28): stopsize = n - 1 matrix.Clear() break txt = Image.new("RGB", (128, 29)) d = ImageDraw.Draw(txt) d.text((0, 0), text, (random.randint(0, 255), random.randint(