本帖最后由 AnkerSong 于 2022-2-10 13:07 编辑
初始化:void CT7112_Init(void)
{
/* enable GPIOB clock */
rcu_periph_clock_enable(RCU_GPIOB);
/* enable I2C0 clock */
rcu_periph_clock_enable(RCU_I2C0);
/* enable AF clock */
rcu_periph_clock_enable(RCU_AF);
/* connect PB8 to I2C0_SCL */
/* connect PB9 to I2C0_SDA */
gpio_init(GPIOB, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, SCL_PIN | SDA_PIN );
/* PB8\9需remap */
gpio_pin_remap_config(GPIO_I2C0_REMAP,ENABLE);
/* configure I2C clock */
i2c_clock_config(I2C0, I2C_SPEED, I2C_DTCY_2);
/* configure I2C address */
i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, 0);
/* enable I2C0 */
i2c_enable(I2C0);
/* enable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
读取:
uint8_t CT7112_Read(uint8_t adr,uint8_t* val){
/* wait until I2C bus is idle */
while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
i2c_ackpos_config(I2C0, I2C_ACKPOS_NEXT);
/* 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, CT7112_Slave_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));
/* enable I2C0*/
i2c_enable(I2C0);
/* send the EEPROM's internal address to write to */
i2c_data_transmit(I2C0, 0x00);
/* 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);
delay_1ms(40);
/* 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, CT7112_Slave_Address | 0x01, I2C_RECEIVER);
/* disable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_DISABLE);
/* 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);
/* while there is data to be read */
/* 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);
if(i2c_flag_get(I2C0, I2C_FLAG_RBNE))
val[0] = i2c_data_receive(I2C0);
if(i2c_flag_get(I2C0, I2C_FLAG_RBNE))
val[1] = i2c_data_receive(I2C0);
/* wait until the stop condition is finished */
while(I2C_CTL0(I2C0) & 0x0200);
/* enable acknowledge */
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
i2c_ackpos_config(I2C0, I2C_ACKPOS_CURRENT);
return 0;
}
以上代码我读写测试正常。
(21ic的代码功能太难用了)
|