Subsection 12.2.3 Part 3: What Just Ran
Here is the whole of
whoami_test.c. Notice the first #define: the device address is written (0x32 >> 1), a number shifted right by one rather than written out. >> moves every bit of a value one place toward the least significant end, dropping the bit that falls off the bottom and bringing in a 0 at the top; it is the mirror of the << we have used on register bits since the first GPIO write. What that does to 0x32, we’ll come back to, and to why the address is written this way, once we have the logic analyzer on the bus.
#include <stdio.h>
#include "ES28.h"
#include "uart.h"
#include "i2c.h"
#define LSM303_ADDRESS_ACCEL (0x32 >> 1) // 7-bit address 0b0011001
#define LSM303_WHO_AM_I_A 0x0F // default value: 00110011
uint8_t lsm303_AccelRegisterRead(uint8_t registerAddress);
int main(void) {
uint8_t who_am_i = 0;
i2c1_init();
uart2_init();
printf("LSM303AGR initialization test \n\r");
while(1) {
who_am_i = lsm303_AccelRegisterRead(LSM303_WHO_AM_I_A);
if( who_am_i == 0x33 ) {
printf("Accelerometer initialized! \n\r");
}
else {
printf("Could not connect to accelerometer \n\r");
}
delay_ms(1000);
}
return 0;
}
/* Read one byte from an accelerometer register (Datasheet, Table 22) */
uint8_t lsm303_AccelRegisterRead(uint8_t registerAddress) {
uint8_t data = 0;
i2c1_memRead(LSM303_ADDRESS_ACCEL, registerAddress, 1, &data);
return data;
}
The program has the same shape as the programs we have been writing all term: initialize the two peripherals, print a startup message, and then a loop that does one thing once a second: read WHO_AM_I, compare what came back to the number 0x33, and print one of two lines. The only function it defines besides
main(), lsm303_AccelRegisterRead(), is a single call into the I2C library from Chapter 10: i2c1_memRead(), asked for one byte from one register. Receiving 0x33 back from the accelerometer as the contents of the WHO_AM_I register verifies the complete read path: the wiring, the device address, the protocol and the code all had to work for that value to arrive. The sensor is otherwise not yet configured, since the control registers are still at their power-on defaults; setting them up requires the accelerometer’s datasheet, which you will read in preparation for Thursday’s class. If it prints Could not connect to accelerometer instead, that is data too. The analyzer we are about to put on the bus shows exactly what the wire is doing.
