Initial Commit
[simavr] / simavr / sim / avr_uart.c
1 /*
2         avr_uart.c
3
4         Handles UART access
5         Right now just handle "write" to the serial port at any speed
6         and printf to the console when '\n' is written.
7
8         Copyright 2008, 2009 Michel Pollet <buserror@gmail.com>
9
10         This file is part of simavr.
11
12         simavr is free software: you can redistribute it and/or modify
13         it under the terms of the GNU General Public License as published by
14         the Free Software Foundation, either version 3 of the License, or
15         (at your option) any later version.
16
17         simavr is distributed in the hope that it will be useful,
18         but WITHOUT ANY WARRANTY; without even the implied warranty of
19         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20         GNU General Public License for more details.
21
22         You should have received a copy of the GNU General Public License
23         along with simavr.  If not, see <http://www.gnu.org/licenses/>.
24  */
25
26 #include <stdio.h>
27 #include "avr_uart.h"
28
29 static void avr_uart_run(avr_t * avr, avr_io_t * port)
30 {
31 //      printf("%s\n", __FUNCTION__);
32 }
33
34 static uint8_t avr_uart_read(struct avr_t * avr, uint8_t addr, void * param)
35 {
36 //      avr_uart_t * p = (avr_uart_t *)param;
37         uint8_t v = avr->data[addr];
38 //      printf("** PIN%c = %02x\n", p->name, v);
39         return v;
40 }
41
42 static void avr_uart_write(struct avr_t * avr, uint8_t addr, uint8_t v, void * param)
43 {
44         avr_uart_t * p = (avr_uart_t *)param;
45
46         if (addr == p->r_udr) {
47         //      printf("UDR%c(%02x) = %02x\n", p->name, addr, v);
48                 avr_core_watch_write(avr, addr, v);
49                 avr_regbit_set(avr, p->udre);
50
51                 static char buf[128];
52                 static int l = 0;
53                 buf[l++] = v < ' ' ? '.' : v;
54                 buf[l] = 0;
55                 if (v == '\n' || l == 127) {
56                         l = 0;
57                         printf("\e[32m%s\e[0m\n", buf);
58                 }
59         }
60 }
61
62 void avr_uart_reset(avr_t * avr, struct avr_io_t *io)
63 {
64         avr_uart_t * p = (avr_uart_t *)io;
65         avr_regbit_set(avr, p->udre);
66 }
67
68 static  avr_io_t        _io = {
69         .kind = "uart",
70         .run = avr_uart_run,
71         .reset = avr_uart_reset,
72 };
73
74 void avr_uart_init(avr_t * avr, avr_uart_t * p)
75 {
76         p->io = _io;
77         avr_register_io(avr, &p->io);
78
79         printf("%s UART%c UDR=%02x\n", __FUNCTION__, p->name, p->r_udr);
80
81         avr_register_io_write(avr, p->r_udr, avr_uart_write, p);
82         avr_register_io_read(avr, p->r_udr, avr_uart_read, p);
83
84 }
85