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
Related
Using DHT22 sensor, display LCD 16x2 and raspberry pi to collect temperature and humidity value.Please help me out with this error.Thanks in advance
import drivers # Imports Custom LCD Display Driver
import socket # Imports socket function
import struct # Imports structure function
import fcntl # Imports networking function
import time # Imports time function
import os # Imports Operating System function
import re # Imports Reg Ex function
from time import sleep # Imports sleep function from time module
import Adafruit_DHT
DHT = 4
disp = drivers.Lcd() # Initializes LCD Display
def tempcpu(): #Defines "tempcpu"
for _ in range(5): # Sets up timer
cputemp = os.popen("vcgencmd measure_temp").readline()
celsius = re.sub("[^0123456789\.]", "", cputemp)
h,t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, DHT)
disp.lcd_display_string("CpuRpi: {}C".format(celsius), 1)
disp.lcd_display_string("T={0:0.1f}C H={1:0.1f}%".format(t,h), 2 )
sleep(1) # Sleeps for one second before restarting loop
while True: # Forever loop
tempcpu() # Calls "tempcpu"
disp.lcd_clear() # Clears the LCD Display
except KeyboardInterrupt: # If interrupted by the keyboard ("Control" + "C")
disp.clear() #clear the lcd display
sleep(1) #sleeps 1 second
disp.backlight(0) #Turn Off Backlight
# Exits the python interpreter
exit()
Error :
disp.lcd_display_string("T={0:0.1f}C H={1:0.1f}%".format(t,h), 2 )
type Error:unsupported format string passed to NoneType.format
I can reproduce your error with the following line (or similarly if t is the one set to None):
h = None,
t = 1
str_to_be_printed = "T={0:0.1f}C H={1:0.1f}%".format(t,h)
The method Adafruit_DHT.read_retry returned None. It probably happens when failing to read the sensor values. Maybe there is an error in your circuit, or the sensor is faulty.
More complete example on https://www.programcreek.com/python/example/92777/Adafruit_DHT.read_retry
I am fairly new to Python and Computer Vision but I've managed to setup a basic script to open my CCTV camera's at home. It works great but I have a slight issue is is that it loops over each camera one after the other, so instead of the camera image updating every second, it updates around every 5 seconds - the time it takes to complete a loop.
What I want is to be able to use multiprocessing / multi threading so that when I call the function for each of my cameras it open ins a new pool, running parallel to each other, therefore updating each camera every second.
As you can see in the below code I call each of the cameras using the same function, but with different argurments. I've read up on Process and have tried a few variations but I don't seem to be able to get it working.
I'm sure its a simple one and it would be great if someone could point me in the right direction.
Here's the code:
# import libraries
from threading import Thread
import imutils
import cv2, time
import argparse
import numpy as np
import datetime
from imutils.video import WebcamVideoStream
from multiprocessing import Process
stream = WebcamVideoStream('rtsp://mylink1./' ).start() # To open any valid video file stream/network stream. In this case 'test.mp4' file.
stream2 = WebcamVideoStream('rtsp://mylink2./' ).start()
stream3 = WebcamVideoStream('rtsp://mylink3./' ).start()
stream4 = WebcamVideoStream('rtsp://mylink4./' ).start()
stream5 = WebcamVideoStream('rtsp://mylink5./' ).start()
def checkimage(stream,camname):
global lastmessage
try:
frame = stream.read()
(h, w) = frame.shape[:2]
cv2.imshow(camname, frame)
print('[INFO]Checked ' + str(camname) + ' at ' + datetime.datetime.now().strftime("%H:%M:%S") + '...')
except AttributeError:
pass
# infinite loop
while True:
checkimage(stream,"Back Door Camera")
checkimage(stream2,"Conservatory Camera")
checkimage(stream3,"Front Door Camera")
checkimage(stream4,"Garage Camera")
checkimage(stream5,"Shed Camera")
key = cv2.waitKey(1) & 0xFF
# check for 'q' key-press
if key == ord("q"):
if 'q' key-pressed break out
break
cv2.destroyAllWindows()
# close output window
stream.stop()
# safely close video stream.
Thanks in advance!
Chris
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 build a keypad activated sensor with a Raspberry Pi and Python. Everything seems to go well but after a few minutes and several keypad entries, the Pi has a total crash and switches off immediately - no error messages pop up.
The script will continously wait for a keypad entry and if the code is correct, switch on a sensor, if it's not you have to try again. If the sensor is activated you have to put in the correct numbers to avoid an alarm being triggered after 30s)
Could anyone point me in the direction of what might be the problem? Here are the things I've tried so far without success
1) Exchange Pi to new Pi 2
2) Different OS, both NOOBS and Raspbian Wheezy
3) Different sensor (accelerometer vs IR sensor)
4) Disconnect monitor, keyboard and use SSH connection via Cygwin
5) Get log file until crash - log file was empty after reboot
python bad_script &> full_log.txt
6) Different log file command: causes instant crash and is also empty after reboot:
python script.py >> /logdir/script.py.log 2>&1
The question is: how am I able to crash Linux? If it's a memory problem, isn't there a prevention in linux to stop processed before they appear?
Here is the full script I am running:
import sys
from time import sleep
import threading
import signal
from matrix_keypad import RPi_GPIO1
import RPi.GPIO as GPIO
import smbus
import time
passcode = [1,2,3,4] # this is the correct code you have to enter
kp = RPi_GPIO1.keypad(columnCount = 3)
alarm_active = threading.Event() # shared variable used to control the sensor monitoring thread
alarm_active.clear() # Clear the alarm initially
monitor_thread = None # Global variable used to store the monitoring thread
#Set up all the pins correctio
GPIO.setmode(GPIO.BCM)
PINIR=7
GPIO.setup(7, GPIO.IN) # infrad-sensor
#Now activate the kaypad and listen for keypad inputs
def digit():
r = None
while r == None:
r = kp.getKey()
return r
def get_keycode():
# Function to loop around reading 4 keypresses in a row
# Compare against chosen code
# If match, switch the alarm state
entered = []
while len(entered) < 4:
key = digit()
sleep(0.5)
print key
entered.append( key )
if entered == passcode:
entered = []
print "Code correct"
switch_alarm_state()
else:
# Just clear the keypad buffer if the wrong code went in
# Could say "BAD CODE!" here, or even force immediate alarm perhaps
print "Wrong Code - Try again"
GPIO.output(27, True) # let red LED blink as indicator that code was wrong
time.sleep(1)
GPIO.output(27, False)
entered = []
def switch_alarm_state():
# Function to control the state of the alarm
# If the alarm should be on, run a thread monitoring the sensor
# If the alarm should be off, make sure the thread is stopped
global monitor_thread
if alarm_active.is_set():
# If the alarm is currently set, stop it
print "Alarm was abolished"
GPIO.output(17, False) #switch green LED off
alarm_active.clear() # Signals to the monitor thread that we wish to shut it down
monitor_thread.join() # Wait until the monitor thread has stopped
else:
# Alarm is not currently set, so start the sensor monitor thread going
print "Alarm was activated"
GPIO.output(17, True)
monitor_thread = threading.Thread( target=sensor_monitor )
alarm_active.set()
monitor_thread.start()
def sensor_monitor():
# Function to be run in a separate thread, monitoring the sensor
alarm_timer = None # Variable to hold a timer object that will fire the alarm
while alarm_active.is_set():
#print xrota
if GPIO.input(PINIR):
print "Alarm has been triggered"
if alarm_timer is None:
alarm_timer = threading.Timer( 30.0, fire_alarm )
alarm_timer.start()
sleep(0.5)
# The alarm must have been deactivated to get here
# Stop any outstanding alarms and shutdown
if alarm_timer is not None:
alarm_timer.cancel()
return
def fire_alarm():
# Here you implement the actions to be carried out by an alarm
print "Alarm is send to server"
msg = "Alarm"
publish.single("alarm/demo",msg, hostname="52.17.194.125")
def shutdown_handler( signum, frame ):
# Shut down the child thread nicely
alarm_active.clear()
monitor_thread.join()
if __name__ == '__main__': # This is the Python way to check you are being directly run, and not just imported by another script
signal.signal( signal.SIGINT, shutdown_handler ) # If you stop the script with ctrl+C, make sure it shuts down properly
signal.signal( signal.SIGTERM, shutdown_handler )
try:
while True:
get_keycode()
except KeyboardInterrupt:
GPIO.cleanup()
print "Quit program"
I'm working on making a photo booth running on a Raspberry Pi using Python and OpenCV. I found a great code example of how to capture images from a web cam here. http://joseph-soares.com/programacao/python/python-opencv-salvar-imagem-da-camera-no-disco/
The code that is provided alone works perfect on both the Pi and on my Windows PC. When I start adding code to this I'm having issues. I can no longer see what the web cam is seeing on the Pi and on Windows it is hit or miss. They are both capturing pictures though. In Windows it will actually display the image taken in the frame. If I revert back to the original code, again it works just fine.
I'm basically using a loop to give a count down before the picture is taken and flashing a light on the Arduino to represent the digit output that will be added in. I originally thought it was a memory issue on the Pi but it not working on my desktop is making me think otherwise. Any help would be appreciated.
import time, cv
from datetime import datetime
import pyfirmata
import serial
#board = pyfirmata.Arduino('/dev/ttyACM0')
board = pyfirmata.Arduino('COM7')
#arduino.open()
# start an iterator thread so
# serial buffer doesn't overflow
iter8 = pyfirmata.util.Iterator(board)
iter8.start()
greenLED = board.get_pin('d:13:o')
debug = 1
def captureImage():
snapped = cv.QueryFrame(capture)
cv.SaveImage(datetime.now().strftime('%Y%m%d_%Hh%Mm%Ss%f') + '.jpg', snapped)
if __name__ == '__main__':
capture = cv.CaptureFromCAM(0)
cv.NamedWindow('Webcam')
try:
while True:
for n in range(0, 4):
frame = cv.QueryFrame(capture)
cv.ShowImage('Webcam', frame)
cv.WaitKey(10)
if debug: print "count down"
for i in range (0, 5):
print i
greenLED.write(1)
time.sleep(1)
greenLED.write(0)
time.sleep(0.2)
i+=1
greenLED.write(1)
time.sleep(0.2)
print "Say Cheese"
captureImage()
greenLED.write(0)
if debug: print "Waiting for 5 seconds"
time.sleep(5)
n+=1
break
capture = None
cv.DestroyAllWindows()
board.exit()
except KeyboardInterrupt:
cv.DestroyAllWindows()
board.exit()