keil下的gd对fm17750 nfc芯片的串口初始化和通讯c程序
时间: 2024-03-23 22:36:05 浏览: 141
串口初始化C程序
以下是基于Keil的GD32F175x/6x固件库,使用USART1与FM17750 NFC芯片进行串口通讯的示例代码:
```c
#include "gd32f1x0.h"
#include <stdio.h>
#define USARTx USART1
#define USARTx_CLK RCC_APB2Periph_USART1
#define USARTx_GPIO_CLK RCC_AHBPeriph_GPIOA
#define USARTx_GPIO_PORT GPIOA
#define USARTx_RxPin GPIO_Pin_10
#define USARTx_TxPin GPIO_Pin_9
#define USARTx_IRQn USART1_IRQn
#define USARTx_IRQHandler USART1_IRQHandler
#define BUFFER_SIZE 64
uint8_t TxBuffer[BUFFER_SIZE];
uint8_t RxBuffer[BUFFER_SIZE];
__IO uint16_t TxCount = 0;
__IO uint16_t RxCount = 0;
void USART_Config(void)
{
USART_InitPara USART_InitStructure;
GPIO_InitPara GPIO_InitStructure;
RCC_AHBPeriphClock_Enable(USARTx_GPIO_CLK, ENABLE);
GPIO_PinAFConfig(USARTx_GPIO_PORT, GPIO_PinSource9, GPIO_AF_1);
GPIO_PinAFConfig(USARTx_GPIO_PORT, GPIO_PinSource10, GPIO_AF_1);
GPIO_InitStructure.GPIO_Pin = USARTx_TxPin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(USARTx_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USARTx_RxPin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USARTx_GPIO_PORT, &GPIO_InitStructure);
RCC_APB2PeriphClock_Enable(USARTx_CLK, ENABLE);
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USARTx, &USART_InitStructure);
USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE);
USART_Cmd(USARTx, ENABLE);
}
void USARTx_IRQHandler(void)
{
if (USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET)
{
RxBuffer[RxCount++] = USART_ReceiveData(USARTx);
}
if (USART_GetITStatus(USARTx, USART_IT_TXE) != RESET)
{
USART_SendData(USARTx, TxBuffer[TxCount++]);
if (TxCount == BUFFER_SIZE)
{
USART_ITConfig(USARTx, USART_IT_TXE, DISABLE);
}
}
}
void USART_SendString(char *str)
{
TxCount = 0;
while (*str && (TxCount < BUFFER_SIZE))
{
TxBuffer[TxCount++] = *str++;
}
USART_ITConfig(USARTx, USART_IT_TXE, ENABLE);
}
void USART_ReceiveString(char *str)
{
uint16_t i;
for (i = 0; i < RxCount; i++)
{
*str++ = RxBuffer[i];
}
*str = '\0';
RxCount = 0;
}
int main(void)
{
USART_Config();
char tx_str[] = "Hello FM17750";
char rx_str[BUFFER_SIZE];
while (1)
{
USART_SendString(tx_str);
while (TxCount < BUFFER_SIZE)
;
USART_ReceiveString(rx_str);
printf("Received message: %s\n", rx_str);
}
}
```
在上述代码中,我们使用USART1与FM17750 NFC芯片进行通讯。在main函数中,我们定义了一个发送字符串和接收字符串的缓冲区,并在循环中不断发送和接收数据。其中,USART_SendString函数用于发送字符串,USART_ReceiveString函数用于接收字符串。我们在接收到数据后,通过printf函数将接收到的数据打印出来。
注意:在使用该程序之前,需要先根据芯片手册,设置FM17750的串口通讯参数。
阅读全文