Good people, it turns out that I am communicating an Arduino UNO with a RaspberryPI and what happens to me is that when an Arduino button is pressed, it sends a simple serial number to RaspberryPi and when it receives it, it will emit a sound, the point is that to avoid annoying people pressing the button many times and locking the system, I have put a delay, but apparently this does not work, since if you press the button many times, it is as if the serial was on hold and if you press the button 5 times, every 10 seconds the sound will be emitted since messages from the serial continue to arrive, up to 5 times you have pressed the button, it is as if it remained in a waiting queue when using sleep(). The question is, how can I modify my code so that it receives 1 message from the serial, every 10s and the other pulses are discarded if they are within those 10s.
Code:
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0]
try:
while True:
read_serial=ser.readline()
print read_serial
playSong()
sleep(10)
Indeed, you have noticed them, no matter how much you do
sleep
, the messages keep coming, so the alternative in reality is to ignore them until the time you want has passed. One way to do it is as follows:We use the function
time.time()
that returns the number of seconds since 1/1/1970 at 00:00:00 and check it against a variablelast_time
that has the same data but from the last execution ofplaySong()
(or0
if it is the first execution). This should print all the received data on the console, but only after 10 seconds will it be executedplaySong()
.Exactly what you mention happens, if data continues to be sent during the delay, they remain in the buffer waiting to be read. In your case, it should be enough to clean all the data present in the buffer and then read while waiting for new ones to arrive. This is done with
flushInput
:When you spend the 10 seconds in your RaspberryPI, have it send a signal to the arduino to indicate that it can now send data, and thus make you receive data when it suits you.