Created
March 16, 2018 00:42
-
-
Save illume/83cf4efcfc7988ade95f7dfeaad40171 to your computer and use it in GitHub Desktop.
pygame custom events, arudino serial ports.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Shows how to send custom events with pygame. | |
# AND serial port data (from perhaps an arduino). | |
# It sends the serial data into pygame (with custom events). | |
# The SERIAL event is only posts when it receives a new line. | |
# NOTE: No error correction is done here. Serial data can corrupt. | |
import pygame as pg | |
import serial | |
ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout = 0) | |
serial_buffer = '' | |
# custom event type is an int based on USEREVENT. | |
GIGGLE = pg.USEREVENT + 1 | |
SERIAL = pg.USEREVENT + 2 | |
def send_giggle(): | |
e = pg.event.Event(GIGGLE, something='lalala', giggle=True) | |
pg.event.post(e) | |
_, going = pg.init(), pg.display.set_mode((320,200)) | |
pg.display.set_caption('g key to giggle') | |
while going: | |
# loop whilst there is data to be read from the serial port. | |
serial_data = ser.read() | |
while serial_data: | |
serial_buffer += serial_data | |
# If there is a new line, we send the event. | |
if '\r\n' in serial_buffer: | |
evt = pg.event.Event(SERIAL, line=serial_buffer) | |
pg.event.post(evt) | |
serial_buffer = '' | |
serial_data = ser.read() | |
for e in [pg.event.wait()] + pg.event.get(): | |
if e.type == pg.QUIT: going = False | |
elif e.type == pg.KEYDOWN and e.key == pg.K_g: send_giggle() | |
elif e.type == GIGGLE: print('Got a giggle! %s' % e) | |
elif e.type == SERIAL: print('Line from serial: %s' % e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment