MbedOS I2C

 

I2C接口提供I2C主控功能。I2C是一种双线串行协议,允许I2C主设备与I2C从设备交换数据。您可以使用它与I2C设备通信,例如串行存储器,传感器和其他模块或集成电路。

I2C协议每条总线最多支持127个设备,其默认时钟频率为100KHz。


注意:请记住,在sda scl 上需要一个上拉电阻。I2C总线上的所有驱动器都需要是开路集电极,因此必须在两个信号上使用上拉电阻。上拉电阻的典型值约为2.2k欧姆,连接在引脚和3v3之间。


I2C类参考


注意: Arm Mbed API使用8位地址,因此请确保在传递之前将7位地址左移1位。


 

Public Member Functions
  I2C (PinName sda, PinName scl)
  创建连接到指定引脚的I2C主接口。
void  frequency (int hz)
  设置I2C接口的频率
int  read (int address, char *data, int length, bool repeated=false)
  从I2C从器件读取。
int  read (int ack)
  从I2C总线读取一个字节。
int  write (int address, const char *data, int length, bool repeated=false)
  写入I2C从器件.
int  write (int data)
  在I2C总线上写入单字节输出。
void  start (void)
  在I2C总线上创建启动条件
  stop (void)
  在I2C总线上创建停止条件。
virtual void  lock (void)
  获取对此I2C总线的独占访问权限
int  transfer (int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event=I2C_EVENT_TRANSFER_COMPLETE, bool repeated=false)
  启动非阻塞I2C传输。
void  abort_transfer ()
  中止正在进行的I2C传输。

导入Mbed IDE(请单击)

/* mbed Example Program
 * Copyright (c) 2006-2014 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#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);
 
        wait(0.5);
 
        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);
    }
}

原文地址:https://os.mbed.com/docs/mbed-os/v5.11/apis/i2c.html


 

你可能感兴趣的:(Mbed,OS)