Skip to content

Commit 7d862b2

Browse files
authored
Merge pull request #1573 from kattni/template-i2c
Adding I2C template code.
2 parents 2e709a3 + 9af73b6 commit 7d862b2

3 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""CircuitPython I2C possible pin-pair identifying script"""
2+
import board
3+
import busio
4+
from microcontroller import Pin
5+
6+
7+
def is_hardware_i2c(scl, sda):
8+
try:
9+
p = busio.I2C(scl, sda)
10+
p.deinit()
11+
return True
12+
except ValueError:
13+
return False
14+
except RuntimeError:
15+
return True
16+
17+
18+
def get_unique_pins():
19+
exclude = ['NEOPIXEL', 'APA102_MOSI', 'APA102_SCK']
20+
pins = [pin for pin in [
21+
getattr(board, p) for p in dir(board) if p not in exclude]
22+
if isinstance(pin, Pin)]
23+
unique = []
24+
for p in pins:
25+
if p not in unique:
26+
unique.append(p)
27+
return unique
28+
29+
30+
for scl_pin in get_unique_pins():
31+
for sda_pin in get_unique_pins():
32+
if scl_pin is sda_pin:
33+
continue
34+
if is_hardware_i2c(scl_pin, sda_pin):
35+
print("SCL pin:", scl_pin, "\t SDA pin:", sda_pin)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""CircuitPython I2C MCP9808 Temperature Sensor Example"""
2+
import time
3+
import board
4+
import adafruit_mcp9808
5+
6+
i2c = board.I2C() # uses board.SCL and board.SDA
7+
mcp9808 = adafruit_mcp9808.MCP9808(i2c)
8+
9+
while True:
10+
temperature_celsius = mcp9808.temperature
11+
temperature_fahrenheit = temperature_celsius * 9 / 5 + 32
12+
print("Temperature: {:.2f} C {:.2f} F ".format(temperature_celsius, temperature_fahrenheit))
13+
time.sleep(2)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""CircuitPython I2C Device Address Scan"""
2+
import time
3+
import board
4+
5+
i2c = board.I2C()
6+
7+
while not i2c.try_lock():
8+
pass
9+
10+
try:
11+
while True:
12+
print("I2C addresses found:", [hex(device_address) for device_address in i2c.scan()])
13+
time.sleep(2)
14+
15+
finally: # unlock the i2c bus when ctrl-c'ing out of the loop
16+
i2c.unlock()

0 commit comments

Comments
 (0)