Skip to content

Commit fb4d315

Browse files
add I2C example (#100)
1 parent b2c17d2 commit fb4d315

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

APIs_Drivers/I2C_ex_1/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# I2C example
2+
3+
This example shows how to use `I2C` API to read temperature sensor. The Mbed OS `I2C` API uses 8 bit addressing and will auto append the 0 or 1 for read/write mode. Please keep in mind that every I2C set up has its own quirks so this example may not work out of the box for your sensor / application. Make sure to check the data sheet for your part for the timing / register access specification.

APIs_Drivers/I2C_ex_1/main.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Copyright (c) 2014-2020 Arm Limited and affiliates.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
#include "mbed.h"
7+
8+
// Read temperature from LM75BD
9+
10+
I2C i2c(I2C_SDA, I2C_SCL);
11+
12+
const int addr7bit = 0x48; // 7 bit I2C address
13+
const int addr8bit = 0x48 << 1; // 8bit I2C address, 0x90
14+
15+
int main()
16+
{
17+
char cmd[2];
18+
while (1) {
19+
cmd[0] = 0x01;
20+
cmd[1] = 0x00;
21+
i2c.write(addr8bit, cmd, 2);
22+
23+
ThisThread::sleep_for(500);
24+
25+
cmd[0] = 0x00;
26+
i2c.write(addr8bit, cmd, 1);
27+
i2c.read(addr8bit, cmd, 2);
28+
29+
float tmp = (float((cmd[0] << 8) | cmd[1]) / 256.0);
30+
printf("Temp = %.2f\n", tmp);
31+
}
32+
}

0 commit comments

Comments
 (0)