739d706069a49c0ca5a061f06c9a3f4040947164
[uccvend-snackrom.git] / ROM2 / sci.c
1 #include "vend.h"
2 #include "chime.h"
3 #include "sci.h"
4
5 char sci_tx_buf[BUFFER_LEN];
6 volatile char sci_rx_buf[BUFFER_LEN];
7 volatile bool sci_have_packet;
8 volatile u8 sci_rx_buf_ptr;
9
10 void sci_init() {
11         /* assumes clock of 4.91Mhz */
12         _io_ports[M6811_BAUD] = 0x03; /* 9600 baud */
13
14         /* Setup character format 1 start, 8-bits, 1 stop.  */
15         _io_ports[M6811_SCCR1] = 0;
16
17         /* Enable reciever and transmitter & rx interrupt.  */
18         _io_ports[M6811_SCCR2] = M6811_RIE | M6811_TE | M6811_RE;
19
20         sci_have_packet = 0;
21         sci_rx_buf_ptr = 0;
22 }
23
24 void send_packet() {
25         char* c;
26         for (c = sci_tx_buf; *c; c++) {
27                 /* wait for TX ready */
28                 while (!(_io_ports[M6811_SCSR] & M6811_TDRE));
29
30                 /* send byte */
31                 _io_ports[M6811_SCDR] = *c;
32         }
33 }
34
35 void sci_rx_int() {
36         /* XXX FIXME we should do something about errors. nack? */
37         if (sci_have_packet) {
38                 /* overrun :( */
39                 _io_ports[M6811_SCDR]; /* read it anyway */
40                 return;
41         }
42         sci_rx_buf[sci_rx_buf_ptr] = _io_ports[M6811_SCDR];
43         if (sci_rx_buf[sci_rx_buf_ptr] == '\n' ||
44                         sci_rx_buf[sci_rx_buf_ptr] == '\r') {
45                 if (sci_rx_buf_ptr == 0) return; /* we've read a blank packet in */
46                 sci_rx_buf[sci_rx_buf_ptr] = '\0';
47                 sci_have_packet = 1;
48                 sci_rx_buf_ptr = 0;
49         }
50         sci_rx_buf_ptr++;
51         if (sci_rx_buf_ptr >= BUFFER_LEN) {
52                 sci_rx_buf[BUFFER_LEN] = '\0'; /* this is as much as we could fit */
53                 sci_have_packet = 1;
54                 sci_rx_buf_ptr = 0;
55         }
56 }
57
58 void sci_interrupt_serial() {
59         chime_start();
60
61         if (_io_ports[M6811_SCSR] & M6811_RDRF) sci_rx_int();
62
63         if (_io_ports[M6811_SCSR] & M6811_OR)
64                 _io_ports[M6811_SCDR]; /* declare it a lost cause */
65 }
66
67 void msg_clr() {
68         sci_have_packet = 0;
69         sci_rx_buf_ptr = 0;
70 }
71
72 void send_ack() {
73         my_strncpy(sci_tx_buf, "!\n", BUFFER_LEN);
74         send_packet();
75 }
76
77 void send_nack() {
78         my_strncpy(sci_tx_buf, "?\n", BUFFER_LEN);
79         send_packet();
80 }

UCC git Repository :: git.ucc.asn.au