Raspberry Pi 4和Python3脚本,在启动时启动但不工作

2024-05-19 00:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这段代码,如果我手动启动它,它工作得很好,但是当我通过crontab启动它时,它会启动,但不能正常工作。 我声明gpio库可以工作,麦克风驱动程序也可以工作,因为它可以监听,我可以从LED和日志文件中看到它正在工作。语音识别库似乎工作不正常。
我们要一条Python。 这是我添加到crontab文件的行: @重新启动python3/home/pi/SpeechRecognition/raspuino\u home\u assistan.py&

#!/usr/bin/python3

import time
#time.sleep(180)

import speech_recognition as sr
import urllib.request as request
from wireless import Wireless
from RPi import GPIO
import os

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.output(22, GPIO.LOW)
GPIO.output(27, GPIO.LOW)
GPIO.output(25, GPIO.LOW)

log = open("log.txt", "w")
log.write("Start at:" + time.strftime("%H:%M:%S") + "\n")
log.write("Start listenig:" + "\n")
log.close() 

def internet_on():
    
    try:
        request.urlopen('http://google.com', timeout=1)
        return True
    
    except request.URLError as err: 
        return False
    
def internet_check():
    while(internet_on()==False):
        GPIO.output(24, GPIO.HIGH)
    
while(internet_on()==False):
    GPIO.output(24, GPIO.HIGH)

recognizer_instance = sr.Recognizer()

with sr.Microphone() as source:
    recognizer_instance.adjust_for_ambient_noise(source)  
        
def luce_sala():
    GPIO.output(25, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(25, GPIO.LOW)     

def luce_cucina():
    GPIO.output(22, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(22, GPIO.LOW)      

def luce_led():
    GPIO.output(27, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(27, GPIO.LOW)

def tutte_le_luci():
    GPIO.output(25, GPIO.HIGH)
    GPIO.output(22, GPIO.HIGH)
    GPIO.output(27, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(25, GPIO.LOW)
    GPIO.output(22, GPIO.LOW)
    GPIO.output(27, GPIO.LOW)                

while (True):
    
    with sr.Microphone() as source:
        recognizer_instance.adjust_for_ambient_noise(source)
        GPIO.output(23, GPIO.HIGH)
        GPIO.output(24, GPIO.LOW)

        audio = recognizer_instance.listen(source)
        GPIO.output(23, GPIO.LOW)
        
    try:
        text = recognizer_instance.recognize_google(audio, language="it-IT")
        log = open("log.txt", "a")
        log.write(text + "\n")
        log.close() 
        
        if ("luce sala") in text.lower():
            luce_sala()

        elif ("luce cucina") in text.lower():
            luce_cucina()
            
        elif ("luce led")  in text.lower():
            luce_led()
            
        elif ("tutte le luci") in text.lower():
            tutte_le_luci()         
            
    except Exception as e:
        log = open("log.txt", "a")
        log.write("Error: " + str(e) + "\n" )
        log.close() 
        internet_check()

Tags: textimportlogoutputgpiotimedefas

热门问题