使用国民技术的N32G455REL7新型号进行串口6中断接收数据及发送实验。源码分享及效果展示:
main.c代码段:
#include "n32g45x.h"
#include "bsp_uart6.h"
int main()
{
bsp_init_uart6(9600);
for(;;)
{
}
}
bsp_uart6.c代码段:
#include "bsp_uart6.h"
uint8_t buf[256];
uint8_t len = 0;
void bsp_init_uart6(u32 baud)
{
GPIO_InitType GPIO_InitStructure;
NVIC_InitType NVIC_InitStructure;
USART_InitType USART_InitStructure;
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_UART6, ENABLE);
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOC | RCC_APB2_PERIPH_AFIO, ENABLE);
GPIO_ConfigPinRemap(GPIO_RMP2_UART6, ENABLE);
USART_DeInit(UART6);
//USART6_TX PC0
GPIO_InitStructure.Pin = GPIO_PIN_0; //PC0
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitPeripheral(GPIOC, &GPIO_InitStructure);
//USART6_RX PC1
GPIO_InitStructure.Pin = GPIO_PIN_1;//PC1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitPeripheral(GPIOC, &GPIO_InitStructure);
//USART
USART_InitStructure.BaudRate = baud;
USART_InitStructure.WordLength = USART_WL_8B;
USART_InitStructure.StopBits = USART_STPB_1;
USART_InitStructure.Parity = USART_PE_NO;
USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
USART_InitStructure.Mode = USART_MODE_TX | USART_MODE_RX;
USART_Init(UART6, &USART_InitStructure);
USART_ClrFlag(UART6, USART_FLAG_IDLEF);
USART_ClrFlag(UART6, USART_FLAG_RXDNE);
USART_ConfigInt(UART6, USART_INT_IDLEF, ENABLE);
USART_ConfigInt(UART6, USART_INT_RXDNE, ENABLE);
USART_Enable(UART6, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = UART6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void bsp_uart6_send_a_byte(u8 byte)
{
while(USART_GetFlagStatus(UART6, USART_FLAG_TXC) == RESET);
USART_SendData(UART6, byte);
while(USART_GetFlagStatus(UART6, USART_FLAG_TXC) == RESET);
}
void bsp_uart6_send_bytes(u8 *bytes, u16 len_bytes)
{
u16 i;
for(i = 0; i < len_bytes; i++)
{
bsp_uart6_send_a_byte(bytes[i]);
}
}
void UART6_IRQHandler(void)
{
if(USART_GetIntStatus(UART6, USART_INT_RXDNE) != RESET)
{
buf[len++] = USART_ReceiveData(UART6);
USART_ClrIntPendingBit(UART6, USART_INT_RXDNE);
}
else if(USART_GetIntStatus(UART6, USART_INT_IDLEF) != RESET)
{
bsp_uart6_send_bytes(buf, len);
len = 0;
USART_ClrIntPendingBit(UART6, USART_INT_IDLEF);
}
}
bsp_uart6.h代码段:
#ifndef __BSP_USART6_H
#define __BSP_USART6_H
#include "n32g45x.h"
void bsp_init_uart6(u32 bound);
void bsp_uart6_send_a_byte(u8 byte);
void bsp_uart6_send_bytes(u8 *bytes, u16 len_bytes);
#endif
实验效果如下图:
在编码过程中遇到的坑就是寄存器的配置,只要寄存器配置好,一版来说就可以实现收发收据了。