【问题标题】:Raspberry Pi won't run script on bootRaspberry Pi 不会在启动时运行脚本
【发布时间】:2015-06-09 00:08:19
【问题描述】:

程序将使用条形码扫描仪来验证优惠券的好坏,并根据优惠券是否有效闪烁红灯或绿灯。

我希望它的工作方式是打开 Pi,然后立即能够扫描优惠券。 Pi 所要做的就是在我打开 Pi 并保持打开状态后启动程序,仅此而已。我正在使用 crontab 启动以下程序:

#Adam Giancola 
#June 5th 2015

#This program will scan a bar code and if it matches a good bar code will         flash a light
#green or red depending on the validity of the coupon.

import sys, select, os
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

greenLED = 16
redLED = 12

GPIO.setup(greenLED, GPIO.OUT)
GPIO.setup(redLED, GPIO.OUT)
GPIO.output(greenLED, GPIO.LOW)
GPIO.output(redLED, GPIO.LOW)
goodBarCode = "0827112134023"

try:
    #Flash LED to test if script is running at RPi boot

    GPIO.output(greenLED, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(greenLED, GPIO.LOW)
    time.sleep(0.5)

    while(1):
        userBarCode = input("")

        if userBarCode == goodBarCode:
            GPIO.output(greenLED, GPIO.HIGH)    
            time.sleep(0.5)
            GPIO.output(greenLED, GPIO.LOW)
            time.sleep(0.5)

        else:
            GPIO.output(redLED, GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(redLED, GPIO.LOW)
            time.sleep(0.5)

except:
    GPIO.cleanup()

如果我使用 "sudo python3 ...blah blah blah" 通过终端运行此代码,它可以正常工作,但我已使用 crontab 在启动时启动程序,但我没有从 LED 获得任何反馈。我知道我的 crontab 配置正在运行,因为我已经同时运行了其他程序并且它们正在运行。为什么 LED 不响应?

【问题讨论】:

  • 为什么不创建一个 init.d 脚本来启动进程而不是 crontab?不过,您将不得不使用 screen 之类的东西或分叉该过程。
  • 我怀疑你错过了告诉它使用什么解释器的 hashbang。试试#!/usr/bin/env python 可能吗?
  • Nathan 我把这个添加到 py 脚本?
  • 将它添加到 /etc/rc.local 而不是 cron 怎么样?
  • dastaan​​ 我这样做了,我得到了相同的结果,它开始了,但我的代码似乎有问题,不允许程序继续运行。

标签: python linux raspberry-pi


【解决方案1】:

问题在于条码扫描器伪装成键盘。当您从控制台运行它时,无论条形码扫描仪输出什么都将进入您的程序,因为它是当前在控制台的标准输入上读取的那个。

当你在后台运行它时,通过 rc.local、cron、init 脚本或任何其他方法,你的程序不会在控制台上,它会在后台,所以它不会“看到”什么条码扫描仪输入键盘。

可能对您来说最好的短期解决方案是在控制台上启用自动登录(GUI 必须关闭)并在登录后立即调用您的程序。 Full explanation here,短版:

编辑 /etc/inittab 并将对应的行改为:

 1:2345:respawn:/bin/login -f pi tty1 </dev/tty1 >/dev/tty1 2>&1

编辑 /home/pi/.bash_profile 并添加:

 sudo python3 bla bla bla

【讨论】:

  • @Cola,很高兴知道这是否对您有用,因为它可能对其他人有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2021-08-01
  • 2021-05-03
  • 1970-01-01
  • 2019-09-20
  • 2015-05-26
  • 1970-01-01
相关资源
最近更新 更多