I have a raspberry pi, and on one of the gpio pins I send an impulse, so I have python code to detect an interrupt on this pin, and they have no more than 2 interrupts every second. Now I want to pass this value (total number of interrupts) to the pygame application.
Currently, python code for detecting interrupts records the total number of no. interrupt to the file when an interrupt is detected, and then the pygame application reads that number from the file. So my question is: how can I integrate interrupt detection code into pygame using threads, since I want both pygame applications and interrupt detection code to run in parallel. I read somewhere that pygame is not thread safe.
My code for detecting interrupts:
GPIO.setmode(GPIO.BCM)
count = 0
GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def my_callback(channel):
file = open('hello.txt','w')
global count
count += 1
file.write(str(count))
GPIO.add_event_detect(2,GPIO.BOTH, callback=my_callback)
while True:
print "Waiting for input."
sleep(60)
GPIO.cleanup()
Pygame application code:
pygame.init()
size=[640,640]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Test")
done=False
clock=pygame.time.Clock()
font = pygame.font.SysFont("consolas", 25, True)
frame_rate = 20
frame_count = 0
count = 0
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
pygame.quit()
sys.exit()
f = open("hello.txt", "r")
count = int(f.read())
output_string = "ACTUAL %s" %count
text = font.render(output_string,True,red)
screen.blit(text, [250,420])
frame_count += 1
clock.tick(frame_rate)
pygame.display.flip()
pygame.quit ()