I am trying to connect the LDR sensor to IoT by using GPIO pins (pin 4) of Raspberry Pi kit and publish MQTT messages. I am using a laser as a transmitter and the LDR sensor as a receiver, the output signal from LDR sensor is (0 or 1), if something passed through laser line, the output of ldrLDR sensor will be 1, then the code must publish an MQTT message.
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time
import ssl
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)
# Define Variables
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 60
MQTT_TOPIC = "ldr"
MQTT_MSG = "there is a product"
MQTT_HOST = "iot.eclipse.org"
# Define on_publish event function
def on_publish(client, userdata, mid):
print ("Message Published...")
# Initiate MQTT Client
mqttc = mqtt.Client()
# Register publish callback function
mqttc.on_publish = on_publish
# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
print ("Connected Successfully")
mqttc.loop_forever()
#Main Loop
while True
input_value = GPIO.input(4)
if input_value == 1:
mqttc.publish(MQTT_TOPIC,MQTT_MSG,qos=1)
print ("message published")
time.sleep(1)
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time
import ssl
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)
# Define Variables
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 60
MQTT_TOPIC = "ldr"
MQTT_MSG = "there is a product"
MQTT_HOST = "iot.eclipse.org"
# Define on_publish event function
def on_publish(client, userdata, mid):
print ("Message Published...")
# Initiate MQTT Client
mqttc = mqtt.Client()
# Register publish callback function
mqttc.on_publish = on_publish
# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
print ("Connected Successfully")
mqttc.loop_forever()
#Main Loop
while True
input_value = GPIO.input(4)
if input_value == 1:
mqttc.publish(MQTT_TOPIC,MQTT_MSG,qos=1)
print ("message published")
time.sleep(1)