这篇文章来看看 GD32 给我们提供的 gpio_af_set() 函数吧。该函数的功能是配置 GPIO的复用功能,如:可以配置某个IO位串口的Tx或Rx等。

函数实现

文件位置:gd32f1x0_gpio.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*!
\brief set GPIO alternate function
\param[in] gpio_periph: GPIOx(x = A,B,C,D,F)
only one parameter can be selected which is shown as below:
\arg GPIOx(x = A,B,C,D,F)
\param[in] alt_func_num: GPIO pin af function, please refer to specific device datasheet
only one parameter can be selected which is shown as below:
\arg GPIO_AF_0: TIMER2, TIMER13, TIMER14, TIMER16, SPI0, I2S0, SPI1, SPI2, I2S2, CK_OUT,
SWDIO, SWCLK, USART0, CEC, IFRP, I2C0, I2C1, TSI, EVENTOUT
\arg GPIO_AF_1: USART0, USART1, IFRP, CEC, TIMER2, TIMER14, I2C0, I2C1, I2C2, EVENTOUT
\arg GPIO_AF_2: TIMER0, TIMER1, TIMER15, TIMER16, EVENTOUT
\arg GPIO_AF_3: TSI, I2C0, TIMER14, EVENTOUT
\arg GPIO_AF_4(port A,B only): TIMER13, I2C0, I2C1, I2C2, USART1
\arg GPIO_AF_5(port A,B only): TIMER15, TIMER16, SPI2, I2S2, I2C0, I2C1
\arg GPIO_AF_6(port A,B only): SPI1, EVENTOUT
\arg GPIO_AF_7(port A only): CMP0, CMP1
\arg GPIO_AF_9(port A,B only): CAN0, CAN1 (only for GD32F170/F190 series)
\arg GPIO_AF_11: SLCD (only for GD32F170/F190 series)
\param[in] pin: GPIO pin
one or more parameters can be selected which are shown as below:
\arg GPIO_PIN_x(x=0..15), GPIO_PIN_ALL
\param[out] none
\retval none
*/
void gpio_af_set(uint32_t gpio_periph, uint32_t alt_func_num, uint32_t pin)
{
uint16_t i;
uint32_t afrl, afrh;

afrl = GPIO_AFSEL0(gpio_periph);
afrh = GPIO_AFSEL1(gpio_periph);

for(i = 0U;i < 8U;i++){
if((1U << i) & pin){
/* clear the specified pin alternate function bits */
afrl &= ~GPIO_AFR_MASK(i);
afrl |= GPIO_AFR_SET(i,alt_func_num);
}
}

for(i = 8U;i < 16U;i++){
if((1U << i) & pin){
/* clear the specified pin alternate function bits */
afrh &= ~GPIO_AFR_MASK(i - 8U);
afrh |= GPIO_AFR_SET(i - 8U,alt_func_num);
}
}

GPIO_AFSEL0(gpio_periph) = afrl;
GPIO_AFSEL1(gpio_periph) = afrh;
}

alt_func_num 参数

该参数用来指定 GPIO 的具体用作什么功能。

alt_func_num 功能
GPIO_AF_0 TIMER2, TIMER13, TIMER14, TIMER16, SPI0, I2S0, SPI1, SPI2, I2S2, CK_OUT, SWDIO, SWCLK, USART0, CEC, IFRP, I2C0, I2C1, TSI, EVENTOUT
GPIO_AF_1 USART0, USART1, IFRP, CEC, TIMER2, TIMER14, I2C0, I2C1, I2C2, EVENTOUT
GPIO_AF_2 TIMER0, TIMER1, TIMER15, TIMER16, EVENTOUT
GPIO_AF_3 TSI, I2C0, TIMER14, EVENTOUT
GPIO_AF_4(port A,B only) TIMER13, I2C0, I2C1, I2C2, USART1
GPIO_AF_5(port A,B only) TIMER15, TIMER16, SPI2, I2S2, I2C0, I2C1
GPIO_AF_6(port A,B only) SPI1, EVENTOUT
GPIO_AF_7(port A only) CMP0, CMP1
GPIO_AF_9(port A,B only) CAN0, CAN1 (only for GD32F170/F190 series)
GPIO_AF_11 SLCD (only for GD32F170/F190 series)