Raspberry-pi - DHT11 + Relay trigger - python

I am a complete noob when it comes to Python and the Raspberry Pi unit but I am figuring it out.
I am working on a script to monitor the current temperature of my greenhouse that I am building. When the temp gets to 28C, I would like for it to activate my relay which will turn on the fan. At 26C the relay should turn off.
Build info:
Raspberry Pi 3
dht11 tempurature - GPIO pin 20
single relay board - GPIO pin 21
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from time import sleep
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# Set relay pins as output
GPIO.setup(21, GPIO.OUT)
# read data using pin 20
instance = dht11.DHT11(pin=20)
while True:
result = instance.read()
tempHI = 28
tempLOW = 26
if result >= tempHI
GPIO.output(21, GPIO.HIGH) #turn GPIO pin 21 on
ifels result < tempLOW
GPIO.output(21, GPIO.LOW) #Turn GPIO pin 21 off
time.sleep(1)
The current errors I am getting:
python ghouse.py
File "ghouse.py", line 19
result = instance.read()
^
IndentationError: expected an indented block

For the current error you're facing, keep in mind that Python relies heavily on indentation. It's not like other languages such as C++ and Java that use curly braces to arrange statements.
To fix the indentation in your code, please see below:
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from time import sleep
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# Set relay pins as output
GPIO.setup(21, GPIO.OUT)
# read data using pin 20
instance = dht11.DHT11(pin=20)
while True:
result = instance.read()
tempHI = 28
tempLOW = 26
if result >= tempHI:
GPIO.output(21, GPIO.HIGH) #turn GPIO pin 21 on
ifels result < tempLOW:
GPIO.output(21, GPIO.LOW) #Turn GPIO pin 21 off
time.sleep(1)
In any if, else, elif, for, or while statement, the code that you want to execute must be indented within the statement in order for it to run, or else you will get the error that you are currently seeing.
There are a few more errors in your code but I'll let you figure out the rest! Welcome to programming in Python and using Raspberry Pi.

Related

Need to take the whole python code into a function that can be access from another python file

import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
def privacyfunc():
# Pin Definitions:
led_pin_1 = 7
led_pin_2 = 21
but_pin = 18
# blink LED 2 quickly 5 times when button pressed
def blink(channel):
x=GPIO.input(18)
print("blinked")
for i in range(1):
GPIO.output(led_pin_2, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led_pin_2, GPIO.LOW)
time.sleep(0.5)
mqttBroker="mqtt.fluux.io"#connect mqtt broker
client=mqtt.Client("privacybtn") #create a client and give a name
client.connect_async(mqttBroker)#from the client -connect broker
while True:
client.publish("privacy", x)#publish this random number to the topic called temparature
print("Just published"+str(x)+"to Topc to privacy")#just print random no to topic temparature
break
def main():
# Pin Setup:
GPIO.setmode(GPIO.BOARD) # BOARD pin-numbering scheme
GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT) # LED pins set as output
GPIO.setup(but_pin, GPIO.IN) # button pin set as input
# Initial state for LEDs:
GPIO.output(led_pin_1, GPIO.LOW)
GPIO.output(led_pin_2, GPIO.LOW)
GPIO.add_event_detect(but_pin, GPIO.FALLING, callback=blink, bouncetime=10)
print("Starting demo now! Press CTRL+C to exit")
try:
while True:
x=GPIO.input(18)
print(x)
# blink LED 1 slowly
GPIO.output(led_pin_1, GPIO.HIGH)
time.sleep(2)
finally:
GPIO.cleanup() # cleanup all GPIOs
if __name__ == '__main__':
main()
need to take this whole code into a function that can be accessed from another python file.plz, help me with this coding part.
In the new python file call import module where module is the name of the file. Like led_blink.py would be import led_blink
Then you can call the methods like so:
led_blink.blink(channel)
This is assuming the files are in the same folder.
Easiest way that I do this is to take a .py file and put it in the same directory you created the python script you are working with. From there you can do the following code from The_Python_File import *
Additionally note that the "The_Python_File" is the name of the .py file that contains the function you are trying to call, but you do not include .py when importing the file.

RuntimeError: The GPIO channel has not been set up as an OUTPUT

My aim is to write a Ros node that publishes the data received from a Sonar installed on my robot car. I use a Raspberry Pi 4B as a microcontroller.Therefore i setted first the raspi pin as out/in for the sonar with the bash command:
$ echo 27 > /sys/class/gpio/export; $ echo out >/sys/class/gpio/gpio27/direction and finally i check if the pin 27 has been setted as output $ cat /sys/class/gpio/gpio27/direction that outputs out. Now, when i run the following python code trying to access this pin, i get the following error: RuntimeError: The GPIO channel has not been set up as an OUTPUT.
It looks like the pin isn't setted. Please note:
I didn't use the GPIO.setup() method cause the pin is already setted.
I don't want to use the sudo command on the python script because this has to be runned with the rosrun command
I setted as well the pin 22 as in
I tried all conventions for pin numbering: BCM, WiringPi and BOARD
Python code:
#!/usr/bin/env pyhton
import RPi.GPIO as GPIO
import time
class Sonar:
def __init__(self):
self.period = 0.00001
self.trigger_pin = 27
self.echo_pin = 22
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setup(self.trigger_pin, GPIO.OUT)
#GPIO.setup(self.echo_pin, GPIO.IN)
def activateTrigger(self):
GPIO.output(self.trigger_pin, 1)
time.sleep(self.period)
GPIO.output(self.trigger_pin, 0)
def waitEcho(self, value):
while GPIO.input(self.echo_pin) == value:
pass
def getDistance(self):
measurements = []
measurements_num = 3
for i in range(measurements_num):
# I activate the trigger
self.activateTrigger()
# I am waiting for the echo to turn 1 and i mesure the time ECHO=1
self.waitEcho(0)
start = time.time()
self.waitEcho(1)
stop = time.time()
pulse_len = (stop - start)
distance_cm = pulse_len*17000
measurements.append(distance_cm)
# return the average of the measurements
return int(sum(measurements)/measurements_num)
if __name__=='__main__':
s = Sonar()
print('Getting distance...') ```

raspberry pi addEvent. Runtime error:Failed to add edge detection

I am writing python code on raspberry pi 3. I am registering an event on input channel 21, to check moisture detection. I am getting this error Runtime error:Failed to add edge detection.
My code is:
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
filehandle = open("output.txt", "w") or die ("Could not write out")
if GPIO.input(channel) == 1:
print ("Water Detected!")
filehandle.write("1")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
filehandle.write("0")
GPIO.output(led_output, GPIO.HIGH)
filehandle.close()
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
while True:
time.sleep(5)
When I reboot the Raspberry and run your code it works perfect.
Only after killing the process or CTRL-C keyboard interrupting and running it again the problem/error occurs. I think this has to do with the fact that you exit the program without cleaning up properly...
I got it working in case you exit the running the program with CTRL-C with the code below in which I included a GPIO.cleanup()
However...this unfortunately it does not cover the situation in which you simply kill the running programm...In that case you still need to reboot.
So there is room for improvement.
Please re-insert your own file management commands again.
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
if GPIO.input(channel) == 1:
print ("Water Detected!")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
GPIO.output(led_output, GPIO.HIGH)
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
try:
while True:
#main loop here with some (dummy) code
eg_set_a_dummy_variable = 0
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print ("Program interrupted by CTRL-C")
except:
# this catches ALL other exceptions including errors.
# You won't get any error messages for debugging
# so only use it once your code is working
print ("Other error or exception occurred!")
finally:
# this ensures a clean exit and prevents your
# error "Runtime error:Failed to add edge detection"
# in case you run your code for the second time after a break
GPIO.cleanup()
# credits to:
# https://raspi.tv/2013/rpi-gpio-basics-3-how-to-exit-gpio-programs-cleanly-avoid-warnings-and-protect-your-pi
It is not very clean solution, but you can call GPIO.cleanup() at the start of your script too for case when your process was killed before and GPIO.cleanup() was not called.

To check the status of relay using interrupt in raspberry pi

I am working with a raspberry pi with a relay with the incandescent bulb, buzzer, and button via SSH. The code is in a way that when I press a key from the keyboard the bulb and buzzer should be ON and when I press button both should get OFF. But my button code is not working properly.
And also I want to check the status of the relay using the interrupt and whenever the light on it should be sent a message to the database. But I don't know with interrupts. Below is my code. Please help me. Thanks in advance
import RPi.GPIO as GPIO
import time
in1 = 25 #GPIO25 pin22
buzzer=24 #GPIO24 PIN18
led=8 #GPIO8 PIN24
button=23 #GPIO23 PIN 16
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(in1, GPIO.OUT)
GPIO.setup(buzzer,GPIO.OUT)
GPIO.setup(led,GPIO.OUT)
#GPIO.setup(button,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(in1, False)
GPIO.output(buzzer,False)
GPIO.output(led,False)
try:
GPIO.output(in1,False)
while True:
GPIO.output(in1,False)
# check from database whether it is effective or deffective .currently I have inputted from keyboard
variable=raw_input()
if variable=="a":
m=variable
for x in m:
GPIO.output(in1, True)
time.sleep(0.05)
GPIO.output(in1, False)
time.sleep(0.05)
GPIO.output(buzzer,True)
GPIO.output(led,True)
if in1==True || buzzer==True:
print "messge to database:pending"
#def my_callback(channel):
#if GPIO.input(button) == True:
GPIO.wait_for_edge(button, GPIO.FALLING)
#if variable=="b":
#while 1:
GPIO.output(in1,False)
GPIO.output(led,False)
GPIO.output(buzzer,False)
print "mesage to database:ack completed"
#else:
#pass
#else:
#pass
GPIO.output(in1,False)
except:
GPIO.cleanup()
GPIO.output(in1,False)
If there is any error in my code please help me to rectify that. Thanks

Relay RISING triggers GPIO event detect on another pin

I'm working on two separate projects on my RPi, a relay that drives a lamp (on GPIO 22) and a button that reboots the RPi (on GPIO 23). They both work fine when run alone but if I try to access the pin 22 while the 23 is being monitored the 23 reads a RISING although I have NOT pressed the button.
Here's the code of the program running on 23:
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import os
import sys
def handler (signo):
print ("Rebooting\n")
GPIO.cleanup()
os.system("sudo reboot")
exit()
GPIO.setmode(GPIO.BCM)
pin = 23
GPIO.setup(pin, GPIO.IN,pull_up_down=GPIO.PUD_UP)
try:
GPIO.add_event_detect(pin, GPIO.RISING, callback=handler, bouncetime=800)
while (1):
time.sleep(10)
except KeyboardInterrupt:
print ("Quit")
GPIO.cleanup()
Here's a scheme of the circuit:
scheme.jpg
Does anyone know why this is happening?
I'm trying to access the gpio 22 (the relay) through:
/sys/class/gpio#...

Categories