To check the status of relay using interrupt in raspberry pi - python

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

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.

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.

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.

Python callback issue with GPIO on raspberry

I'm an absolute python newbie and this is my first raspberry project. I try to build a simple music player in which every input button loads a different album (8 albums) and 3 buttons to control playback (next, pause, last).
To load the music I use a USB drive which, as soon as it is connected automatically triggers the copy process.
The buttons are debounced with a callback function. Everything works great, except that after new music is loaded with the USB drive the buttons don't work anymore.
Most likely it is a simple programming issue which I - as a beginner - just don't see.
This is the code to work with two buttons:
#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
import pyudev
from time import sleep
from mpd import MPDClient
from socket import error as SocketError
# Configure MPD connection settings
HOST = 'localhost'
PORT = '6600'
CON_ID = {'host':HOST, 'port':PORT}
#Configure Buttons
Button1 = 25
Button2 = 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(Button1, GPIO.IN)
GPIO.setup(Button2, GPIO.IN)
client = MPDClient()
#Function to check if USB is connected
def checkForUSBDevice(name):
res = ""
context = pyudev.Context()
for device in context.list_devices(subsystem='block', DEVTYPE='partition'):
if device.get('ID_FS_LABEL') == name:
res = device.device_node
return res
#Function to load music from USB
def loadMusic(client, con_id, device):
os.system("mount "+device+" /music/usb")
os.system("/etc/init.d/mpd stop")
os.system("rm -r /music/mp3/*")
os.system("cp -r /music/usb/* /music/mp3/")
os.system("umount /music/usb")
os.system("rm /music/mpd/tag_cache")
os.system("/etc/init.d/mpd start")
os.system("mpc clear")
os.system("mpc ls | mpc add")
os.system("/etc/init.d/mpd restart")
#Function to connect to MPD
def mpdConnect(client, con_id):
try:
client.connect(**con_id)
except SocketError:
return False
return True
#Function to load an Album
def loadAlbum(number):
mpdConnect(client, CON_ID)
if client.status()["state"] == "play" or client.status()["state"] == "pause": client.stop()
os.system("mpc clear")
os.system("mpc ls "+str(number)+" | mpc add")
client.play()
client.disconnect()
#Callback Function
def buttonPressed(channel):
if channel == Button1:
print('Button 1 HIT')
loadAlbum(1)
elif channel == Button2:
print('Button 2 HIT')
loadAlbum(2)
def main():
GPIO.add_event_detect(Button1, GPIO.RISING, callback=buttonPressed, bouncetime=200)
GPIO.add_event_detect(Button2, GPIO.RISING, callback=buttonPressed, bouncetime=200)
# This function just creates an endless loop which does
# nothing, in order for the button detection to work
try:
flag = 0
while flag == 0:
device = checkForUSBDevice("MUSIC") # MUSIC is the name of my thumb drive
if flag == 1:
flag = 0
else:
flag = 0
if device != "":
# USB thumb drive has been inserted, new music will be copied
print('USB erkannt, Musik wird kopiert.', device)
loadMusic(client, CON_ID, device)
print('Musik wurde kopiert, USB kann entfernt werden!', device)
while checkForUSBDevice("MUSIC") == device:
sleep(1.0)
print('USB wurde entfernt.')
loadAlbum(1)
except KeyboardInterrupt:
GPIO.cleanup()
if __name__ == "__main__":
main()
Hope anyone can help me on this?
Matthias
Here is what did the trick for me. Probably it's not the best solution but it seams to do the trick.
Only the main function was changed. Changes are highlighted at the beginning of the line with a comment.
def main():
GPIO.add_event_detect(Button1, GPIO.RISING, callback=buttonPressed, bouncetime=200)
GPIO.add_event_detect(Button2, GPIO.RISING, callback=buttonPressed, bouncetime=200)
# This function just creates an endless loop which does
# nothing, in order for the button detection to work
try:
flag = 0
while flag == 0:
device = checkForUSBDevice("MUSIC") # MUSIC is the name of my thumb drive
if flag == 1:
flag = 0
else:
flag = 0
if device != "":
# USB thumb drive has been inserted, new music will be copied
print('USB erkannt, Musik wird kopiert.', device)
# Stop the callback before loading the files from the USB:
GPIO.remove_event_detect(Button1)
GPIO.remove_event_detect(Button2)
loadMusic(client, CON_ID, device)
print('Musik wurde kopiert, USB kann entfernt werden!', device)
while checkForUSBDevice("MUSIC") == device:
sleep(1.0)
print('USB wurde entfernt.')
loadAlbum(1)
# Recall the main function
main()
except KeyboardInterrupt:
GPIO.cleanup()
The reason that the buttons dont work any more is because you are still in the callback function - so it cant get triggered again. The solution is to use the callback function to simply set a flag and have the main waiting loop detect the flag and do the playing. But note that playing is probably blocking so that the main loop will also have stopped for the duration.

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