Reputation: 79
I just bought a BH1750 lux detector for my Raspberry Pi 4 project. This code works:
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)
I can stop it with CTRL+C and re-run it as often as I like.
But this code
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)
fails with the error message:
.../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
If I run
i2cdetect -y 1
before running the script, I can see the Lux detector is at address 0x23
. Running i2cdetect
after the script fails shows no i2c devices.
I'm baffled. I don't know what's causing this. Presumably something in the other imports, but I need them to control other outputs for my project.
Any help diagnosing/resolving this is much appreciated.
Upvotes: 0
Views: 164
Reputation: 79
It turns out the answer is this line was causing the problem:
interlock_2 = Button(3)
Button(3) is a gpizero button set to GPIO3, which happens to also be the SCL pin. I'd disconnected the buttons and forgot about them, and reading the code I hadn't realised GPIO3 and SCL were the same pin (I use a breakout HAT that lists the pin as SCL). So the IC2 connection to the BH1750 was being lost by turning the pin into a GPIO connection. I still don't understand why running the test code didn't turn the pin back into an SCL pin, but I can resume my project now.
I worked out the problem line of code by starting with the working lux-displaying script, and pasting each line of the failing code into it one at a time and running the script until I found the line that broke the code. Then I looked up the GPIO3 pin on a diagram and saw it was the SCL pin.
Upvotes: 0