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()
Related
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.
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)
My project is to take the reading from the PIR sensor and play a song when the person is in front of the sensor but I cannot figure the logic behind this code that I found online and tried modifying it.
What I need to do is:
How do I loop this, omxp.poll() doesn't work :(
Edit: Now It stops but is there a way to loop the process and is there a way to make the script memory efficient
Here is the code:(updated)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from subprocess import Popen
from omxplayer import OMXPlayer
import RPi.GPIO as GPIO
import time
import subprocess
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
song = OMXPlayer('/home/pi/5Seconds.mp3')
try:
print ("Pir Module Test (CTRL+C to exit)")
time.sleep(2)
print("Ready")
active = False
while True:
time.sleep(2)
if GPIO.input(PIR_PIN):
time.sleep(1)
print("Motion detected")
if not active:
active = True
print("Music started")
song.play()
time.sleep(10)
elif active:
print("No motion detected, stop the music")
song.pause()
song.can_control(song)
active = False
if active and song.poll() != None: # detect completion to allow another start
print("Music finished")
active = False
except KeyboardInterrupt:
print ("Quit")
GPIO.cleanup()
Based on your original code, try the following, I have made a few minor changes to the way your script works:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
song_path = '/home/pi/Hillsong.mp3'
try:
print ("Pir Module Test (CTRL+C to exit)")
time.sleep(2)
print("Ready")
active = False
while True:
if GPIO.input(PIR_PIN):
print("Motion detected")
if not active:
active = True
print("Music started")
omxp = Popen(['omxplayer', song_path])
elif active:
print("No motion detected, stop the music")
omxp.terminate()
active = False
if active and omxp.poll() != None: # detect completion to allow another start
print("Music finished")
active = False
time.sleep(5)
except KeyboardInterrupt:
print ("Quit")
GPIO.cleanup()
Note:
while True means loop forever, as such the time.sleep(10) following it would never be executed.
while False will never execute what is inside it, so omxp.terminate() would never be executed.
Use a variable active to indicate if the player is running to avoid multiple starts.
I do not have a Pi to hand so it has not been tested.
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.