介绍
通过I2C总线向外部设备(如OLED屏、传感器等)写入数据
头文件
base\iot_hardware\interfaces\kits\wifiiot_lite\wifiiot_i2c.h
#include "wifiiot_i2c.h"
定义
/**
* @brief Writes data to an I2C device.
*
*
*
* @param id Indicates the I2C device ID.
* @param deviceAddr Indicates the I2C device address.
* @param i2cData Indicates the pointer to the data descriptor to write.
* @return Returns {@link WIFI_IOT_SUCCESS} if the operation is successful;
* returns an error code defined in {@link wifiiot_errno.h} otherwise.
* @since 1.0
* @version 1.0
*/
unsigned int I2cWrite(WifiIotI2cIdx id, unsigned short deviceAddr, const WifiIotI2cData *i2cData);
参数:
| 参数名 | 类型 | 含义说明 |
|---|---|---|
id |
WifiIotI2cIdx |
I2C总线编号(ID),用于指定使用哪一路I2C硬件接口。<br>例如Hi3861开发板通常支持WIFI_IOT_I2C_IDX_0(I2C0)。 |
deviceAddr |
unsigned short |
目标I2C设备的地址(7位或10位地址,取决于设备)。<br>例如OLED屏常见地址为0x78、0x3C或0x3D。 |
i2cData |
const WifiIotI2cData * |
指向待发送数据的结构体指针,包含发送缓冲区和数据长度(见下方结构体说明)。 |
返回值:
- 成功:返回
WIFI_IOT_SUCCESS(通常定义为0)。 - 失败:返回错误码
以上都定义在 wifiiot_errno.h 中,如I2C总线未初始化、通信超时等
相关结构体 WifiIotI2cData
详见链接:
https://www.malaoshi.top/show_1GW200V68QBl.html
注意事项
I2C总线初始化:使用
I2cWrite()前,需先通过I2cInit()初始化对应I2C总线(设置通信速率等),否则会返回失败。设备地址格式:
deviceAddr需与外设实际地址一致(注意是7位地址,无需左移1位,鸿蒙驱动会自动处理)。数据缓冲区:
sendBuf必须指向有效内存(提前分配),且sendLen不能超过外设支持的最大单次传输长度(避免溢出)。协议适配:不同I2C设备(如OLED、传感器)对数据格式的要求不同(如OLED需要区分“指令”和“数据”),需根据外设 datasheet 填充
sendBuf。
该函数是鸿蒙I2C通信的基础接口,掌握其用法是实现OLED显示、传感器数据写入等功能的关键。
例子
详见链接:
https://www.malaoshi.top/show_1GW200V68QBl.html