初级会员

- 积分
- 67
- 金钱
- 67
- 注册时间
- 2016-9-7
- 在线时间
- 11 小时
|

楼主 |
发表于 2016-9-20 00:20:21
|
显示全部楼层
#include "stm32f10x.h"
void usart_init()
{
GPIO_InitTypeDef GPIO_InitStrue;
USART_InitTypeDef USART_InitStrue;
NVIC_InitTypeDef NVIC_InitStrue;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //串口时钟使能,GPIO时钟使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
//GPIO_Pin_9和GPIO_Pin_10端口复用
GPIO_InitStrue.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStrue.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStrue.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStrue);
GPIO_InitStrue.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStrue.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStrue.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStrue);
//串口初始化
USART_InitStrue.USART_BaudRate=115200; //波特率设置
USART_InitStrue.USART_HardwareFlowControl=USART_HardwareFlowControl_None; //硬件流控制没有使用
USART_InitStrue.USART_Mode=USART_Mode_Tx|USART_Mode_Rx; //发送接收或者都使能(模式)
USART_InitStrue.USART_Parity=USART_Parity_No; //奇偶效验
USART_InitStrue.USART_StopBits=USART_StopBits_1; //停止位入口参数 设置为一位停止位
USART_InitStrue.USART_WordLength=USART_WordLength_8b; //字长,因为没有级偶校验所以是8位
USART_Init(USART1,&USART_InitStrue);
USART_Cmd(USART1,ENABLE); //串口使能,不使用串口中断的话到这里就完了
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); //接收使能开启
NVIC_InitStrue.NVIC_IRQChannel=USART1_IRQn;
NVIC_InitStrue.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStrue.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStrue.NVIC_IRQChannelSubPriority=1;
NVIC_Init(&NVIC_InitStrue); //中断函数
}
void USART1_IRQHandler(void) //串口中断服务程序
{
u8 res;
if(USART_GetITStatus(USART1,USART_IT_RXNE))
{
res= USART_ReceiveData(USART1);
USART_SendData(USART1,res);
}
}
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
usart_init();
while(1);
} |
|