Skip to content

Commit b5d5c9f

Browse files
Examples: Add I2C controller example to read acc WhoAmI reg.
1 parent 193ec38 commit b5d5c9f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

examples/i2c_controller.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Copyright 2022 Micro:bit Educational Foundation and contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
#include "mbed.h"
18+
19+
// I2C address of the on-board accelerometer & Who Am I values for LSM303AGR
20+
#define ACC_I2C_ADDR (0x19 << 1)
21+
#define ACC_WHOAMI_REG (0x0F)
22+
#define ACC_WHOAMI_VAL (0x33)
23+
24+
// Set up I2C with the internal I2C bus pins
25+
I2C i2c(I2C_SDA0, I2C_SCL0);
26+
27+
// Set up serial and printf
28+
UnbufferedSerial pc_serial(USBTX, USBRX, 115200);
29+
FileHandle *mbed::mbed_override_console(int fd) {
30+
return &pc_serial;
31+
}
32+
33+
// Simple function to read a single register from an I2C device
34+
uint8_t i2c_read_register(uint8_t target_address, uint8_t reg_address) {
35+
uint8_t error = i2c.write(target_address, (char *)&reg_address, 1, true);
36+
if (error) {
37+
printf("Error performing an I2C write.");
38+
return 0;
39+
}
40+
uint8_t data = 0;
41+
error = i2c.read(target_address, (char *)&data, 1);
42+
if (error) {
43+
printf("Error performing an I2C read.");
44+
}
45+
return data;
46+
}
47+
48+
49+
int main(void) {
50+
uint8_t acc_who_am_i_value = i2c_read_register(ACC_I2C_ADDR, ACC_WHOAMI_REG);
51+
52+
printf("I2C accelerometer Who Am I value: %d\n", acc_who_am_i_value);
53+
printf((acc_who_am_i_value == ACC_WHOAMI_VAL) ? "Success!\n" : "Invalid value :(\n");
54+
55+
while (1);
56+
}

0 commit comments

Comments
 (0)