本帖最后由 eew_4FmF97 于 2025-1-3 17:42 编辑
英飞凌PSOC4100SMAX使用心得(I2C篇)
上一篇介绍了CAN总线的使用,在这一篇我续写I2C使用,PSOC4100SMAX的I2C使用也是比较容易上手的,
- 配置时钟Peripheral-Clocks配置
- Peripherals配置
- 配置PIN
这里需要注意电平,如果I2C SDA和SCL上没有外接上接电阻,距离短的情况下可以使用IO口内置的上拉
cy_en_scb_i2c_status_t i2c_res;
cy_en_sysint_status_t int_res;
const cy_stc_sysint_t PASCO2_I2C_IRQ_config = {
/*.intrSrc =*/PASCO2_I2C_IRQ,
/*.intrPriority =*/3u };
/*初始化并使能I2C Master模式*/
i2c_res = Cy_SCB_I2C_Init(PASCO2_I2C_HW, &PASCO2_I2C_config,
&PASCO2_I2C_context);
if (i2c_res != CY_SCB_I2C_SUCCESS) {
CY_ASSERT(0);
}
/* 挂载中断 */
int_res = Cy_SysInt_Init(&PASCO2_I2C_IRQ_config, &PASCO2_I2C_Interrupt);
if (int_res != CY_SYSINT_SUCCESS) {
CY_ASSERT(0);
}
NVIC_EnableIRQ((IRQn_Type) PASCO2_I2C_IRQ_config.intrSrc);
Cy_SCB_I2C_Enable(PASCO2_I2C_HW, &PASCO2_I2C_context);
.(2)读I2C寄存器
cy_stc_scb_i2c_master_xfer_config_t transfer;
uint8_t readBuffer[20UL];
uint8_t writeBuffer[2UL] = { 0U };
uint8_t readDataLen;
transfer.buffer = writeBuffer;
transfer.bufferSize = 1; //只写寄存器地址
transfer.xferPending = true; //这里表示写入地址后面还要继续等待应答
transfer.slaveAddress = 0x28U;//I2C 从设备地址
writeBuffer[0]=0;//准备读的寄存器的起始地址
readDataLen=10;//读的寄存器个数
/*先写要读的寄存器地址*/
scb_status = Cy_SCB_I2C_MasterWrite(scbID, &transfer, i2cContext);
if (scb_status == CY_SCB_I2C_SUCCESS) {
/* 等待I2C通信 */
do {
status = Cy_SCB_I2C_MasterGetStatus(scbID, i2cContext);
Cy_SysLib_DelayUs(1u);
} while (0UL != (CY_SCB_I2C_MASTER_BUSY & status));
/* 配置读操作 */
transfer.buffer = readBuffer;
transfer.bufferSize = sizeof(readBuffer);
transfer.xferPending = false; /* 读操作完成后产生结束信号*/
(void) Cy_SCB_I2C_MasterRead(scbID, &transfer, i2cContext);
/* 等待 */
while (0UL
!= (CY_SCB_I2C_MASTER_BUSY
& Cy_SCB_I2C_MasterGetStatus(scbID, i2cContext))) {
}
……
}
- (3)写寄存器也是类似的
uint8_t writeBuffer[20UL] = { 5U,6U };
uint8_t writeDataLen;
transfer.buffer = writeBuffer;
transfer.bufferSize = ; //只写寄存器地址
transfer.xferPending = false; //这里表示写入完成后结束通信
transfer.slaveAddress = 0x28U;//I2C 从设备地址
writeBuffer[0]=20;//准备写的寄存器的起始地址
writeDataLen=2;//写的数据长度
/*先写要读的寄存器地址*/
scb_status = Cy_SCB_I2C_MasterWrite(scbID, &transfer, i2cContext);
if (scb_status == CY_SCB_I2C_SUCCESS) {
/* 等待I2C通信 */
do {
status = Cy_SCB_I2C_MasterGetStatus(scbID, i2cContext);
Cy_SysLib_DelayUs(1u);
} while (0UL != (CY_SCB_I2C_MASTER_BUSY & status));
}
……
PSOC4100S Max的库已经高度封装了I2C的基本操作,我们只需要简单调用就可以了,结合GPIO中断,就可以操作操作各种I2C外设了。接下来,我继续介绍ADC的操作,敬请期待!