usart.h
usart.h
如下:
#ifndef __USART_H
#define __USART_H
#include "stdio.h"
extern u8 USART_RX_BUF[];
extern u8 USART_RX_STA;
void uart2_init ( u32 bound );
#endif
usart.c
usart.c
如下:
#include "sys.h"
#include "usart.h"
#if 1
#pragma import(__use_no_semihosting)
struct __FILE {
int handle;
};
FILE __stdout;
void _sys_exit ( int x ) {
x = x;
}
int fputc ( int ch, FILE *f ) {
while ( ( USART2->SR & 0X40 ) == 0 );
USART2->DR = ( u8 ) ch;
return ch;
}
#endif
u8 USART_RX_BUF[64];
u8 USART_RX_STA = 0;
void uart2_init ( u32 bound ) {
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* 注意! */
RCC_APB2PeriphClockCmd ( RCC_APB2Periph_GPIOA, ENABLE );
RCC_APB1PeriphClockCmd ( RCC_APB1Periph_USART2, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init ( GPIOA, &GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init ( GPIOA, &GPIO_InitStructure );
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init ( &NVIC_InitStructure );
USART_InitStructure.USART_BaudRate = bound;
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 ( USART2, &USART_InitStructure );
USART_ITConfig ( USART2, USART_IT_RXNE, ENABLE );
USART_Cmd ( USART2, ENABLE );
}
void USART2_IRQHandler ( void ) {
u8 Res;
if ( USART_GetITStatus ( USART2, USART_IT_RXNE ) != RESET ) {
Res = USART_ReceiveData ( USART2 );
if ( ( USART_RX_STA & 0x80 ) == 0 ) {
if ( USART_RX_STA & 0x40 ) {
if ( Res != 0x0a ) {
USART_RX_STA = 0;
} else {
USART_RX_STA |= 0x80;
}
} else {
if ( Res == 0x0d ) {
USART_RX_STA |= 0x40;
} else {
USART_RX_BUF[USART_RX_STA & 0X3F] = Res;
USART_RX_STA++;
if ( USART_RX_STA > 63 ) {
USART_RX_STA = 0;
}
}
}
}
}
}
main.c
main.c
如下:
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "led.h"
int main ( void ) {
SystemInit();
delay_init ( 72 );
NVIC_Configuration();
uart2_init ( 9600 );
LED_Init();
while ( 1 ) {
LED0 = !LED0;
printf ( "hello, world\r\n" );
if ( USART_RX_STA & 0x80 ) {
u8 t;
u8 len = USART_RX_STA & 0x3f; // 得到此次接收到的数据长度
printf ( "\r\n您发送的消息为: " );
for ( t = 0; t < len; t++ ) {
USART2->DR = USART_RX_BUF[t];
while ( ( USART2->SR & 0X40 ) == 0 ); // 等待发送结束
}
printf ( "\r\n" ); // 插入换行
USART_RX_STA = 0;
}
delay_ms ( 500 );
}
}