GD32E230F下一个I2C通讯的代码
时间: 2024-05-02 08:16:42 浏览: 212
I2C通信代码
以下是使用GD32E230F芯片的I2C通信代码:
```c
#include "gd32e23x.h"
#define I2C_SCL_PIN GPIO_PIN_6
#define I2C_SDA_PIN GPIO_PIN_7
#define I2C_PORT GPIOB
#define I2C_SPEED 100000 // I2C通信速度为100KHz
void i2c_gpio_init(void)
{
rcu_periph_clock_enable(RCU_GPIOB);
gpio_init(I2C_PORT, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, I2C_SCL_PIN | I2C_SDA_PIN);
gpio_pin_remap_config(GPIO_I2C0_REMAP, ENABLE);
}
void i2c_config(void)
{
rcu_periph_clock_enable(RCU_I2C0);
i2c_clock_config(I2C0, I2C_SPEED, I2C_DTCY_2);
i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, 0x00);
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
i2c_enable(I2C0);
}
void i2c_write_byte(uint8_t device_addr, uint8_t reg_addr, uint8_t data)
{
i2c_start_on_bus(I2C0, I2C_I2CDEV_7BIT_ADDR(device_addr), I2C_SENDER);
while (!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));
i2c_master_addressing(I2C0, reg_addr, I2C_TRANSMITTER);
while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));
i2c_data_transmit(I2C0, data);
while (!i2c_flag_get(I2C0, I2C_FLAG_TBE));
i2c_stop_on_bus(I2C0);
}
uint8_t i2c_read_byte(uint8_t device_addr, uint8_t reg_addr)
{
uint8_t data;
i2c_start_on_bus(I2C0, I2C_I2CDEV_7BIT_ADDR(device_addr), I2C_SENDER);
while (!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));
i2c_master_addressing(I2C0, reg_addr, I2C_TRANSMITTER);
while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));
i2c_start_on_bus(I2C0, I2C_I2CDEV_7BIT_ADDR(device_addr), I2C_RECEIVER);
while (!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));
i2c_ack_config(I2C0, I2C_ACK_DISABLE);
i2c_stop_on_bus(I2C0);
i2c_start_on_bus(I2C0, I2C_I2CDEV_7BIT_ADDR(device_addr), I2C_RECEIVER);
i2c_ack_config(I2C0, I2C_ACK_DISABLE);
while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE));
data = i2c_data_receive(I2C0);
i2c_stop_on_bus(I2C0);
i2c_ack_config(I2C0, I2C_ACK_ENABLE);
return data;
}
int main(void)
{
i2c_gpio_init();
i2c_config();
uint8_t device_addr = 0x68;
uint8_t reg_addr = 0x00;
uint8_t data = 0x12;
i2c_write_byte(device_addr, reg_addr, data);
reg_addr = 0x01;
data = i2c_read_byte(device_addr, reg_addr);
while (1);
}
```
该代码使用GPIOB的6和7两个引脚作为I2C的SCL和SDA信号线,并且使用100KHz的速度进行通信。在main函数中,首先调用i2c_write_byte函数向I2C设备写入数据,然后调用i2c_read_byte函数从I2C设备中读取数据。需要根据具体的I2C设备地址、寄存器地址和数据来修改这两个函数的参数。
阅读全文