Program with MQTT hanging after starting, LDR processing is not working with no MQTT messages

General Tech Learning Aids/Tools 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

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 ldr sensor will be 1, then the code must publish an MQTT message.

I tried this code:

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)

When I run it I only see the printed output text "successful connection" and I am not seeing any of the expected MQTT messages.

Can you please tell me what's wrong with this code? i create the main loop depending on this idea: input_value = GPIO.input(4) should enter the signal if the value of signal is 1 then it should publish the message what's wrong with my code?

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.