我在树莓派上运行了一个python脚本,希望在启动时自动运行。在添加温度传感器之前,我一直在进行此操作,直到现在程序在启动时不会自动运行,但是如果手动运行,它将正常运行,没有错误。
启动时是否对某些导入不了解?
有效方法:
我通过在文件末尾附近添加rc.local
来修改python /home/pi/myscript.py &
。
其中myscript.py =
#!/usr/bin/python3
import RPi.GPIO as GPIO #for GPIO naming convention
import os #for power circuit
import serial #for reading serial port on USB
import time
import threading
def power_button():
GPIO.setmode(GPIO.BCM)#set to GPIO Values
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.OUT)#relay coil
GPIO.setup(22,GPIO.OUT)#power LED
GPIO.setup(27,GPIO.IN)#power button sense
GPIO.output(4,GPIO.HIGH)#turn on coil
GPIO.output(22,GPIO.HIGH)#turn on power LED
powerButton = GPIO.input(27)
while powerButton ==1: #check for change, then shutdown
powerButton = GPIO.input(27)
#change occured, as program left the while loop, proceed below
GPIO.output(22,GPIO.LOW)#turn off power LED
os.system('sudo shutdown -h now')
#power button thread
thread1 = threading.Thread(target=power_button)
thread1.start()
就像上面提到的那样,此代码可以正常运行,并在启动时自动正常运行。
什么不起作用: 添加温度传感器导入后,它将不再自动启动,但是如果在pi启动后手动运行,它将运行正常。
myscripy.py,其中添加了更多导入:
#!/usr/bin/python3
import RPi.GPIO as GPIO #for GPIO naming convention
import os #for power circuit
import serial #for reading serial port on USB
import time
import threading
import adafruit_sht31d #sht temphumid sensor
import board #sht temphumid sensor
import busio #sht temphumid sensor
import adafruit_sht31d #sht temphumid sensor
import requests #for posting
# Create library object using our Bus I2C port for SHT31 temp humid sensor
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_sht31d.SHT31D(i2c)
def power_button():
GPIO.setmode(GPIO.BCM)#set to GPIO Values
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.OUT)#relay coil
GPIO.setup(22,GPIO.OUT)#power LED
GPIO.setup(27,GPIO.IN)#power button sense
GPIO.output(4,GPIO.HIGH)#turn on coil
GPIO.output(22,GPIO.HIGH)#turn on power LED
powerButton = GPIO.input(27)
while powerButton ==1: #check for change, then shutdown
powerButton = GPIO.input(27)
#change occured, as program left the while loop, proceed below
GPIO.output(22,GPIO.LOW)#turn off power LED
os.system('sudo shutdown -h now')
#power button thread
thread1 = threading.Thread(target=power_button)
thread1.start()
有什么想法吗?