basic heap implementation
[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
22 #include <drivers/uart.h>
23 #include <drivers/st7735s.h>
24
25 #define SERIAL 1
26 #define TFT 0
27 #define BUFSIZE 256
28
29 static char stdbuf[BUFSIZE];
30
31 /* Abstraction layer for I/O communication */
32
33 char getchar(void) {
34         char c;
35         if (SERIAL) {
36                  while ((c = uart_getc()) == 0);
37                 /* do nothing */
38         }
39         return c;
40 }
41
42 void cputchar(char c) {
43
44         if (SERIAL) {
45                 uart_putc(c);
46         }
47         if (TFT) {
48                 tft_putc(0xFFFF, 0x0000, c);
49         }
50
51 }
52
53 void putc(void *p, char c) {
54
55         cputchar(c);
56
57 }
58
59 void cputs(unsigned char *str) {
60      
61      int i;
62      for (i = 0; i < strlen(str); i++)     {
63          cputchar(str[i]);
64     }
65
66 }
67
68 char * readline(char *prompt)
69 {
70         int i, c, echoing;
71
72         if (prompt != NULL)
73                 cputs(prompt); 
74
75         i = 0;
76         echoing = 1;
77         while (1) {
78                 c = getchar();
79                 if (c < 0) {
80                         cputs("read error");
81                         return NULL;
82                 } else if ((c == '\b' || c == '\x7f') && i > 0) {
83                         if (echoing)
84                                 cputchar('\b');
85                         i--;
86                 } else if (c >= ' ' && i < BUFSIZE-1) {
87                         if (echoing)
88                                 cputchar(c);
89                         stdbuf[i++] = c;
90                 } else if (c == '\n' || c == '\r') {
91                         if (echoing)
92                                 cputchar('\n');
93                         stdbuf[i] = 0;
94                         return stdbuf;
95                 }
96         }
97 }