查看原理图中定义的I2C的管脚,PB0和PB1
在board.ve中定义的引脚功能
I2C0_SDA PIN_36
I2C0_SCL PIN_35
新建工程
测试代码
#include "board.h"
#define MIN_IRQ_PRIORITY 1
#define MAX_IRQ_PRIORITY PLIC_MAX_PRIORITY
#define I2C_PRIORITY (MIN_IRQ_PRIORITY + 1)
void I2cISR()
{
I2C_ClearInt(I2C0);
}
int main(void)
{
board_init();
plic_isr[I2C0_IRQn] = I2cISR;
PERIPHERAL_ENABLE(I2C, 0);
INT_EnableIRQ(I2C0_IRQn, I2C_PRIORITY);
uint32_t frequency = 400e3;
I2C_Init(I2C0, frequency);
uint32_t pclk_freq = SYS_GetPclkFreq();
uint16_t prescaler = I2C_GetPrescaler(I2C0);
printf("I2C frequency: %d, prescaler: %d, apb clk frequency: %d\n", frequency, prescaler, pclk_freq);
if (fabs((prescaler + 1) * 5.0 * frequency / pclk_freq - 1) > 0.01) {
printf("I2C prescaler read mismatch, 0x%02x%02x, %d, %d\n", I2C0->PRERHI, I2C0->PRERLO, frequency, pclk_freq);
return false;
}
I2C_Enable(I2C0);
#define LSM6DSR_IIC_ADDR 0x68
#define LSM6DSR_WHO_AM_I 0x75
I2C_StartSend(I2C0, LSM6DSR_IIC_ADDR);
I2C_SendData(I2C0, LSM6DSR_WHO_AM_I);
I2C_StartReceive(I2C0, LSM6DSR_IIC_ADDR);
I2C_WaitForTransfer(I2C0);
uint8_t data;
data = I2C_StopReceiveWait(I2C0);
// data = I2C_ReceiveDataWait(I2C0);
printf("who am i is %x", data);
return 0;
}
串口调试终端输出,who am i 寄存器数据符合预期
通过逻辑分析仪抓取的I2C波形
视频讲解