Skip to content

Instantly share code, notes, and snippets.

@juliancheal
Last active September 22, 2022 01:58
Show Gist options
  • Save juliancheal/09054e0dd9e2baf96860d518c62c2c90 to your computer and use it in GitHub Desktop.
Save juliancheal/09054e0dd9e2baf96860d518c62c2c90 to your computer and use it in GitHub Desktop.
Sonoff light switch toggle via MQTT
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import paho.mqtt.publish as publish
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
button_on = False
while True:
if GPIO.input(10) == GPIO.HIGH and button_on == False:
print(button_on)
button_on = True
print("Button is on!")
publish.single("cmnd/kitchen/power", "on", hostname="your_mqtt_server_ip")
if GPIO.input(10) == GPIO.LOW and button_on == True:
print(button_on)
button_on = False
print("Button is off")
publish.single("cmnd/kitchen/power", "off", hostname="your_mqtt_server_ip")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment