本文采用的是GD32F450芯片,基于此芯片的官网例程来对IIC读写EEPROM进行详解。
对于初学者来说,感觉IIC很复杂,时许逻辑很绕,无从下手。感觉很多概念不理解,但是不要慌,此文给你详解。 上来不多说,直接贴代码!
- 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_FLAG_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_FLAG_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_FLAG_ADDSEND));
-
- /* clear the ADDSEND bit */
- i2c_flag_clear(I2C0,I2C_FLAG_ADDSEND);
-
- /* wait until the transmit data buffer is empty */
- while( SET != i2c_flag_get(I2C0, I2C_FLAG_TBE));
-
- /* send the EEPROM's internal address to write to : only one byte address */
- i2c_data_transmit(I2C0, write_address);
-
- /* wait until BTC bit is set */
- while(!i2c_flag_get(I2C0, I2C_FLAG_BTC));
-
- /* while there is data to be written */
- while(number_of_byte--){
- i2c_data_transmit(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_FLAG_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);
- }
上面的代码是页写EEPROM的程序。不懂EEPROM页写,字节写概念的童靴,请自行百度一下,比较好理解,这个就不再赘述了。
|