Skip to content

Commit d6e799d

Browse files
committedNov 6, 2024
Improve bus reset
1 parent 8282227 commit d6e799d

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed
 

‎src/modulino/modulino.py

+17-11
Original file line numberDiff line numberDiff line change
@@ -56,22 +56,28 @@ def reset_bus(i2c_bus: I2C) -> I2C:
5656
# Unfortunately the I2C class does not expose those attributes directly.
5757
interface, scl_pin_number, sda_pin_number = _I2CHelper.extract_i2c_info(i2c_bus)
5858

59-
scl_pin = Pin(scl_pin_number, Pin.IN) # Detach pin from I2C
60-
sda_pin = Pin(sda_pin_number, Pin.IN) # Detach pin from I2C
59+
# Detach pins from I2C and configure them as GPIO outputs in open-drain mode
60+
scl_pin = Pin(scl_pin_number, Pin.OUT, Pin.OPEN_DRAIN)
61+
sda_pin = Pin(sda_pin_number, Pin.OUT, Pin.OPEN_DRAIN)
6162

62-
scl_pin = Pin(scl_pin_number, Pin.OUT)
63-
sda_pin = Pin(sda_pin_number, Pin.OUT)
63+
# Set both lines high initially
64+
scl_pin.value(1)
65+
sda_pin.value(1)
66+
sleep(0.001) # 1 millisecond delay to stabilize bus
67+
68+
# Pulse the SCL line 9 times to release any stuck device
69+
for _ in range(9):
70+
scl_pin.value(0)
71+
sleep(0.001) # 1 millisecond delay for each pulse
72+
scl_pin.value(1)
73+
sleep(0.001)
6474

65-
period = 1 / _I2CHelper.frequency
75+
# Ensure SDA is high before re-initializing
6676
sda_pin.value(1)
67-
for _ in range(0, 20):
68-
scl_pin.value(1)
69-
sleep(period / 2) # Add sleep to match the frequency
70-
scl_pin.value(0)
71-
sleep(period / 2) # Add sleep to match the frequency
77+
scl_pin.value(1)
78+
sleep(0.001) # 1 millisecond delay to stabilize bus
7279

7380
# Need to re-initialize the bus after resetting it
74-
# otherwise it gets stuck.
7581
return I2C(interface, freq=_I2CHelper.frequency)
7682

7783
@staticmethod

0 commit comments

Comments
 (0)
Please sign in to comment.