华大单片机HC32L130/HC32L136从机IIC通信
选用中断方式进行:
uint8_t u8Recdata1[10] = {0x00};
uint8_t u8Recdata[10]={0x00};
uint8_t u8SendLen=0;
uint8_t u8RecvLen=0;
uint8_t u8RecvLen1=0;
uint8_t u8State = 0;
static void I2c0CallBack(void)
{
u8State = I2C_GetState(I2C0);
switch(u8State)
{
case 0x60:
case 0x70:
case 0xa0:
u8RecvLen = 0;
I2C_SetFunc(I2C0,I2cAck_En);
break;
case 0x68:
case 0x78:
case 0x88:
case 0x98:
I2C_SetFunc(I2C0,I2cAck_En);
break;
case 0x80:
case 0x90:
u8Recdata[u8RecvLen++] = I2C_ReadByte(I2C0);//接收数据
break;
case 0xa8://接收读命令返回ACK
case 0xb0:
u8SendLen = 0;
I2C_WriteByte(I2C0,u8Recdata[u8SendLen++]);//发送数据首字节
break;
case 0xb8:
I2C_WriteByte(I2C0,u8Recdata[u8SendLen++]);
break;
case 0xc0:
case 0xc8:
break;
}
I2C_ClearIrq(I2C0);
}
void IIC_SlaveGpioConfig(void)
{
stc_i2c_addr_t stcSlaveAddr;
stc_gpio_config_t stcGpioCfg;
stc_i2c_config_t stcI2cCfg;
stc_sysctrl_clk_config_t stcCfg;
DDL_ZERO_STRUCT(stcCfg);
DDL_ZERO_STRUCT(stcI2cCfg);
DDL_ZERO_STRUCT(stcGpioCfg);
DDL_ZERO_STRUCT(stcSlaveAddr);
Sysctrl_ClkSourceEnable(SysctrlClkRCL,TRUE);
Sysctrl_SysClkSwitch(SysctrlClkRCL);
Sysctrl_SetRCHTrim(SysctrlRchFreq24MHz);
Sysctrl_SysClkSwitch(SysctrlClkRCH);
Sysctrl_ClkSourceEnable(SysctrlClkRCL,FALSE);
Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio,TRUE);
Sysctrl_SetPeripheralGate(SysctrlPeripheralI2c0,TRUE);
stcGpioCfg.enDir = GpioDirOut;
stcGpioCfg.enOD = GpioOdEnable;
stcGpioCfg.enPuPd = GpioPu;
Gpio_Init(GpioPortB, GpioPin8,&stcGpioCfg);//端口初始化
Gpio_Init(GpioPortB, GpioPin9,&stcGpioCfg);
Gpio_SetAfMode(GpioPortB, GpioPin8,GpioAf1);//SCL
Gpio_SetAfMode(GpioPortB, GpioPin9,GpioAf1);//SDA
stcI2cCfg.enFunc = I2cBaud_En;
stcI2cCfg.u8Tm = 0x02;//1M=(24000000/(8*(2+1))//波特率配置
stcI2cCfg.pfnI2c0Cb = I2c0CallBack;
stcI2cCfg.bTouchNvic = TRUE;
I2C_DeInit(I2C0);
stcSlaveAddr.Addr = 0x12;
stcSlaveAddr.Gc = 0;
I2C_Init(I2C0,&stcI2cCfg);//模块初始化
I2C_WriteSlaveAddr(I2C0,&stcSlaveAddr);//写从机设备地址
I2C_SetFunc(I2C0,I2cMode_En);//模块使能
I2C_SetFunc(I2C0,I2cAck_En);//ACK打开
if(TRUE == stcI2cCfg.bTouchNvic)
{
EnableNvic(I2C0_IRQn,IrqLevel3,TRUE);
}
}
int32_t main(void)
{
IIC_SlaveGpioConfig();
while(1)
{
}
}
|