Speak now
Please Wait Image Converting Into Text...
Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Challenge yourself and boost your learning! Start the quiz now to earn credits.
Unlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
General Tech Learning Aids/Tools 2 years ago
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.
Turn Your Knowledge into Earnings.
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?
input_value = GPIO.input(4)
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.
General Tech 9 Answers
General Tech 7 Answers
General Tech 3 Answers
General Tech 2 Answers
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.