I need to Write "pir sensor" motion detection COUNT to text file.
I tried with this code and this is work without writing to text file. when I put write to file it gives an error file = open("textFile.txt", "w")
IndentationError: unindent does not matchanyouter indentation level.
Expected Output is last motion count number in text file.
code is
# Import required Python libraries
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN)
Current_State = 0
Previous_State = 0
# I put Variable= 0 for the motion Count
Variable= 0
try:
print "Waiting for PIR to settle ..."
# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0
print " Ready"
# Loop until users quits with CTRL-C
while True :
# Read PIR state
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1 and Previous_State==0:
# PIR is triggered
start_time=time.time()
print " Motion detected!"
# here I need to write numbers for the text file.
file = open("textFile.txt", "w")
file.write(Variable)
file.close()
Variable+=1
# Record previous state
Previous_State=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
stop_time=time.time()
print " Ready ",
elapsed_time=int(stop_time-start_time)
print " (Elapsed time : " + str(elapsed_time) + " secs)"
Previous_State=0
except KeyboardInterrupt:
print " Quit"
# Reset GPIO settings
GPIO.cleanup()
import RPi.GPIO as GPIO
import time
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
print "PIR Module Test (CTRL-C to exit)"
# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN) # Echo
Current_State = 0
Previous_State = 0
Variable=0
try:
print "Waiting for PIR to settle ..."
# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0
print " Ready"
# Loop until users quits with CTRL-C
while True :
# Read PIR state
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1 and Previous_State==0:
# PIR is triggered
print " Motion detected!"
# Record previous state
Previous_State=1
file = open("textFile.txt", "w")
file.write(Variable)
file.close()
Variable+=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
print " Ready"
Previous_State=0
# Wait for 10 milliseconds
time.sleep(0.01)
except KeyboardInterrupt:
print " Quit"
# Reset GPIO settings
This is my friend's code.
(I believe nothing is wrong with your code but a few Indentation Error(e.g. spacing Error) For that you can use some sort of text editor (I use sublime text)
You need to use a string with file.write, here is an example:
file = open("textfile.txt", "rw+")
file.write(str(Variable))
file.close()
Related
I am trying to count people who break a laser beam (hardware works) and then post to google form.
code:
###################################################
######### People Counter v1-1 ############
###################################################
################################
###Setting up Python Modules####
################################
import RPi.GPIO as GPIO
import os, time
################################
##### Setting up GPIO pins #####
################################
RECEIVER_PIN = 23
################################
######Setting up Counters ######
################################
peoplecount = 0
uploadcount = 0
door = 1 # <- Use this to designate multiple doors for tracking
location = 'Entry' # <- Use this to designate multiple locations for tracking in one form
rpitemp = 'vcgencmd measure_temp | cut -c6-7' # Temperatur vom RPi
def callback_func(channel):
if GPIO.input(channel):
print("Lichtschranke wurde unterbrochen")
## This waits for a specified minute of the hour, checks if anyone has been detected since the last upload, then uploads the data to a Google Form.
# if time.strftime("%M") in ("13", "28", "43", "58") and peoplecount > 0 and uploadcount == 0:
global peoplecount
global uploadcount
if peoplecount > 0 and uploadcount == 0:
try:
url = 'https://docs.google.com/forms/d/e/1FAIpQLSduNOOwMUtpQc5QNFbcwPXQhD0MRppum3kkYHThkFvo0JluQw/formResponse?entry.664100658=%s&entry.1901373746=%s&entry.1382055524=%s&entry.718436324=%s&submit=Senden' % (location, door, peoplecount, rpitemp)
response = br.open(url)
print "People count uploaded with value %s on door %s at %s and RPi Temp %s" % (peoplecount, door, location, rpitemp)
uploadcount = 0
peoplecount = 0
print "values reset"
except:
print "Cannot Access Page"
elif time.strftime("%M") in ("38", "39", "40", "41") and uploadcount == 1:
uploadcount = 0
elif GPIO.input(RECEIVER_PIN) == True:
peoplecount = peoplecount + 1
print "Motion Detected: Door %s at %s on %s. Count is %s" % (door, time.strftime("%H:%M:%S"), time.strftime("%A"), peoplecount)
time.sleep(3)
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RECEIVER_PIN, GPIO.IN)
GPIO.add_event_detect(RECEIVER_PIN, GPIO.RISING, callback=callback_func, bouncetime=200)
try:
while True:
time.sleep(0.5)
except:
# Event wieder entfernen mittels:
GPIO.remove_event_detect(RECEIVER_PIN)
error:
Lichtschranke wurde unterbrochen
Motion Detected: Door 1 at 19:47:22 on Friday. Count is 1
Cannot Access Page
It seems that the variables don't send any data. If I don't send the form with %s it works. Can anybody help me or is there a better method?
I think you are using the Browser module to open the URL. If so you haven't imported the browser module. So that's why it's throwing an exception and printing cannot Access page
from mechanize import Browser
br = Browser()
Install the module using PIP and add this at the start of the code. This should help
Code below is designed so when the motion sensor is triggered it starts recording data from the DHT11. The data is then sent to a site called cayenne for data transfer. The issue is that the data being recorded and sent to cayenne is not being stored into the CSV file that is also created. It successfully prints the titles for each piece of data, however the figures being read are not being printed.
Uses Raspberry Pi 3B+, DHT11 Temperature and Humidity sensor and PIR motion sensor.
import sys
import os
import Adafruit_DHT as dht
import cayenne.client
import RPi.GPIO as GPIO
# Added to deal with RPi 3B+
import platform
import re
import time
from time import strftime
import datetime
#Cayenne authentification info stuff
MQTT_USERNAME="4ff7bed0-f66b-11e8-a08c-c5a286f8c00d"
MQTT_PASSWORD="82e9cd4df60e9a8e864d0f4f80262322ad692068"
MQTT_CLIENT_ID="66751010-f7d6-11e8-898f-c12a468aadce"
client = cayenne.client.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)
# DHT sensor connected to Raspberry Pi to GPIO dhtpin.
dhtpin = 3 #pin03 is BCM2; 2 in BOARD
# Pin for Pir sensor
pirsensor = 17 # BOARD11
#GPIO.setmode(GPIO.BOARD) #for using the WiringPi numbers
GPIO.setmode(GPIO.BCM) #for the Broadcom numbers instead of the WiringPi numbers
#GPIO.setwarnings(False)
GPIO.setup(dhtpin, GPIO.OUT) # Set dhtpin as an output
GPIO.setup(pirsensor,GPIO.IN) #Set pirsensor to input
# Sensor should be set to Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = dht.DHT11
# Set Duration in second between two mesures.
period = 1
# Pir status
state = 0
#Create the log file in CSV format with header columns
with open('dhtpir.csv', 'a+') as f:
f.write(" DATE & TIME \t " + " , \t"+ "% HUMIDITY " + " , " + "T(Celcius)" + " , \t" + " T(Fahrenheit),\n")
while True:
# Note that sometimes you won't get a reading and the results will be null
# (because Linux can't guarantee the timing of calls to read the sensor).
# If this happens try again!
client.loop()
# Pir
time.sleep(0.1)
state = GPIO.input(pirsensor)
if state == 1:
humidity,tempC = dht.read_retry(dht.DHT11, dhtpin)
#Convert from Celcius to Farenheit
tempF = (9.0/5.0)*(tempC)+32
print("GPIO PIR pin %s is %s" % (pirsensor, state))
#Get the data
if humidity is not None and tempC is not None:
# Get the timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d %H:%M:%S")
client.celsiusWrite(1, tempC)
client.luxWrite(2, humidity)
# Print data to the terminal
print('{}'.format(timestamp),'\t Humidity: {0:0.1f}% Temperature: {1:0.1f} C'.format(humidity, tempC) , '({0:0.1f} F)'.format(tempF)), # print temperature in Celcius
# Fill the previously created log wile with the sensor data in csv format
#
with open('dhtpir.csv', 'a+') as f:
f.write('{}'.format(timestamp)+ " , \t" + (repr(humidity))+"%" + " , \t" + str(tempC)+" C" + " , \t" + '{0:0.1f} F,'.format(tempF) + " \n"),
#f.write(timestamp + " , \t" + (repr(humidity))+"%" + " , \t" + str(tempC)+" C" + " , \t" + str(tempF) + " F\n"), # just a different formating output
f.close() # not absolutly needed when using the 'with' syntax
else:
print('Exiting: failed to get reading.\n Try again!')
with open('dhtpir.csv', 'a+') as f:
f.write('{}'.format(timestamp)+ " , \t Exiting: failed to get reading.\n Try again!")
f.close()
sys.exit(1)
# Wait for the period in second between data reading
time.sleep(period)
GPIO.cleanup()
So i'm starting to use hc-sr04 ultrasonic sensors and ran into a problem. I want to read multiple sensors (two for starters) but I get the same distance value on both. Here is the code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Adafruit_BBIO.GPIO as GPIO
import time
def distanceMeasurement(TRIG,ECHO):
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulseStart = time.time()
while GPIO.input(ECHO) == 1:
pulseEnd = time.time()
pulseDuration = pulseEnd - pulseStart
distance = pulseDuration * 17150
distance = round(distance, 2)
return distance
#Configuration
GPIO.setup("P9_15",GPIO.OUT) #Trigger
GPIO.setup("P9_12",GPIO.IN) #Echo
GPIO.setup("P9_11",GPIO.OUT)
GPIO.setup("P9_13",GPIO.IN)
#Security
GPIO.output("P9_11", False)
GPIO.output("P9_15", False)
time.sleep(0.5)
#main Loop
try:
while True:
for i in range(2):
if i == 0:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ",recoveredDistance,"cm"
elif i == 1:
recoveredDIstance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ",recoveredDistance,"cm"
time.sleep(1)
except KeyboardInterrupt:
print "Measurement stopped by user"
GPIO.cleanup()
I get the same reading on both no matter the distance to the object on sensor2, the distance read in sensor1 is what both display; seems that sensor2 is ignored.
Doing some "manual debugging" (i.e. print TRIG, ECHO) I notice the function recives the correct parameters, here is the output to that "debugging":
P9_11
P9_13
Distance1: 20.79 cm
P9_15
P9_12
Distance2: 20.79 cm
P9_11
P9_13
Distance1: 20.13 cm
P9_15
P9_12
I want to use that one fucntion to read all the sensors. Thank you in advance
You print the same result twice, because the second measurement is saved as recoveredDIstance. So recoveredDistance is unchanged. Python is case sensitive.
while True:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ", recoveredDistance, "cm"
recoveredDistance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ", recoveredDistance, "cm"
time.sleep(1)
I am running a Python Program on a Raspberry Pi 3 which I want to log the temperature from a DS18B20 sensor once every 0.25 seconds.
Earlier, when the program was simple and displaying the temperature on shell, it was quite fast and not having issues. Unfortunately due to the program itself now which includes logging to a file, I am getting a log every 2 seconds or 3 seconds only.
How do I ensure the 0.25 second logging interval.
I have shared the code below:
#This program logs temperature from DS18B20 and records it
#Plots the temperature-time plot.
import os
import sys
#import matplotlib.pyplot as plt
from re import findall
from time import sleep, strftime, time
from datetime import *
#plt.ion()
#x = []
#y = []
ds18b20 = ''
def setup():
global ds18b20
for i in os.listdir('/sys/bus/w1/devices'):
if i != 'w1_bus_master1':
ds18b20 = i
# Reads temperature data from the Temp sensor
# This needs to be modified for use with max31855 and K-type thermocouples
def read():
# global ds18b20
location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave'
tfile = open(location)
text = tfile.read()
tfile.close()
secondline = text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature = temperature / 1000
return temperature
#Loop for logging - sleep, and interrupt to be configured.
def loop():
while True:
if read() != None:
print "Current temperature : %0.3f C" % read()
#sleep(0.25)
func()
def write_temp(temperature,file_name):
with open(file_name, 'a') as log:
log.write("{0},{1}\n".format(datetime.now().strftime("%d-%m-%Y %H:%M:%S"),str(temperature)))
arg = sys.argv[1]
filename1 = str(arg) + "-" + datetime.now().strftime("%d-%m-%Y-%H-%M-%S")+".csv"
def func():
temperature = read()
#sleep(0.25)
write_temp(temperature,filename1)
#graph(temperature)
#For plotting graph using MatPlotLib
#Comment out this function during foundry trials to avoid system slowdown
#Check system resource usage and slowdown using TOP or HTOP
#def graph(temperature):
# y.append(temperature)
# x.append(time())
# plt.clf()
# plt.scatter(x,y)
# plt.plot(x,y)
# plt.draw()
#Interrupt from command-line
def destroy():
pass
if __name__ == '__main__':
try:
setup()
func()
loop()
except KeyboardInterrupt:
destroy()
I have commented out sections that I thought to be resource heavy, but still I can't manage anything less than 2 seconds. I am getting results as below:
Output:
27-09-2016 12:18:41,23.0
27-09-2016 12:18:43,23.062
27-09-2016 12:18:46,23.125
27-09-2016 12:18:48,23.187
27-09-2016 12:18:50,23.187
27-09-2016 12:18:53,23.562
27-09-2016 12:18:55,25.875
27-09-2016 12:18:58,27.187
27-09-2016 12:19:00,27.5
Only open the logfile once (and close it on program exit)
Don't always re-read the temperature from the sensor. You call read() way too often.
Reduce general overhead and simplify your calls.
I am not able to completely test this, but something like this sould work:
import os
import sys
import time
from datetime import datetime
def read_temp(dev):
'''Reads temperature from sensor and returns it as float.'''
loc = '/sys/bus/w1/devices/' + dev + '/w1_slave'
with open(loc) as tf:
return float(tf.read().split('\n')[1].split(' ')[9][2:]) / 1000.0
def write_temp(t, logfile):
'''Writes temperature as .3 float to open file handle.'''
logfile.write('{0},{1:.3f}\n'.format(datetime.now().strftime('%d-%m-%Y %H:%M:%S'), t))
def loop(dev, logfile):
'''Starts temperature logging until user interrupts.'''
while True:
t = read_temp(dev)
if t:
write_temp(t, logfile)
print('Current temperature: {0:.3f} °C'.format(t))
sys.stdout.flush() # Flush. Btw, print is time-consuming!
time.sleep(.25)
if __name__ == '__main__':
# Take the first match for a device that is not 'w1_bus_master1'
dev = [d for d in os.listdir('/sys/bus/w1/devices') if d != 'w1_bus_master1'][0]
# Prepare the log filename
fname = str(sys.argv[1]) + "-" + datetime.now().strftime("%d-%m-%Y-%H-%M-%S")+".csv"
# Immediately open the log in append mode and do not close it!
logfile = open(fname, 'a')
try:
# Only pass device and file handle, not the file name.
loop(dev, logfile)
except KeyboardInterrupt:
# Close log file on exit
logfile.close()
I have a problem with my project, I have a little python script to read my gas meter.
Every revolution of digits a small magnet inside the gas meter close to the reed switch makes an input for my raspberry. The problem is when the magnet stops close to the sensor circuit leaving on a high level, which cause false inputs, here my script.
Any suggestion? thanks to all
#!/usr/bin/env python
import time
import datetime
import os.path
import pycurl
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(10, GPIO.RISING, bouncetime = 5000)
def GetGas(arg):
time.sleep(0.01) # need to filter out the false positive of some power fluctuation
if GPIO.input(10) != GPIO.HIGH:
return
gastotale=0
if os.path.isfile('/var/www/myscripts/gas/gastotale.txt'):
file = open("/var/www/myscripts/gas/gastotale.txt","r")
gastotale = float(file.read())
file.close()
gastotale = gastotale+0.01
file = open("/var/www/myscripts/gas/gastotale.txt","w")
file.write(str(gastotale))
file.close()
now = datetime.datetime.now()
fileday = '/var/www/myscripts/gas/'+now.strftime("%Y-%m-%d")+'.txt'
gasday = 0
if os.path.isfile(fileday):
file = open(fileday,"r")
gasday = float(file.read())
file.close()
gasday = gasday+0.01
file = open(fileday,"w")
file.write(str(gasday))
file.close()
oem = pycurl.Curl()
oem.setopt(oem.URL, 'http://emoncms.org/input/post.json?node=0
csv=0,'+str(gasday)+',0,0,'+str(gastotale)+'&apikey=dfb6ccf')
oem.perform()
laststate = 0
while True:
if (GPIO.input(10) == 1 ):
if (laststate == 0):
gastotale = gastotale+0.01
laststate=1
else:
laststate=0
time.sleep(30)