IIC总线应用真的太广泛了,介绍什么的就不说了。
GD32F407真的太像STM32F407了,之前用STM32的时候网上都说硬件IIC不稳定容易死机,不过没有真正在项目中使用过,主要官方给的源码都是while结构的,如何敢用,简直了。
最近项目用到了GD32F407的三组IIC,而且还有一组作为从机模式,如果用模拟GPIO方式来做从机之前真没有玩过,网上看资料不多(主要看有没现成拿来用,哈哈),那就都用硬件方式,咨询过GD的工程师完全可以用硬件来做项目的。但是非常遗憾的事GD的源码也是while结构的,单独运行起来杠杠的,但是能直接放到项目嘛,当然不行,那就直接修改了。下面记录修改过程,及遇到问题
一、下面是硬件IIC作为主机模式发送接受软件流程图
Datasheet上的主机发送 接收模式的软件流程图,中文版太给力了,这是第一次认真去分析每一步如何发送数据该如何设置标志和清除标志
主机发送模式下的软件流程
主机接受模式,A和B都差不多,
非常详细介绍了每一步应该如何判断哪个标志位清除哪个标志位,我们照着来就好了。
二、首先看看官方硬件接收源码:
/*!
\brief write more than one byte to the EEPROM with a single write cycle
\param[in] p_buffer: pointer to the buffer containing the data to be written to the EEPROM
\param[in] write_address: EEPROM's internal address to write to
\param[in] number_of_byte: number of bytes to write to the EEPROM
\param[out] none
\retval none
*/
void eeprom_page_write(uint8_t* p_buffer, uint8_t write_address, uint8_t number_of_byte)
{
/* wait until I2C bus is idle */
while(i2c_flag_get(I2C0, I2C_I2CBSY));
/* send a start condition to I2C bus */
i2c_start_on_bus(I2C0);
/* wait until SBSEND bit is set */
while(!i2c_flag_get(I2C0, I2C_SBSEND));
/* send slave address to I2C bus */
i2c_master_addressing(I2C0, eeprom_address, I2C_TRANSMITTER);
/* wait until ADDSEND bit is set */
while(!i2c_flag_get(I2C0, I2C_ADDSEND));
/* clear the ADDSEND bit */
i2c_flag_clear(I2C0,I2C_STAT0_ADDSEND);
/* wait until the transmit data buffer is empty */
while( SET != i2c_flag_get(I2C0, I2C_TBE));
/* send the EEPROM's internal address to write to : only one byte address */
i2c_transmit_data(I2C0, write_address);
/* wait until BTC bit is set */
while(!i2c_flag_get(I2C0, I2C_BTC));
/* while there is data to be written */
while(number_of_byte--){
i2c_transmit_data(I2C0, *p_buffer);
/* point to the next byte to be written */
p_buffer++;
/* wait until BTC bit is set */
while(!i2c_flag_get(I2C0, I2C_BTC));
}
/* send a stop condition to I2C bus */
i2c_stop_on_bus(I2C0);
/* wait until the stop condition is finished */
while(I2C_CTL0(I2C0)&0x0200);
}
都是while的结构,如果有一个地方卡主那就死机了,所以下面将它修改成不用while模式。用硬件IIC最好用中断模式,即在硬件标志了就会产生中断这个时候可你以处理数据。
下面是一个主机读写开始的一个函数,不管读数据还是写数据都是主机发送起始信号,
voi