basic implemtation general purpose clock and tinyprintf
[cortex-from-scratch] / lib / stdio.c
1 #include <stdbool.h>
2 #include <stddef.h>
3 #include <stdint.h>
4
5 #include <lib/stdio.h>
6 #include <lib/string.h>
7 #include <drivers/uart.h>
8
9 #define SERIAL 1
10 #define TFT 0
11 #define BUFSIZE 256
12
13 static char stdbuf[BUFSIZE];
14
15 /* Abstraction layer for I/O communication */
16
17 char getchar(void) {
18         char c;
19         if (SERIAL) {
20                  while ((c = uart_getc()) == 0);
21                 /* do nothing */
22         }
23         return c;
24 }
25
26 void cputchar(char c) {
27
28         if (SERIAL) {
29                 uart_putc(c);
30         }
31
32 }
33
34 void putc(void *p, char c) {
35
36         cputchar(c);
37
38 }
39
40 void cputs(unsigned char *str) {
41      
42      int i;
43      for (i = 0; i < strlen(str); i++)     {
44          cputchar(str[i]);
45     }
46
47 }
48
49 char * readline(char *prompt)
50 {
51         int i, c, echoing;
52
53         if (prompt != NULL)
54                 cputs(prompt); 
55
56         i = 0;
57         echoing = 1;
58         while (1) {
59                 c = getchar();
60                 if (c < 0) {
61                         cputs("read error");
62                         return NULL;
63                 } else if ((c == '\b' || c == '\x7f') && i > 0) {
64                         if (echoing)
65                                 cputchar('\b');
66                         i--;
67                 } else if (c >= ' ' && i < BUFSIZE-1) {
68                         if (echoing)
69                                 cputchar(c);
70                         stdbuf[i++] = c;
71                 } else if (c == '\n' || c == '\r') {
72                         if (echoing)
73                                 cputchar('\n');
74                         stdbuf[i] = 0;
75                         return stdbuf;
76                 }
77         }
78 }