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).
Related
I write some automation python script for my rpi project ... here the part of script :
import socket
import sys
import platform
import uuid
import psutil
import subprocess
import os
import RPi.GPIO as GPIO
import time
from subprocess import call
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return (temp.replace("temp=","").replace("'C\n",""))
while True:
print
print 'Hostname:' +socket.gethostname()
print 'Machine :' +platform.machine()
print
print 'CPU Usage:'
print(psutil.cpu_percent())
print
print 'MEM Usage:'
print(psutil.virtual_memory().percent)
print
print 'Disk Usage:'
print(psutil.disk_usage('/').percent)
print
print 'CPU Temp:'
if measure_temp() == "50.1":
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22,GPIO.OUT)
print "Fan on"
GPIO.output(22,GPIO.HIGH)
time.sleep(50)
print "Fan off"
GPIO.output(22,GPIO.LOW)
time.sleep(10)
GPIO.cleanup()
print(measure_temp())
time.sleep(10)
os.system('clear')
print 'end'
my problem is in this line :
if measure_temp() == "50.1":
I want escape all symbols after first number like this :
if measure_temp() == "5\":
but it does not work. How can I solve this problem?
measure_temp() seems to return a string. I would convert this to a float type first and then check if the value is greater than 50.
if float(measure_temp()) >= 50:
# Your code
You would need to be certain that measure_temp always returned a string that could be converted to a float.
You may replace your measure_temp() with the following, that returns float, that is easier to deal with:
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
try :
t = re.findall( r'temp=([\d\.]+)', temp )
t = float(t[0])
except : # something went wrong
print 'unable to convert the temperature:', temp
t = 20.0 # room temperature
pass
return t
and import re somewhere in the beginning of the file.
Once done, you may compare the temperature value with the numbers, like if temperature > 50 or something.
And just in case you're wondering, your recent changes 'if float(measure_temp()) >= 50:' will eventually break when vcgencmd stalls or returns an empty string or something that cannot be easily converted to float, you ought to handle exceptions for your scripts to run smoothly.
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).