6b0f2a24e2059b53b216463dad511730e57ad147
[cortex-from-scratch] / lib / stdio.c
1 /* (CC-BY-NC-SA) ROBIN KRENS - ROBIN @ ROBINKRENS.NL
2  * 
3  * $LOG$
4  * 2019/7/23 - ROBIN KRENS      
5  * Initial version 
6  * 
7  * $DESCRIPTION$
8  * The 'classic' putc and getchar functions. Should not be used directly
9  * use the tinyprintf library instead
10  *
11  * Can be extended for multiple interfaces (serial, tft or oled screens)
12  *
13  */
14
15 #include <stdbool.h>
16 #include <stddef.h>
17 #include <stdint.h>
18
19 #include <lib/stdio.h>
20 #include <lib/string.h>
21 #include <drivers/uart.h>
22
23 #define SERIAL 1
24 #define TFT 0
25 #define BUFSIZE 256
26
27 static char stdbuf[BUFSIZE];
28
29 /* Abstraction layer for I/O communication */
30
31 char getchar(void) {
32         char c;
33         if (SERIAL) {
34                  while ((c = uart_getc()) == 0);
35                 /* do nothing */
36         }
37         return c;
38 }
39
40 void cputchar(char c) {
41
42         if (SERIAL) {
43                 uart_putc(c);
44         }
45
46 }
47
48 void putc(void *p, char c) {
49
50         cputchar(c);
51
52 }
53
54 void cputs(unsigned char *str) {
55      
56      int i;
57      for (i = 0; i < strlen(str); i++)     {
58          cputchar(str[i]);
59     }
60
61 }
62
63 char * readline(char *prompt)
64 {
65         int i, c, echoing;
66
67         if (prompt != NULL)
68                 cputs(prompt); 
69
70         i = 0;
71         echoing = 1;
72         while (1) {
73                 c = getchar();
74                 if (c < 0) {
75                         cputs("read error");
76                         return NULL;
77                 } else if ((c == '\b' || c == '\x7f') && i > 0) {
78                         if (echoing)
79                                 cputchar('\b');
80                         i--;
81                 } else if (c >= ' ' && i < BUFSIZE-1) {
82                         if (echoing)
83                                 cputchar(c);
84                         stdbuf[i++] = c;
85                 } else if (c == '\n' || c == '\r') {
86                         if (echoing)
87                                 cputchar('\n');
88                         stdbuf[i] = 0;
89                         return stdbuf;
90                 }
91         }
92 }