accel_i2c.py 972 B

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