4508282e9bba0246eafd0a67642a2391c05c9ccc
[fw/sdcc] / device / lib / serial.c
1 //----------------------------------------------------------------------------
2 //Written by Dmitry S. Obukhov, 1996
3 // dso@usa.net 
4 //----------------------------------------------------------------------------
5 //This module implements serial interrupt handler and IO routinwes using
6 //two 256 byte cyclic buffers. Bit variables can be used as flags for 
7 //real-time kernel tasks
8 //Last modified 6 Apr 97
9 //----------------------------------------------------------------------------
10
11 #include "reg51.h"//This module contains definition of I8051 registers
12
13
14 static unsigned char xdata stx_index_in, srx_index_in, stx_index_out, srx_index_out;
15 static unsigned char xdata stx_buffer[0x100];
16 static unsigned char xdata srx_buffer[0x100];
17
18 static bit work_flag_byte_arrived;
19 static bit work_flag_buffer_transfered;
20 static bit tx_serial_buffer_empty;
21 static bit rx_serial_buffer_empty;
22
23
24 void serial_init(void)
25 {
26     SCON = 0x50;
27     T2CON = 0x34;
28     PS = 1;
29     T2CON = 0x34;
30     RCAP2H = 0xFF;
31     RCAP2L = 0xDA;
32     
33     RI = 0;
34     TI = 0;
35     
36     stx_index_in = srx_index_in = stx_index_out = srx_index_out = 0;
37     rx_serial_buffer_empty = tx_serial_buffer_empty = 1;
38     work_flag_buffer_transfered = 0;
39     work_flag_byte_arrived = 0;
40     ES=1;
41 }
42
43 void serial_interrupt_handler(void) interrupt 4 using 1
44 {
45     ES=0;
46     if ( TI )
47         {
48             TI = 0;
49             if (stx_index_out == stx_index_in )
50                 {
51                     tx_serial_buffer_empty = 1;
52                     work_flag_buffer_transfered = 1;
53                 }
54             else SBUF = stx_buffer[stx_index_out++];
55         }
56     if ( RI )
57         {
58             RI = 0;
59             srx_buffer[srx_index_in++]=SBUF;
60             work_flag_byte_arrived = 1;
61             rx_serial_buffer_empty = 0;
62         }
63     ES=1;
64 }
65
66 //Next two functions are interface
67
68 void serial_putc(unsigned char c)
69 {
70     stx_buffer[stx_index_in++]=c;
71     ES=0;
72     if ( tx_serial_buffer_empty )
73         {
74             tx_serial_buffer_empty = 0;
75             TI=1;
76         }
77     ES=1;
78 }
79
80 unsigned char serial_getc(void)
81 {
82     unsigned char tmp = srx_buffer[srx_index_out++];
83     ES=0;
84     if ( srx_index_out == srx_index_in) rx_serial_buffer_empty = 1;
85     ES=1;
86     return tmp;
87 }
88
89 //END OF MODULE