我擁有一臺連接到樹莓的3D打印機。爲了遠程控制打印機(如通過relais關閉和關閉打印機),我製作了一個小型python腳本。Raspi python腳本不斷崩潰
控制它的一種可能性是使用似乎正常工作的Telegram Bot(telepot)。 打開和關閉打印機的另一種方法是硬件開關。出於安全原因,我希望打印機僅在開關按下3秒鐘時關閉。
問題是,腳本有時會崩潰(大多數情況下會在長時間的正常運行時間之後)。 我認爲這是我最後的while循環,但我不明白爲什麼它只會在可變的時間之後崩潰,以及如何改善它。 這是迄今爲止代碼:
#!/usr/bin/python
import time
import subprocess
import os
import datetime
import telepot
import urllib
import RPi.GPIO as GPIO
chat_id_auth = XXXXXXXXXXX
# Warnungen ausschalten
GPIO.setwarnings(False)
# Pin Nummern verwenden
GPIO.setmode(GPIO.BOARD)
# Pin 11 als Input
GPIO.setup(29, GPIO.IN)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, 0) #on
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Got command: %s' % command
if chat_id == chat_id_auth:
if command == '/status':
bot.sendMessage(chat_id, 'online')
elif command == '/picture':
bashCommand = 'wget --output-document snapshot.jpg http://127.0.0.1:8080/?action=snapshot'
subprocess.check_output(bashCommand, shell=True)
print ('downloaded photo')
bot.sendPhoto(chat_id, open('snapshot.jpg','rb'), caption='Printer Status')
print ('sent photo')
bashCommand = 'rm snapshot.jpg'
subprocess.check_output(bashCommand, shell=True)
print ('removed photo')
elif command == '/ip':
bashCommand = 'ifconfig eth0 | grep \'inet addr:\' | cut -d: -f2 | awk \'{ print $1}\''
output = subprocess.check_output(bashCommand, shell=True)
bot.sendMessage(chat_id, output)
print(output)
elif command == '/on':
#bashCommand = 'echo \'0\' > /sys/class/gpio/gpio17/value'
#output = subprocess.check_output(bashCommand, shell=True)
GPIO.output(11, 0) #on
bot.sendMessage(chat_id, 'Drucker wird eingeschaltet..')
#print(output)
elif command == '/off':
#bashCommand = 'echo \'1\' > /sys/class/gpio/gpio17/value'
#output = subprocess.check_output(bashCommand, shell=True)
GPIO.output(11, 1) #off
bot.sendMessage(chat_id, 'Drucker wird ausgeschaltet..')
#print(output)
else:
bot.sendMessage(chat_id, 'You are not authorized.')
bot = telepot.Bot('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
bot.message_loop(handle)
print 'I am listening ...'
global n
n=0
while True:
if GPIO.input(29):
if GPIO.input(11) == 0:
if n >= 300: #Taster 3s halten zum Ausschalten
GPIO.output(11, 1) #off
n=0
time.sleep(2)
elif GPIO.input(11) == 1:
GPIO.output(11, 0) #on
n=0
time.sleep(2)
time.sleep(0.01)
n+=1
else:
n=0
print n
GPIO.cleanup()