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

Python code to power on/off your MM-lcd and to mqtt motion

  • Hello to everyone, this is my first post in the forum, please take that into consideration 😃
    So I have MM working on a pi zero w, I’ve modded the lcd to be able to power on and off the backlight using one of the Gpio using a python code on startup.
    The problem is that I’m having some problems, recently I’ve implemented in the same python code the sending of an mqtt message status every time the PIR is trigged ON or goes OFF, the fact is that time by time, let’s say every 24h the pi get stuck…
    This is the code:

    #!/usr/bin/env python
    from time import time, sleep
    import datetime
    import os                 
    import RPi.GPIO as GPIO
    import urlparse
    import paho.mqtt.client as paho
    # Time to wait (in seconds)
    # Setup Gpio
    # GPIO.setwarnings(False)
    GPIO.setup(23, GPIO.IN)         #Output PIR
    GPIO.setup(25, GPIO.OUT)
    # Mqtt
    #mqttc = mosquitto.Mosquitto()
    mqttc = paho.Client()
    url_str = 'mqtt://'
    url = urlparse.urlparse(url_str)
    mqttc.username_pw_set("xxxx", "yyyyyy")
    def sendmqtt(mess):
        print "Send mqtt"
        now =
        mqttc.connect(url.hostname, url.port)
    #   mqttc.publish("pir/kitchen", str(now) + mess)
        mqttc.publish("pir/kitchen", mess)
    while True:
        if i==0:                 #When output from motion sensor is LOW, no movement
            print cttw
            if cttw==0: # Counter has reached zero
                print "Counter is 0"
                GPIO.output(25, False)
                cttw=ttw    # Reset counter
        elif i==1:               #When output from motion sensor is HIGH, movement detected
            print "Motion detected"
            GPIO.output(25, True)

  • I’m a total noob at coding so really every kind of suggestion is appreciated

Log in to reply