3

I have am working on a project where I'm trying to get a Raspberry Pi to play some sounds when triggered by button presses on an Arduino. The command is sent to Raspberry Pi through serial. I used this tutorial to get started: http://blog.makezine.com/2012/10/22/a-halloween-sound-trigger-with-raspberry-pi-and-arduino/

I was able to get it to work as in the tutorial but my final product will be playing a lot more sounds and it will be playing different sounds on button ups and downs. I would like to be able to send commands through the serial similar to the following:

ButtonAPressed
ButtonAReleased
ButtonBPressed
Etc

I modified the tutorial to have my arduino script send 'Serial.write("ButtonAPressed")' and I modified the pertinent portion of the python script to look something like this:

while True:
    try:
        val = serialFromArduino.read()
        if (val != ""):
            print(val)
        if (val == "ButtonAPressed"): 
            soundChannelA.play(soundA) 
        if (val == "ButtonBPressed"):
            soundChannelB.play(soundB)
        if (val == "ButtonBReleased"):
            soundChannelC.play(soundC)
        val = ""
        sleep(.01)
    except KeyboardInterrupt: 
        exit()

The issue I'm having is my Print's are spitting out information similar to the following:

But
tonAPressed
ButtonBPr
essed
ButtonB
Released

So clearly the whole line isn't getting in the buffer before it's getting read. Is there a way I can make sure the whole line from arduino is in the buffer before it gets read? I don't want to increase the sleep because the button presses or press/release could be quite close together. For the sake of readability I would really rather not convert all of my commands to single characters.

1
  • Whats happening inside this serialFromArduino ? Most likely that is not reading the buffer fully or doing some sort of timed dumps.
    – Piotr Kula
    Commented Mar 7, 2013 at 9:17

1 Answer 1

1

This is just a wild guess but you could try adding a newline to the end on the arduino send.

Serial.write("ButtonAPressed\n")

On the python side add it to the == tests as well.

1
  • 1
    This was pretty much it. Turns out the root of my problem was a misunderstanding about what "serialFromArduino" was. I thought it was a python module but it was just the variable name for a standard serial object. That's what I get for copying an example without understanding it. Anyway I added trailing newlines to my send in arduino and my test string in python, set a serial timeout of 1, and am now using readline and it works great. Turns out the trailing newline is required by the way or it will just hang until the timeout. Thanks for the help.
    – William
    Commented Mar 7, 2013 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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