More things to hopefully make this work.
[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] = '\0';
45                 sci_have_packet = 1;
46                 sci_rx_buf_ptr = 0;
47         }
48         sci_rx_buf_ptr++;
49         if (sci_rx_buf_ptr >= BUFFER_LEN) {
50                 sci_rx_buf[BUFFER_LEN] = '\0'; /* this is as much as we could fit */
51                 sci_have_packet = 1;
52                 sci_rx_buf_ptr = 0;
53         }
54 }
55
56 void sci_interrupt_serial() {
57         chime_start();
58
59         if (_io_ports[M6811_SCSR] & M6811_RDRF) sci_rx_int();
60
61         if (_io_ports[M6811_SCSR] & M6811_OR)
62                 _io_ports[M6811_SCDR]; /* declare it a lost cause */
63 }
64
65 void msg_clr() {
66         sci_have_packet = 0;
67         sci_rx_buf_ptr = 0;
68 }
69
70 void send_ack() {
71         sci_tx_buf[0] = '!';
72         sci_tx_buf[1] = '\n';
73         sci_tx_buf[2] = '\0';
74         send_packet();
75 }
76
77 void send_nack() {
78         sci_tx_buf[0] = '?';
79         sci_tx_buf[1] = '\n';
80         sci_tx_buf[2] = '\0';
81         send_packet();
82 }

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