LSM303AGR Accelerometer Magnetometer
The LSM303AGR from STMicroelectronics [1] is a 3D accelerometer and 3D magnetometer with SPI and I2C interfaces. It can operate from between 1.71 V and 3.6 V.
The I2C addresses are 25 (#x19) for the accelerometer and 30 (#x1E) for the magnetometer.
This sensor is provided in the BBC Micro:bit Version 1.5 and Version 2. On the Version 2 the sensor is on I2C port 1, so the second parameter to the with-i2c calls should be 1.
Checking the sensor ID
; Should return 64
(defun lsm303-whoami ()
(with-i2c (str 0 #x1e)
(write-byte #x4f str)
(restart-i2c str 1)
(read-byte str)))
Initialising the sensor
The following routine initialises the sensor:
; Continuous mode, 10Hz
(defun lsm303-init ()
(with-i2c (str 0 #x1e)
(write-byte #x60 str)
(write-byte #x00 str)))
Reading the sensor
This returns the sensor data as a list of three numbers between 0 and 65535:
(defun read16 (str)
(logior (read-byte str) (ash (read-byte str) 8)))
; Read magnetometer x, y, and z
(defun lsm303-xyz ()
(with-i2c (str 0 #x1e)
(write-byte #x68 str)
(restart-i2c str 6)
(list (read16 str) (read16 str) (read16 str))))
Checking data ready
; Is new data ready?
(defun lsm303-data-p ()
(with-i2c (str 0 #x1e)
(write-byte #x67 str)
(restart-i2c str 1)
(eq (logand (read-byte str) #x08) 8)))- ^ LSM303AGR Datasheet on ST.com.
