I am new to programming and want to write a code for an infrared sensor to log a timestamp in a .csv file whenever it detects motion. So far I have found code for the detection but now need to add code to specify for it to write an entry in a csv file. Credits for motion detection code: https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
def MOTION(PIR_PIN):
print ("Motion Detected")
print ("PIR Module Test (CTRL+C to exit)")
time.sleep(2)
print ("Ready")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
Next I am trying to add something along the following lines which will then write in two columns TIMESTAMP and "motion detected":
import csv
import strftime
row = [strfttime("%a, %d %b %Y %H:%M:%S"), motion_detected]
with open('datalog.csv', 'a') as f:
w = csv.writer(f)
w.writerow(row)
I have only found ways to write to CSV's from static files so they didn't seem to provide a straightforward answer to my question. So any help in joining these codes or correcting the second would be great!
import RPi.GPIO as GPIO
import time
import csv
import strftime
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
def MOTION(PIR_PIN):
print ("Motion Detected")
print ("PIR Module Test (CTRL+C to exit)")
row = [strfttime("%a, %d %b %Y %H:%M:%S"), 'motion_detected']
with open('datalog.csv', 'a') as f:
w = csv.writer(f)
w.writerow(row)
time.sleep(2)
print ("Ready")
try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
Note: For a string motion detected, you need to add quotaion marks around it(in Python both single and double ones are supported).
Related
I have a working code which tells me, when a laser and a photoresistor will be interrupted.
It would be great, when I can write the information of time into a file and also a counting (i=i+1). So this will be done normally every 2 seconds. A writing after e.g. 500 breaks would be great, because it is running at a rasyperry pi. Less writing would be great.
My output file should be something like this with unix time stamp. So I do not know where do I have to put my counter i = i + 1 at which position and the second question is about the caching issue.
12341234.12341234 1
123478.234789 2
12342134.12341234 3
78989123.12341234 4
Code
import os, time
from time import strftime,localtime
RECEIVER_PIN = 23
def callback_func(channel):
if GPIO.input(channel):
print("Sensor1: Lichtschranke wurde unterbrochen")
date_local = strftime("%Y-%m-%d %H:%M:%S", localtime())
ticks = time.time()
print(date_local)
print(ticks)
with open("/home/pi/Documents/sensors/sensor01_tageswert.txt","a+") as sensor01:
# sensor01.write(date_local)
sensor01.write(str(ticks))
sensor01.write("\n")
# alternativ kann ein Script / Shell Befehl gestartet werden
# os.system("ls")
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.25)
except:
# Event wieder entfernen mittels:
GPIO.remove_event_detect(RECEIVER_PIN)
In this script I am taking the temperature from a DHT11 sensor and parsing the data that another script can read. Everything works except for writing the file to another pc using the path I placed in the f = open part of the script below. Everything works great except that the file doesn't get written or saved.
Any Help?
#!/usr/bin/env python
# encoding: utf-8
import sys
import time
import dht11
import RPi.GPIO as GPIO
#define GPIO 14 as DHT11 data pin
Temp_sensor=14
def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
instance = dht11.DHT11(pin = Temp_sensor)
while True:
#get DHT11 sensor value
result = instance.read()
temp = '{:.0f}'.format(result.temperature * 1.8 + 32)+"°"
# The path to send the txt file to and save is /10.1.1.28/c$/Temperature_RETR/kvoa_temp.txt
if result.is_valid():
print temp
f = open('\\10.1.1.28\c$\Temperature_RETR\new_temp.txt','w')
#f = open('/home/pi/Desktop/new_temp.txt','w')
y = temp
z = str(y)
f.write(z)
f.close()
time.sleep(60) # 60 second delay
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
I'm very new at Python scripting and am working on a script to turn on a fan when my Raspberry Pi3 reaches a specific temp. I've been trying to debug my code all day and found I can't figure out what's wrong. Here is my code:
import os
import sys
import signal
import subprocess
import atexit
import time
from time import sleep
import RPi.GPIO as GPIO
pin = 18
maxTMP = 60
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def setPin(mode):
GPIO.output(pin, mode)
return()
def exit_handler():
GPIO.cleanup()
def FanON():
SetPin(True)
return()
def FanOFF():
SetPin(False)
return()
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
finally:
exit_handler()
Here is my error:
File "/home/pi/Scripts/run-fan.py", line 36
while True:
^
IndentationError: unexpected indent
I've tried to indent every way possible. I need help.
Thanks!
I want to preface this with, you should use four spaces for your indentation. If you do, it will be way, way easier to see problems like the one you have here. If you use an IDE like Spyder or PyCharm, there are settings that automatically highlight indentation problems for you (regardless of how many spaces you want to use).
That said, with your current indentation scheme of one-space-per-indent, you want to replace your bottom block with this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
If you used four spaces instead of one on your original code, it would have looked like this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
There's another problem here, which is that your while True block will currently never exit (maybe you want a break statement somewhere).
Im playing around with a Raspberry Pi, Breakout Board and GSM module. I'm having problems with the serial read data. It seems to be very speratic, with lots of blanks lines and various odd entries that look to be from the terminal (ssh login field prompt). Im simply trying to read the input response for an AT command. Reading the AT Command manual for my GSM, the responses are very specific so I am looking to read just the response im looking for. I am new to serial interfacing like this so any suggestions on best practise would also be appreciated.
#!/usr/bin/python
import time
import serial
import traceback
import netifaces as ni
import RPi.GPIO as GPIO
def resetModule(resetModulePin):
GPIO.output(resetModulePin, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(resetModulePin, GPIO.LOW)
time.sleep(0.1)
def switch(onModulePin):
GPIO.output(onModulePin, GPIO.HIGH)
time.sleep(2)
GPIO.output(onModulePin, GPIO.LOW)
def writeAT():
i = 0
while True:
ser.flushInput()
ser.flush()
out = ''
ser.write('AT\r')
time.sleep(1)
if ser.inWaiting() > 0:
out += ser.read(12)
print 'GSM Is Up'
return out
else:
i += 1
if i > 3:
print 'GSM Down'
print 'Resetting Module'
resetModule(resetModulePin)
time.sleep(5)
print 'Turning On GSM'
switch(onModulePin)
time.sleep(5)
i = 0
try:
resetModulePin = 15
onModulePin = 13
GPIO.setmode(GPIO.BOARD)
GPIO.setup(onModulePin , GPIO.OUT)
GPIO.setup(resetModulePin, GPIO.OUT)
ser = serial.Serial(port='/dev/ttyAMA0', baudrate=115200)
ser.isOpen()
answers = ['yes', 'y']
while True:
out = writeAT()
if out != '':
print out
break
question = raw_input('Do you want to powerdown GSM?:').lower()
if question in answers:
print 'Powering Off GSM'
switch(onModulePin)
ser.close()
GPIO.cleanup()
except KeyboardInterrupt, e:
GPIO.cleanup()
except Exception,e :
traceback.print_exc()
GPIO.cleanup()
OUTPUT (note the blank lines)#Debugging
pi#raspberrypi:~/Desktop $ sudo python Newpy
GSM Down
Resetting Module
Turning On GSM
GSM Is Up
Do you want to powerdown GSM?:
Try ser.write('AAAAAAAT') per this. Apparently the SIM908 on the GSM breakout board tries to automatically detect the baud rate, and you have to give it some extra data in order to do so.
Edit Or try this (post of Tue Nov 25, 2014 11:41 pm) — check the setting of the "charge" jumper on the SIM908.
I am a complete noob using a Raspberry Pi trying to make a program that would track instances of movement with a PIR sensor set on GPIO 4, now the program works without any issues until I try to export the data, long story short, I try gspread, and ubidots and both won't work, even just with a test file. So my next attempt is a simple txt file that will capture time and date, and would write a 1.
this is what I have:
import time
import datetime
import RPi.GPIO as GPIO
sensor = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
prevstate = False
currState = False
while True:
time.sleep(0.1)
prevState = currState
currState = GPIO.input(sensor)
if currState != prevState:
newState = "1" if currState else "0"
print("GPIO pin %s is %s" % (sensor, newState))
try:
values = [datetime.datetime.now(), newState]
with open("test.txt", "a") as text_file:
text_file.write("values")
time.sleep(1.5)
So i don't really don't now why but everything works until I hit the value section, and then I get a unindent error, if I remove from try down i get nothing
I did had before:
except:
print: "cannot open file"
but that really wasn't any issue there. the unindent still comes up.
You have indentation issues. It looks like you started allowing Idle to tab - 8 for indentation then switched to 4. You need to unindent and re-indent everything.
The way you are handling your file, you will overwrite it every time through. You will end up with only one entry in the file. Try opening the file before your main loop:
import time
import datetime
import RPi.GPIO as GPIO
sensor = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
prevstate = False
currState = False
with open("test.txt", "a") as text_file:
while True:
time.sleep(0.1)
prevState = currState
currState = GPIO.input(sensor)
if currState != prevState:
newState = "1" if currState else "0"
print("GPIO pin %s is %s" % (sensor, newState))
try:
values = [datetime.datetime.now(), newState]
text_file.write("values")
except:
print "cannot open file"
get rid of the colon ":" after print, and that sleep after your main loop was not doing anything.
You must always follow the try statement with an except or finally statement, but you mentioned that you also got the error with the try statement? Did that also include the : after print (it shouldn't)? This should work:
try:
values = [datetime.datetime.now(), newState]
with open("test.txt", "a") as text_file:
text_file.write(values)
except:
print: "cannot open file"
Notice that I also removed the quotes around values in text_file.write(values).