-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial.c
84 lines (73 loc) · 2.14 KB
/
serial.c
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
#include <at89c5131.h>
bit tx_complete = 0,rx_complete = 0; //Bit flags for interrupts
/********************
uart_init():
Initialization function to be completed
Initializes UART peripheral for 8-bit transfer,
1 start and 1 stop bits.
Please write TH1 value for required baud rate
*********************/
void uart_init(void)
{
TMOD=0x20; //Configure Timer 1 in Mode 2
TH1=243; //Load TH1 to obtain require Baudrate (Refer Serial.pdf for calculations)
SCON=0x50; //Configure UART peripheral for 8-bit data transfer
TR1=1; //Start Timer 1
EA=1; //Enable Serial Interrupt
ES=1; //Enable Global Interrupt
}
/********************
transmit_char(<unsigned char ch>):
Transmits a character using UART
*********************/
void transmit_char(unsigned char ch)
{
SBUF=ch; //Load data in SBUF
while(!tx_complete); //Wait for tx_complete flag (interrupt to complete)
tx_complete = 0; //Clear tx_complete flag
}
/********************
transmit_string(<String pointer>):
Transmit a string using UART
*********************/
void transmit_string(unsigned char *s)
{
while(*s != 0)
{
transmit_char(*s++);
}
}
/********************
receive_char():
Receives a character through UART. Returns a
character.
*********************/
unsigned char receive_char(void)
{
unsigned char ch = 0;
while(!rx_complete); //Wait for rx_complete(interrupt to complete)
rx_complete = 0;
ch = SBUF; //Read data from SBUF
return ch; //Return read character
}
/********************
Serial_ISR():
Interrupt service routine for UART interrupt.
Determines whether it is a transmit or receive
interrupt and raise corresponding flag.
Transmit or receive functions (defined above) monitor
for these flags to check if data transfer is done.
*********************/
void serial_ISR(void) interrupt 4
{
if(TI==1) //check whether TI is set
{
TI = 0; //Clear TI flag
tx_complete = 1; //Set tx_complete flag indicating interrupt completion
}
else if(RI==1) //check whether RI is set
{
RI = 0; //Clear RI flag
rx_complete = 1; //Set rx_complete flag indicating interrupt completion
}
}