Search code examples
pythonpygameraspberry-pipyserialqtimer

how to pause reading serial data so I can call a function?


I made a program that receives temperature sensor data from a microcontroller that connected to my Raspberry Pi via serial (USB) i use import serial to connect them. I can print the data already but I want to make like an alerting system if the data is over 35 degree celcius then an audio that says "temperature is over 35" will be played, but if its not over 35 then keep printing the data. the problem with this code is that if I get 35.1 then the next data is 35.4 the audio keep playing but its not finished. so the output audio will be "tempe- temperature is over 35". I want it to be if the data is 35.1 then the audio will play until its finish, then if the next data is over 35 again then the audio will play again, without getting cutoff. I'm a beginner to python and raspberry pi so any help will be appreciated!

here is the code for reading serial data and print to a label

    def readserial(self):
        response=ser.readline().decode('utf-8').rstrip()
        response=float(response)
        if response > 35.00:
            self.label2.setText(str(response))
            self.alarm()
        elif response <= 35.00:
            self.label2.setText(str(response))
            self.timer=QTimer()
            self.timer.timeout.connect(self.readserial)
            self.timer.start(500)

    def alarm(self):
        pygame.mixer.music.load("over.mp3")
        pygame.mixer.music.play()

Solution

  • You can add an if statement for You can pygame.mixer.music.get_busy()

    if not pygame.mixer.music.get_busy(): # returns true if music is playing
        pygame.mixer.music.play()