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)
Related
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 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).
I am currently working on setting up my Raspberry Pi to (when triggered by an IR sensor) record twenty second videos, each to a new file.
Currently it is returning this error when movement is detected:
"Traceback (most recent call last):
File "pir_2filenametest2.py", line 57, in
for filename in camera.start_recording('pivid{counter:03}.h264'):
TypeError: 'NoneType' object is not iterable"
I am pretty much brand new to python, so any help would be wonderful.
Here is the code:
# Author : Matt Hawkins
# Date : 21/01/2013
# Import required Python libraries
import RPi.GPIO as GPIO
import time
import picamera
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 7
print "Wilbur Cam! (CTRL-C to exit)"
# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN) # Echo
Current_State = 0
Previous_State = 0
camera = picamera.PiCamera()
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
# Camera begins to record
camera.resolution = (1360, 768)
for filename in camera.start_recording('pivid{counter:03}.h264'):
print('Captured %s' % filename)
time.sleep(20)
camera.stop_recording()
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
GPIO.cleanup()
camera.start_recording does not return a value, it starts the recording, the first arg output is what the video is written to which you could pass as a string or a file object but there is nothing to iterate over:
start_recording(output, format=None, resize=None, splitter_port=1, **options)
Start recording video from the camera, storing it in output.
If output is a string, it will be treated as a filename for a new file which the video will be written to. Otherwise, output is assumed to be a file-like object and the video data is appended to it (the implementation only assumes the object has a write() method - no other methods will be called).
So in your case the filename is 'pivid{counter:03}.h264')
If you want different filenames you could use something like the following:
i = 0 # set i to 0 outside the while
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
# Camera begins to record
camera.resolution = (1360, 768)
camera.start_recording('pivid{}.h264'.format(i)) # pass i to str.format
print('Captured pivid{}.264'.format(i))
i += 1 # increase i
time.sleep(20)
camera.stop_recording()