BH1750 I2C Python 在 Raspberry Pi 上失败

问题描述 投票:0回答:1

我刚刚为我的 Raspberry Pi 4 项目购买了 BH1750 勒克斯探测器。此代码有效:

import board
import time
import adafruit_bh1750
i2c = board.I2C()
sensor = adafruit_bh1750.BH1750(i2c)

while True:
    print("%.2f Lux"%sensor.lux)
    time.sleep(0.1)

我可以使用 CTRL+C 停止它,然后根据需要多次重新运行它。

但是这个代码

import RPi.GPIO as GPIO
from gpiozero import LED, LightSensor, Button
from time import time, sleep
import board
import adafruit_bh1750
import sys
from math import floor
import csv
from os import path

M0 = (17,18,27,22)
M1 = (4,25,24,23)
M2 = (13,12,6,5)
M3 = (20,26,16,19)

GPIO.setmode(GPIO.BCM)
RotationPins = M2
TranslationPins = M1
 
#initialise the LED emitter on physical pin 8, GPIO 14
emitter = LED(14)
emitter.off()

#initialise sensor
i2c = board.I2C()
sensor = adafruit_bh1750.BH1750(i2c)

#buttons for interlock on GPIO 2 and GPIO 3
interlock_1 = Button(2)
interlock_2 = Button(3)

StepCounter = 0

WaitTime = 0.01
Seq =  [[1,0,0,1],
        [1,0,0,0],
        [1,1,0,0],
        [0,1,0,0],
        [0,1,0,0],
        [0,1,1,0],
        [0,0,1,0],
        [0,0,1,1],
        [0,0,0,1]]
StepDir=1
StepCount = len(Seq)

#emitter.off()
while True:
    print("%.2f Lux"%sensor.lux)
    sleep(0.1)

失败并显示错误消息:

.../python3.9/site-packages/busio.py", line 197, in readfrom_into
    return self._i2c.readfrom_into(address, buffer, stop=True)
.../python3.9/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 67, in readfrom_into
    readin = self._i2c_bus.read_bytes(address, end - start)
.../python3.9/site-packages/Adafruit_PureIO/smbus.py", line 170, in read_bytes
    return self._device.read(number)
TimeoutError: [Errno 110] Connection timed out

如果我跑步

i2cdetect -y 1

在运行脚本之前,我可以看到勒克斯探测器位于地址

0x23
。脚本失败后运行
i2cdetect
显示没有 i2c 设备。

我很困惑。我不知道是什么原因造成的。大概是其他导入中的东西,但我需要它们来控制我的项目的其他输出。

非常感谢任何诊断/解决此问题的帮助。

python i2c pi iio
1个回答
0
投票

事实证明答案是这条线导致了问题:

interlock_2 = Button(3)

Button(3) 是一个设置为 GPIO3 的 gpizero 按钮,它恰好也是 SCL 引脚。我断开了按钮并忘记了它们,在阅读代码时我没有意识到 GPIO3 和 SCL 是同一个引脚(我使用了一个将引脚列为 SCL 的突破 HAT)。因此,通过将引脚转为 GPIO 连接,IC2 与 BH1750 的连接就会丢失。我仍然不明白为什么运行测试代码没有将引脚恢复为 SCL 引脚,但我现在可以恢复我的项目。

我通过从工作的勒克斯显示脚本开始,然后将失败代码的每一行一次粘贴到其中并运行脚本,直到找到破坏代码的行来解决问题代码行。然后我在图表上查找了 GPIO3 引脚,发现它是 SCL 引脚。

© www.soinside.com 2019 - 2024. All rights reserved.