Paul Sokolovsky | a2e0d92 | 2015-10-28 21:04:03 +0300 | [diff] [blame] | 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 | |
Paul Sokolovsky | 9d0d6d3 | 2015-11-29 02:56:02 +0200 | [diff] [blame^] | 7 | from machine import Pin |
| 8 | from machine import I2C |
Paul Sokolovsky | a2e0d92 | 2015-10-28 21:04:03 +0300 | [diff] [blame] | 9 | import time |
| 10 | |
| 11 | # Accelerometer needs to be powered on first. Even |
| 12 | # though signal is called "AVDD", and there's separate |
| 13 | # "DVDD", without AVDD, it won't event talk on I2C bus. |
Paul Sokolovsky | 9d0d6d3 | 2015-11-29 02:56:02 +0200 | [diff] [blame^] | 14 | accel_pwr = Pin("MMA_AVDD") |
Paul Sokolovsky | a2e0d92 | 2015-10-28 21:04:03 +0300 | [diff] [blame] | 15 | accel_pwr.value(1) |
| 16 | |
Paul Sokolovsky | 9d0d6d3 | 2015-11-29 02:56:02 +0200 | [diff] [blame^] | 17 | i2c = I2C(1, baudrate=100000) |
Paul Sokolovsky | a2e0d92 | 2015-10-28 21:04:03 +0300 | [diff] [blame] | 18 | addrs = i2c.scan() |
| 19 | print("Scanning devices:", [hex(x) for x in addrs]) |
| 20 | if 0x4c not in addrs: |
| 21 | print("Accelerometer is not detected") |
| 22 | |
| 23 | ACCEL_ADDR = 0x4c |
| 24 | ACCEL_AXIS_X_REG = 0 |
| 25 | ACCEL_MODE_REG = 7 |
| 26 | |
| 27 | # Now activate measurements |
| 28 | i2c.mem_write(b"\x01", ACCEL_ADDR, ACCEL_MODE_REG) |
| 29 | |
| 30 | print("Try to move accelerometer and watch the values") |
| 31 | while True: |
| 32 | val = i2c.mem_read(1, ACCEL_ADDR, ACCEL_AXIS_X_REG) |
| 33 | print(val[0]) |
| 34 | time.sleep(1) |