0

The following code is meant to create 6 GPIO pins and be able to change the output of each of those pins depending on the letter pressed (I made it a function because I will have to code each letter, but for now it is just "a"). It also has to play a sound file (different for each letter) immediately before sending output signals to the pins.

Please let me know which part of the code you think is making it run so slowly. It takes around 18 seconds to start working after F5 is pressed and there is an about 5 second delay after pressing a for the sound to play.

Sorry if the answer is really obvious. I am new to coding.

import RPi.GPIO as GPIO
import time
import os,sys
import pygame

pygame.init()
pygame.display.set_mode((100,100))

t=True
f=False

'''
pin layout:

p1  p4
p2  p5
p3  p6
'''

def setup(sound,p1,p2,p3,p4,p5,p6):
  os.system('omxplayer -o local '+sound)
  GPIO.setwarnings(False)
  GPIO.setmode(GPIO.BOARD)
  GPIO.setup(7,GPIO.OUT)
  GPIO.setup(11,GPIO.OUT)
  GPIO.setup(12,GPIO.OUT)
  GPIO.setup(13,GPIO.OUT)
  GPIO.setup(15,GPIO.OUT)
  GPIO.setup(16,GPIO.OUT)
  GPIO.output(7,p1)
  GPIO.output(11,p2)
  GPIO.output(12,p3)
  GPIO.output(13,p4)
  GPIO.output(15,p5)
  GPIO.output(16,p6)
  time.sleep(5)
  GPIO.cleanup()
  return;

while True:
  for event in pygame.event.get():
    if event.type==pygame.KEYDOWN:
      if event.key == pygame.K_a:
        setup(sound='tone.mp3',p1=t,p2=f,p3=f,p4=f,p5=f,p6=f)
        print('done')
0

It does take a few seconds for python to fire up. On my RPi Zero, it takes roughly 5 seconds just to blink an LED in a simple script. After everything loads, there is no longer a pause.

Looking at your code, it looks like you call setup() on every keypress, and setup() has a 5 second delay at the end, so that might explain a 5 second delay between key presses. Also, you are doing a lot of things in setup() that probably don't need to be done on every keypress. I'd try moving the omxplayer line into a separate function that just does the minimum required to quickly play the sound and do whatever GPIO changes you need.

  • Alright. Thanks a lot. I tried your answer but there is still a delay. By this, I mean when i press A, after everything has started up, it takes a couple seconds to start playing the audio file. Is there anything that plays audio faster? Faster response to a key-press is always better. – Larry Mar 24 '17 at 16:54
  • 1
    I'd check the pygame docs to see if you could avoid calling omxplayer externally. Loading up and starting an external app will definitely add some overhead, and if my memory serves, pygame had that functionality built in. Definitely make sure that time.sleep(5) isn't in your playback function! – bobstro Mar 24 '17 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.