- 串口一初始化
**Bound为串口波特率
void USART1_Init(int Bound)
{
GPIO_InitTypeDef GPIO_InitStruct;//定义引脚的结构体
USART_InitTypeDef USART_InitStruct;//定义串口的结构体
NVIC_InitTypeDef NVIC_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//打开串口1的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//打开引脚的时钟
///初始化引脚9 Tx
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //设置为复用输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStruct);
//初始化引脚10 Rx
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;//设置为上拉输入
GPIO_Init(GPIOA,&GPIO_InitStruct);
//初始化串口
USART_InitStruct.USART_BaudRate = Bound ;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1,&USART_InitStruct);
USART_Cmd(USART1,ENABLE);//使能串口一
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//打开接受中断
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1; //子优先级
NVIC_Init(&NVIC_InitStruct);
}
串口初始化已经完成
在调用串口初始化的时候,要在main函数提前分配中断组我的串口一初始化时按中断组二来分配的
int main()
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//中断组为2抢占优先级占2位子优先级占2位
Usart_Init(115200);//初始化串口一并使波特率为115200
return 0;
}
串口发送数据需要好几种定义发送字符串或数组或8位数据需要写好多行不便于管理和记忆以及后期的发送所以最好直接用c语言中的printf来一下实现这些东西
首先先把kill带的微型库选上然后把c99标准也选上
当完成上面操作的时候在文件里包含#include <stdio.h>头文件
代码如下
#include <stdio.h>
int fputc(int ch ,FILE *f)
{
USART_ClearFlag(USARTx,USART_FLAG_TC);
USART_SendData(USARTx,(uint8_t) ch);
while(USART_GetFlagStatus(USARTx,USART_FLAG_TC)==RESET);
return ch;
}