GD32F103硬件IIC向器件发送一个字节数据
时间: 2023-08-04 20:02:39 浏览: 143
以下是使用GD32F103芯片的硬件IIC向器件发送一个字节数据的示例代码:
```c
#include "gd32f10x.h"
#define IIC_SCL_PIN GPIO_PIN_6
#define IIC_SDA_PIN GPIO_PIN_7
#define IIC_SCL_PORT GPIOB
#define IIC_SDA_PORT GPIOB
#define IIC_SCL_HIGH() gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN)
#define IIC_SCL_LOW() gpio_bit_reset(IIC_SCL_PORT, IIC_SCL_PIN)
#define IIC_SDA_HIGH() gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN)
#define IIC_SDA_LOW() gpio_bit_reset(IIC_SDA_PORT, IIC_SDA_PIN)
#define IIC_SDA_READ() gpio_input_bit_get(IIC_SDA_PORT, IIC_SDA_PIN)
void iic_init(void)
{
rcu_periph_clock_enable(RCU_GPIOB);
gpio_init(IIC_SCL_PORT, GPIO_MODE_OUT_OD, GPIO_OSPEED_50MHZ, IIC_SCL_PIN);
gpio_init(IIC_SDA_PORT, GPIO_MODE_OUT_OD, GPIO_OSPEED_50MHZ, IIC_SDA_PIN);
IIC_SCL_HIGH();
IIC_SDA_HIGH();
}
void iic_start(void)
{
IIC_SDA_HIGH();
IIC_SCL_HIGH();
delay_us(4);
IIC_SDA_LOW();
delay_us(4);
IIC_SCL_LOW();
}
void iic_stop(void)
{
IIC_SDA_LOW();
IIC_SCL_HIGH();
delay_us(4);
IIC_SDA_HIGH();
delay_us(4);
}
void iic_write_byte(uint8_t data)
{
uint8_t i;
for (i = 0; i < 8; i++)
{
if ((data & 0x80) != 0)
{
IIC_SDA_HIGH();
}
else
{
IIC_SDA_LOW();
}
data <<= 1;
IIC_SCL_HIGH();
delay_us(2);
IIC_SCL_LOW();
delay_us(2);
}
}
int main(void)
{
iic_init();
iic_start();
iic_write_byte(0x55); // 发送0x55
iic_stop();
while (1);
return 0;
}
```
在此示例中,使用PB6和PB7作为IIC的SCL和SDA线,通过调用iic_init()函数初始化GPIO口。然后,使用iic_start()函数发送IIC起始信号,使用iic_write_byte()函数向器件发送一个字节的数据,最后使用iic_stop()函数发送IIC停止信号。
阅读全文