设置GD32F103硬件iic程序
时间: 2023-12-12 13:04:53 浏览: 100
基于STM32F103系列单片机,通过拨码开关,外部硬件设置PCB ID,带程序源码及原理图,C,C++源码.zip
5星 · 资源好评率100%
以下是基于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_CLOCK RCU_GPIOB
#define IIC_SDA_CLOCK RCU_GPIOB
```
然后,需要初始化IIC总线:
```c
void iic_init(void)
{
rcu_periph_clock_enable(IIC_SCL_CLOCK);
rcu_periph_clock_enable(IIC_SDA_CLOCK);
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);
gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN);
gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN);
}
```
接下来,需要编写IIC开始、停止、发送和接收函数:
```c
void iic_start(void)
{
gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN);
gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN);
gpio_bit_reset(IIC_SDA_PORT, IIC_SDA_PIN);
gpio_bit_reset(IIC_SCL_PORT, IIC_SCL_PIN);
}
void iic_stop(void)
{
gpio_bit_reset(IIC_SCL_PORT, IIC_SCL_PIN);
gpio_bit_reset(IIC_SDA_PORT, IIC_SDA_PIN);
gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN);
gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN);
}
void iic_send_byte(uint8_t byte)
{
uint8_t i;
for (i = 0; i < 8; i++) {
if (byte & 0x80) {
gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN);
} else {
gpio_bit_reset(IIC_SDA_PORT, IIC_SDA_PIN);
}
byte <<= 1;
delay_us(1);
gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN);
delay_us(1);
gpio_bit_reset(IIC_SCL_PORT, IIC_SCL_PIN);
delay_us(1);
}
}
uint8_t iic_receive_byte(void)
{
uint8_t i, byte = 0;
gpio_bit_set(IIC_SDA_PORT, IIC_SDA_PIN);
for (i = 0; i < 8; i++) {
gpio_bit_set(IIC_SCL_PORT, IIC_SCL_PIN);
delay_us(1);
byte <<= 1;
if (gpio_input_bit_get(IIC_SDA_PORT, IIC_SDA_PIN)) {
byte |= 0x01;
}
gpio_bit_reset(IIC_SCL_PORT, IIC_SCL_PIN);
delay_us(1);
}
return byte;
}
```
最后,可以使用以上函数来进行IIC通信操作。例如,向IIC设备写入数据:
```c
void iic_write(uint8_t address, uint8_t data)
{
iic_start();
iic_send_byte(address << 1);
iic_send_byte(data);
iic_stop();
}
```
读取IIC设备数据:
```c
uint8_t iic_read(uint8_t address)
{
uint8_t data;
iic_start();
iic_send_byte((address << 1) | 0x01);
data = iic_receive_byte();
iic_stop();
return data;
}
```
以上是一个基于GD32F103芯片的硬件IIC程序示例,具体实现可能需要根据具体情况进行调整和优化。
阅读全文