-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusart.c
More file actions
119 lines (96 loc) · 2.36 KB
/
usart.c
File metadata and controls
119 lines (96 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "sys.h"
#include "usart.h"
#include "includes.h" //ucos ʹÓÃ
#endif
#if 1
#pragma import(__use_no_semihosting)
struct __FILE
{
int handle;
/* Whatever you require here. If the only file you are using is */
/* standard output using printf() for debugging, no file handling */
/* is required. */
};
/* FILE is typedef¡¯ d in stdio.h. */
FILE __stdout;
_sys_exit(int x)
{
x = x;
}
int fputc(int ch, FILE *f)
{
while((USART1->SR&0X40)==0);
USART1->DR = (u8) ch;
return ch;
}
#endif
//end
//////////////////////////////////////////////////////////////////
#if EN_USART1_RX //enable receive
u8 USART_RX_BUF[USART_REC_LEN];
//bit15£¬ finished
//bit14£¬ receive 0x0d
//bit13~0£¬ number of data
u16 USART_RX_STA=0; //status
void USART1_IRQHandler(void)
{
u8 res;
#if SYSTEM_SUPPORT_OS .
OSIntEnter();
#endif
if(USART1->SR&(1<<5))//receive data
{
res=USART1->DR;
if((USART_RX_STA&0x8000)==0)//unfinished
{
if(USART_RX_STA&0x4000)//receive 0x0d
{
if(res!=0x0a)USART_RX_STA=0;//error
else USART_RX_STA|=0x8000; //finished
}else /
{
if(res==0x0d)USART_RX_STA|=0x4000;
else
{
USART_RX_BUF[USART_RX_STA&0X3FFF]=res;
USART_RX_STA++;
if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;//error
}
}
}
}
#if SYSTEM_SUPPORT_OS
OSIntExit();
#endif
}
#endif
//Init IO USART1
//pclk2:PCLK2(Mhz)
//bound:
void uart_init(u32 pclk2,u32 bound)
{
float temp;
u16 mantissa;
u16 fraction;
temp=(float)(pclk2*1000000)/(bound*16);
mantissa=temp;
fraction=(temp-mantissa)*16;
mantissa<<=4;
mantissa+=fraction;
RCC->AHB1ENR|=1<<0; //ENABLE PORTA Clock
RCC->APB2ENR|=1<<4; //ENABLE USART1 Clock
GPIO_Set(GPIOA,PIN9|PIN10,GPIO_MODE_AF,GPIO_OTYPE_PP,GPIO_SPEED_50M,GPIO_PUPD_PU);
GPIO_AF_Set(GPIOA,9,7); //PA9,AF7
GPIO_AF_Set(GPIOA,10,7);//PA10,AF7
//set bound
USART1->BRR=mantissa;
USART1->CR1&=~(1<<15);
USART1->CR1|=1<<3; //ENABLE USART1
#if EN_USART1_RX
//ENABLE receive interupt
USART1->CR1|=1<<2;
USART1->CR1|=1<<5; //
MY_NVIC_Init(3,3,USART1_IRQn,2);
#endif
USART1->CR1|=1<<13;
}