本帖最后由 heqiaosheng 于 2015-7-21 23:24 编辑
GD32F130使用的是STM32F0xx的库,芯片选的是STM32F103R8。SDA、SCL没有波形,外部有上拉地址。代码如下:
/**
* @brief I2C接口初始化
* 初始化为I2C1主机,7位地址模式,启用模拟滤波器,停用数字滤波器,
* 启用应答,I2C传输速度100KHz
* @param 无
* @retval 无
*/
void I2C2_Init_Config(void)
{
I2C_InitTypeDef I2C_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOF, ENABLE); //使能GPIOB时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
/*
//I2C PF6 PF7
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;// 开漏
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOF, &GPIO_InitStructure); //
*/
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_AnalogFilter = I2C_AnalogFilter_Enable;
I2C_InitStructure.I2C_DigitalFilter = 0x01;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_Timing = 0x40B22536;
I2C_Cmd(I2C2, ENABLE);
I2C_Init(I2C2, &I2C_InitStructure);
}
/**
* @brief 从I2C1总线上的某一器件的某一起始地址中读取一定字节的数据到数组中
* @param driver_Addr:I2C器件地址
* @param start_Addr1:起始字节地址1
* @param start_Addr2:起始字节地址2
* @param number_Bytes:要读取的字节数量(小于一页)
* @param read_Buffer:存放读取数据的数组指针
* @retval 是否读取成功
*/
I2C_Status I2C2_Read_NBytes2(uint8_t driver_Addr, uint8_t start_Addr1, uint8_t start_Addr2, uint8_t number_Bytes, uint8_t *read_Buffer)
{
uint8_t read_Num;
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_BUSY) != RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL;
}
}
I2C_TransferHandling(I2C2, driver_Addr, 1, I2C_SoftEnd_Mode, I2C_Generate_Start_Write);
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_TXIS) == RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL+1;
}
}
I2C_SendData(I2C2, start_Addr1);
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_TXIS) == RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL+2;
}
}
I2C_SendData(I2C2, start_Addr2);
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_TC) == RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL+3;
}
}
I2C_TransferHandling(I2C2, driver_Addr, number_Bytes, I2C_AutoEnd_Mode, I2C_Generate_Start_Read);
for(read_Num = 0; read_Num < number_Bytes; read_Num++)
{
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_RXNE) == RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL+4;
}
}
read_Buffer[read_Num] = I2C_ReceiveData(I2C2);
}
I2C_Timeout = I2C_TIMEOUT;
while(I2C_GetFlagStatus(I2C2, I2C_FLAG_STOPF) == RESET)
{
if((I2C_Timeout--) == 0)
{
return I2C_FAIL+5;
}
}
return I2C_OK;
}
|