Relay RISING triggers GPIO event detect on another pin - python

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#...

Related

Openhab2 exec binding to external rpi using pigpio and gpiozero

Using openhab2 on machine A. Machine B is a RPi which controls a relay.
Using pigpio and gpiozero from machine a to control machine b gpio pins.
Using below script for testing. How can I rewrite this so that the on/off function in openhab will work? as of now it just loops between on and off.
help a noob please
#!/usr/bin/python
# https://gpiozero.readthedocs.io/en/stable/
# https://gpiozero.readthedocs.io/en/stable/api_output.html#outputdevice
import sys
import time
import gpiozero
relay = gpiozero.OutputDevice(18, active_high=False, initial_value=False)
def set_relay(status):
if status:
print("Setting relay: ON")
relay.on()
else:
print("Setting relay: OFF")
relay.off()
def toggle_relay():
print("toggling relay")
relay.toggle()
def main_loop():
while 1:
# then toggle the relay every second until the app closes
toggle_relay()
# wait a second
time.sleep(1)
if __name__ == "__main__":
try:
main_loop()
except KeyboardInterrupt:
# turn the relay off
set_relay(False)
print("\nExiting application\n")
# exit the application
sys.exit(0)

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

Raspberry-pi - DHT11 + Relay trigger

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.

RuntimeError: You must setup() the GPIO channel first

When i execute with sudo python3 program.py and press de switch 1 throws the next exception:
Taking picture...
Picture takeng...
Traceback (most recent call last):
File "main.py", line 21, in <module>
if GPIO.input(switch1):
RuntimeError: You must setup() the GPIO channel first
I use a raspberry cam library and rpi.gpio library for this project. Anyone knows what happend in my code ?
import RPi.GPIO as GPIO
import time
import picamera
# initial config for gpio ports
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# input switches
switch1 = 22
switch2 = 23
switch3 = 24
# setup
GPIO.setup(switch1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# main loop
while True:
if GPIO.input(switch1):
print ("Taking picture...")
with picamera.PiCamera() as camera:
camera.resolution = (1280, 720)
camera.start_preview()
time.sleep(0.5)
camera.capture("test.jpg")
print ("Picture takeng...")
elif GPIO.input(switch2):
print ("Taking video...")
elif GPIO.input(switch3):
print ("Poweroff...")
break
GPIO.cleanup()
The error is telling you that you have not set the pins to work as input and, when you try to access them as so, it fails. I had a similar problem and as far as I see it it should work (you are setting the pins after all).
Try changing GPIO.setmode(GPIO.BCM) to GPIO.setmode(GPIO.BOARD). You will also have to change the pin numbers to the physical ones (yours would be 15, 16 and 18).
I still don't know why, but it did the trick on my code.
You have to give access permission to the /dev/ folder and the mem file.
To do so open the raspberry terminal and enter the commands bellow
sudo chmod -R 777 /dev/ and hit enter
then
sudo chmod -R 777 /dev/mem and hit enter that's it

Categories