I'm trying to build a Motion Detected play video for my store as a Welcome Introduction, so I'm using a PIR Sensor connected to the raspberry, and here is my code:
import RPi.GPIO as GPIO
import time
import os
import sys
GPIO.setmode(GPIO.BOARD)
PIR_PIN=7
GPIO.setup(PIR_PIN,GPIO.IN)
def MOTION(PIR_PIN):
os.sys("omxplayer -o local -b /home/pi/g1.mp4")
print("My Store Name")
time.sleep(2)
print ("Wating for Customers...")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
My problems comes once the sensors detect a movement, a video should have to be played, but I got the error message: 'Module'object is not callable
Any clue?
Thanks in Advance, Im will really appreciate your help.
Related
I have a kivy app that has multiple screens and widgets. I am using a motion sensor to check if there is motion and if there isn't any motion detected for 1 minute then the rpi reduces the screen's backlight or blanks the screen. Im not sure where I should place the rpi code. does it go inside the App class ?
Pir Module that works really well.
import time
from gpiozero import MotionSensor
import board
import adafruit_dht
import subprocess
def turn_on():
CONTROL = "vcgencmd"
CONTROL_UNBLANK = [CONTROL, "display_power", "1"] subprocess.call(CONTROL_UNBLANK)
def turn_off():
CONTROL = "vcgencmd"
CONTROL_BLANK = [CONTROL, "display_power", "0"] subprocess.call(CONTROL_BLANK)
pir = MotionSensor(4)
dhtDevice = adafruit_dht.DHT22(board.D23)
while True:
if pir.motion_detected:
turn_on()
print("Motion Detected!")
try:
#Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity))
except RuntimeError as error:
# Errors happen fairly often, keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(60.0)
print("sleeping for 1 minute")
else:
turn_off()
print("No Motion Detected!")
So I think I found a proper solution. The idea would be to use threading on the rpi. Its pretty simple to be honest. Here is the link to some code that has a gui but also uses a pir sensor to sense motion and adjust back lighting on the screen.
https://github.com/norrisredhi/kivy/blob/norrisredhi-patch-1/Kivyapp_with_threading_RPI.py
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)
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.
Hi I am trying to make drive recorder by raspberry pi3 and camera module.
Then I am using picamera which is python library that uses the official camera module for development.
Here is a document of picamera.
Basic idea is this.
Record for 10 min and loop this.
If user pushed button that connected to GPIO pin, stop recording.
I thought I can use the callback function to end the recording.
But I couldn't stop camera recording by callback method.
Does anyone tell me my recognition of callback is wrong?
Here is my code.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from time import sleep
from picamera import PiCamera
import os
import sys
import datetime
import RPi.GPIO as GPIO
import os
class driveRecoder():
try:
#Button setup
SWITCH_PIN=21
GPIO.setmode(GPIO.BCM)
GPIO.setup(SWITCH_PIN,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
#Camera setup
camera = PiCamera()
resolution_width = 1920
resolution_height = 1080
record_time=60
camera.resolution = (resolution_width, resolution_height)
camera.framerate = 30
camera.led = False
def shutdown():
print "shutdown"
os.system("sudo shutdown -h now")
#Callback function
def stopRecording():
camera.stop_recording()
print("録画終了")
#I want to power down after stop recording
#GPIO.cleanup()
#shutdown()
GPIO.add_event_detect(SWITCH_PIN,GPIO.FALLING)
GPIO.add_event_callback(SWITCH_PIN,stopRecording)
while True:
try:
print("録画開始")
#setup file name and directory path to save
now = datetime.datetime.now()
dir_name = now.strftime('%Y%m%d')
dir_path = '/home/admini/Video/'+dir_name
file_name = now.strftime('%H%M%S')
#Make each date folder if not exist folder
if not os.path.exists(dir_path):
os.makedirs(dir_path)
os.chmod(dir_path, 0777)
#Recording 10 min the loop
camera.start_recording(dir_path+'/'+file_name+'.h264')
camera.wait_recording(record_time)
camera.stop_recording()
print("録画終了")
sleep(2)
except KeyboardInterrupt:
camera.stop_recording()
break
finally:
pass
print("録画終了")
except KeyboardInterrupt:
print("ctl+c終了")
GPIO.cleanup()
sys.exit(0)
finally:
pass
print("終了")
GPIO.cleanup()
sys.exit(0)
You need to pull this function out of the class for DriveRecorder. I am surprised you aren't seeing an error. I would pull "shutdown" function out, too.
#Callback function
def stopRecording():
camera.stop_recording()
print("録画終了")
#I want to power down after stop recording
#GPIO.cleanup()
#shutdown()
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#...