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).
Related
I'm making a bot in python and it works normally, but I need a certain part of the code to be in an infinite loop, so when i put the code inside the "while True" it looks like my imports are unusable. can someone explain to me how i can solve this?´
import datetime
import os
import time
import cv2
import pytesseract
from playwright.sync_api import sync_playwright
caminho = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
data = datetime.datetime.now()
h = data.strftime("%h")
d = data.strftime("%d")
H = data.strftime("%H")
M = data.strftime("%M")
S = data.strftime("%S")
hd = h + d
t = H + M
pasta =f"C:/Kprints/{hd}"
chave = "****"
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("*****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[19]/button[1]').click()
time.sleep(3)
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/button').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[1]/img[1]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div[2]/div/div[2]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[2]/div[5]/button').click()
time.sleep(1)
while True:
page.screenshot(path=f"{pasta}/{t}.png")
time.sleep(1)
img = cv2.imread(f"{pasta}/{t}.png")
time.sleep(1)
pytesseract.pytesseract.tesseract_cmd = caminho
texto = pytesseract.image_to_string(img)
time.sleep(1)
if not os.path.isdir(pasta):
os.mkdir(pasta)
list = os.listdir(pasta)
for arquivo in list:
if chave not in texto:
os.remove(f"{pasta}/{arquivo}")
Errors:
Unused import statement 'import os'
Unused import statement'import cv2'
Unused import statement 'import pytesseract'
This code is unreachable
Your analyzer is saying the code using them can't be reached because your while loop, being infinite, renders it impossible to reach any code after it. Either:
The loop never ends, or
The calls inside it raise an exception, that (thanks to no try blocks being involved) will bubble up (skipping the remaining code) and end the program.
Either way, as written, the code after the loop never runs, so those imports are effectively unused.
The question for you is: Do you expect/need the code after that loop to run? If so, the loop cannot be infinite and you need to change the code so it can end. If not, why is the code after the loop even there?
Those are not errors. Those should be just warnings.
Can you try re-run and post actual output here?
You code gets stuck in that loop so imports not used and yes pytesseract can not be reached.
Practice this code snippet first:
key = ""
while key != "q":
key = input("Enter a Key: ")
if key == "q":
break
print(f"You Entered: {key}")
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
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.
actually I´m working at a "Magic Mirror" and now I got a problem with the python script wich should turning my monitor on/off.
I copied the python script from this site
#!/usr/bin/env python
import sys
import time
import RPi.GPIO as io
import subprocess
io.setmode(io.BCM)
SHUTOFF_DELAY = 60 # seconds
PIR_PIN = 7 # Pin 26 on the board
def main():
io.setup(PIR_PIN, io.IN)
turned_off = False
last_motion_time = time.time()
while True:
if io.input(PIR_PIN):
last_motion_time = time.time()
sys.stdout.flush()
if turned_off:
turned_off = False
turn_on()
else:
if not turned_off and time.time() > (last_motion_time + SHUTOFF_DELAY):
turned_off = True
turn_off()
time.sleep(.1)
def turn_on():
subprocess.call("sh /home/pi/Documents/PIR/monitor_on.sh", shell=True)
def turn_off():
subprocess.call("sh /home/pi/Documents/PIR/monitor_off.sh", shell=True)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
io.cleanup()
I tried to run the script, but python tell me there is a syntax error at line 25, it points exactly at the semicolon after & and before gt
I didn't worked with python until now, therefore I don't know anything about the syntax of python.
I would appreciate it very much if you guys will take a minute to help me solving my problem.
I got the python version 2.7.9
This is not the exact copy of the original Python file. You copied some HTML markup while copying the file.
Replace > with >.
if not turned_off and time.time() > (last_motion_time + SHUTOFF_DELAY):
turned_off = True
turn_off()
You also have indentation issues and other HTML stuff you should get rid of:
def main():
io.setup(PIR_PIN, io.IN)
turned_off = False
last_motion_time = time.time()
and
def turn_on():
subprocess.call("sh /home/pi/Documents/PIR/monitor_on.sh", shell=True)
def turn_off():
subprocess.call("sh /home/pi/Documents/PIR/monitor_off.sh", shell=True)
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).