MagicMirror² v2.14.0 is available! For more information about this release, check out this topic.

Trouble with python script for ultrasonic mudule HC-SR04

  • Hi,

    i’ve got some problems with my script (don’t know, where i found it).
    In principle, it works, but after 1 or 2 days, the monitor switches no longer on or off.
    This means that the script is in an undefined state.
    With the logging I wanted to see where it hangs, but that does not really work either.
    Who can help me and optimize the script?

    Thank you

    #Bibliotheken einbinden / Import libs
    from subprocess import call
    import RPi.GPIO as GPIO
    import time
    import logging
    #Einstellungen für das Logging / settings for log options
                        datefmt='%m-%d %H:%M',
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    # tell the handler to use this format
    # add the handler to the root logger
    #GPIO Modus (BOARD / BCM)
    #GPIO Pins zuweisen / set GPIO pins
    GPIO_ECHO = 24
    Monitor_State = 0
    Counter = 0
    TVSERVICE = '/opt/vc/bin/tvservice'
    #Richtung der GPIO-Pins festlegen (IN / OUT) / direction for Pins (in/out)
    Text = (time.strftime("%d.%m.%Y %H:%M:%S")) + (" Messung vom User gestartet")'Gestartet')'ENDE')
    # Bildschirm erst einmal ausschalten :-) / switch off monitor first :-)
    call([TVSERVICE, '-o'])
    def distanz():
        # setze Trigger auf HIGH / set trigger to HIGH
        GPIO.output(GPIO_TRIGGER, True)
        # setze Trigger nach 0.01ms aus LOW / set trigger after 0.01ms low
        GPIO.output(GPIO_TRIGGER, False)
        StartZeit = time.time()
        StopZeit = time.time()
        # speichere Startzeit / remember starttime
        while GPIO.input(GPIO_ECHO) == 0:
            StartZeit = time.time()
        # speichere Ankunftszeit / remember 2'nd time
        while GPIO.input(GPIO_ECHO) == 1:
            StopZeit = time.time()
        # Zeit Differenz zwischen Start und Ankunft / calc difference
        TimeElapsed = StopZeit - StartZeit
        # mit der Schallgeschwindigkeit (34300 cm/s) multiplizieren
        # und durch 2 teilen, da hin und zurueck
        distanz = (TimeElapsed * 34300) / 2
        return distanz
    if __name__ == '__main__':
            while True:
                abstand = distanz()
                if abstand < 120 and Monitor_State == 0:
        'Monitor gestartet')
                  Counter = 0
                  call([TVSERVICE, '-p'])
                elif abstand < 120 and Monitor_State == 1:
                  Ausgabe = " Counter reset " + (" - %.1f cm" % abstand)
                  Counter = 0
                elif abstand >= 120 and Monitor_State == 1 and Counter = 100 and Counter >= 11:
                  Counter = 0
                  call([TVSERVICE, '-o'])
            # Beim Abbruch durch STRG+C resetten / reset after STRG+C
        except KeyboardInterrupt:

  • Module Developer

    @mymirror What is your log saying? I am not that fluent in Python, but in the last elif you assign Counter the value 100. The seems not right.

    Its an Ultrasonic sensor, so do you still hear the clicking noise after 1 or 2 days?

  • @idoodler Thanks for your Reply.
    There is no clicking noise … as i haven’t got any sound device connected.
    But you’re right … the 100 seems to be the problem.
    I didn’t “saw” it … damn.
    I’ll correct this and test it again.


  • Module Developer

    @mymirror Funny story. Last Thursday I found the same issue in the production code of a project I am working on in my real live job, which lead to an really wired issue.

    That was the biggest facepalm ever😩

    And the ultra sonic sensor is clicking itself. The sensor is just a speaker and an microphone. The speaker is clicking constantly and the microphone is picking up the clicking. I am pretty jung, it would drive me crazy if I have to sleep, or stay here the sensor for a long time. But with increasing age humans won’t hear it anymore. But I think animals like cats, dogs, birds, … do hear it better.

    The more you know 🤘

Log in to reply