Skip to content

add I2C example #100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions APIs_Drivers/I2C_ex_1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# I2C example

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.
32 changes: 32 additions & 0 deletions APIs_Drivers/I2C_ex_1/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2014-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/

#include "mbed.h"

// Read temperature from LM75BD

I2C i2c(I2C_SDA, I2C_SCL);

const int addr7bit = 0x48; // 7 bit I2C address
const int addr8bit = 0x48 << 1; // 8bit I2C address, 0x90

int main()
{
char cmd[2];
while (1) {
cmd[0] = 0x01;
cmd[1] = 0x00;
i2c.write(addr8bit, cmd, 2);

ThisThread::sleep_for(500);

cmd[0] = 0x00;
i2c.write(addr8bit, cmd, 1);
i2c.read(addr8bit, cmd, 2);

float tmp = (float((cmd[0] << 8) | cmd[1]) / 256.0);
printf("Temp = %.2f\n", tmp);
}
}