Imported Upstream version 2.9.0
[debian/cc1111] / 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 //This module contains definition of I8051 registers
12 #include "8052.h"
13
14
15 static unsigned char __xdata stx_index_in, srx_index_in, stx_index_out, srx_index_out;
16 static unsigned char __xdata stx_buffer[0x100];
17 static unsigned char __xdata srx_buffer[0x100];
18
19 static __bit work_flag_byte_arrived;
20 static __bit work_flag_buffer_transfered;
21 static __bit tx_serial_buffer_empty;
22 static __bit rx_serial_buffer_empty;
23
24
25 void serial_init(void)
26 {
27     SCON = 0x50;
28     T2CON = 0x34;
29     PS = 1;
30     T2CON = 0x34;
31     RCAP2H = 0xFF;
32     RCAP2L = 0xDA;
33     
34     RI = 0;
35     TI = 0;
36     
37     stx_index_in = srx_index_in = stx_index_out = srx_index_out = 0;
38     rx_serial_buffer_empty = tx_serial_buffer_empty = 1;
39     work_flag_buffer_transfered = 0;
40     work_flag_byte_arrived = 0;
41     ES=1;
42 }
43
44 void serial_interrupt_handler(void) __interrupt 4 __using 1
45 {
46     ES=0;
47     if ( RI )
48         {
49             RI = 0;
50             srx_buffer[srx_index_in++]=SBUF;
51             work_flag_byte_arrived = 1;
52             rx_serial_buffer_empty = 0;
53         }
54     if ( TI )
55         {
56             TI = 0;
57             if (stx_index_out == stx_index_in )
58                 {
59                     tx_serial_buffer_empty = 1;
60                     work_flag_buffer_transfered = 1;
61                 }
62             else SBUF = stx_buffer[stx_index_out++];
63         }
64     ES=1;
65 }
66
67 //Next two functions are interface
68
69 void serial_putc(unsigned char c)
70 {
71     stx_buffer[stx_index_in++]=c;
72     ES=0;
73     if ( tx_serial_buffer_empty )
74         {
75             tx_serial_buffer_empty = 0;
76             TI=1;
77         }
78     ES=1;
79 }
80
81 unsigned char serial_getc(void)
82 {
83     unsigned char tmp = srx_buffer[srx_index_out++];
84     ES=0;
85     if ( srx_index_out == srx_index_in) rx_serial_buffer_empty = 1;
86     ES=1;
87     return tmp;
88 }
89
90 //END OF MODULE