Skip to content

Commit a2e0d92

Browse files
committed
examples: Add example of I2C usage, taking PyBoard accelerometer as subject.
1 parent f3b1a93 commit a2e0d92

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

examples/accel_i2c.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# This is an example on how to access accelerometer on
2+
# PyBoard directly using I2C bus. As such, it's more
3+
# intended to be an I2C example, rather than accelerometer
4+
# example. For the latter, using pyb.Accel class is
5+
# much easier.
6+
7+
import pyb
8+
import time
9+
10+
# Accelerometer needs to be powered on first. Even
11+
# though signal is called "AVDD", and there's separate
12+
# "DVDD", without AVDD, it won't event talk on I2C bus.
13+
accel_pwr = pyb.Pin("MMA_AVDD")
14+
accel_pwr.value(1)
15+
16+
i2c = pyb.I2C(1)
17+
addrs = i2c.scan()
18+
print("Scanning devices:", [hex(x) for x in addrs])
19+
if 0x4c not in addrs:
20+
print("Accelerometer is not detected")
21+
22+
ACCEL_ADDR = 0x4c
23+
ACCEL_AXIS_X_REG = 0
24+
ACCEL_MODE_REG = 7
25+
26+
# Now activate measurements
27+
i2c.mem_write(b"\x01", ACCEL_ADDR, ACCEL_MODE_REG)
28+
29+
print("Try to move accelerometer and watch the values")
30+
while True:
31+
val = i2c.mem_read(1, ACCEL_ADDR, ACCEL_AXIS_X_REG)
32+
print(val[0])
33+
time.sleep(1)

0 commit comments

Comments
 (0)