当脚本在启动时运行时,Raspberry Pi A +蓝牙与DS18B20无法正常工作

时间:2015-04-21 16:29:44

标签: python bluetooth raspberry-pi boot temperature

我编写了一个python脚本,在Raspberry Pi A +上运行,通过蓝牙与Raspberry Pi B +连接,并使用DS18B20传感器发送温度数据。当我从A +手动运行脚本时,它运行得很好,但是当我尝试将脚本设置为在Pi启动时运行时,它无法通过蓝牙连接。这是脚本:

import socket
import time
import os

#time.sleep(10)
serverMACAddress = '00:15:83:12:1A:39'
port = 3
connected = False
while connected == False:
    try:

        s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
        s.connect((serverMACAddress,port))
        connected=True
        print("connected")
    except Exception as e:
        print('failed')
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

temp_sensor = '/sys/bus/w1/devices/28-000006773191/w1_slave'
current_time = time.time()
UPDATE_THRESHOLD = 5
newTemp = False
def temp_raw():
    f = open(temp_sensor,'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = temp_raw()
    temp_output = lines[1].find('t=')
    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output+2:]
        temp_c = float(temp_string)/1000.0
        temp_f = temp_c*9.0/5.0+32.0
        return temp_c

waterTemp = read_temp()

while True:

    nextWaterTemp = read_temp()
    current_time = time.time()
    newTemp = True
    if nextWaterTemp != waterTemp:
        waterTemp = nextWaterTemp
    try:
        s.send(bytes(str(waterTemp),'UTF-8'))
        time.sleep(30)
        connected = True
        print(waterTemp)
    except Exception as e:
        print("Fail")
        connected = False

    while connected == False:
        try:
            s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.s.connect((serverMACAddress,port)))
            s.send(bytes(str(waterTemp),'UTF-8'))
            connected = True
            print("Connected")
        except Exception as e:
            print("Fail")
            time.sleep(.5)

如果连接失败,此代码也无法重新连接到B +。我必须重新启动B +和A +上的代码才能让它们因某种原因再次连接。但这是一个不同的问题。我只是希望这个代码在启动时运行。

我用来让脚本在启动时运行的方法是将此代码放在/etc/rc.local文件中: /usr/bin/python /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err

有什么想法吗?

更新:

它将始终在client.out文件中打印出“失败”。

OR

在client.err或client.out文件中没有记录任何内容,屏幕顶部的蓝牙图标显示它已连接,但我只收到0应该发送的温度值。但是当我尝试手动运行脚本而不在启动时运行它时,温度工作正常。

1 个答案:

答案 0 :(得分:0)

找到它。

/usr/bin/python /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err

需要

/usr/bin/python3 /home/pi/Desktop/client.py >/tmp.client.out 2>/tmp/client.err

使用DS18B20

在寻找好几个小时之后,我觉得自己像个白痴。很抱歉浪费任何人的时间。我会留下这个,以防一些可怜的灵魂需要它作为参考。