wayne roberts
/
basic_serial_console
demonstration of using serial port as console/terminal
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 Serial pc(USBTX, USBRX); 00004 char pcbuf[64]; 00005 00006 DigitalOut myled(LED1); 00007 00008 uint16_t my_data; 00009 00010 void service_something() 00011 { 00012 /* poll something while waiting for keyboard */ 00013 } 00014 00015 int get_kbd_str(char* buf, int size) 00016 { 00017 char c; 00018 int i; 00019 static int prev_len; 00020 00021 for (i = 0;;) { 00022 if (pc.readable()) { 00023 c = pc.getc(); 00024 if (c == 8) { // backspace 00025 if (i > 0) { 00026 pc.putc(8); 00027 pc.putc(' '); 00028 pc.putc(8); 00029 i--; 00030 } 00031 } else if (c == '\r') { 00032 if (i == 0) { 00033 return prev_len; // repeat previous 00034 } else { 00035 buf[i] = 0; // null terminate 00036 prev_len = i; 00037 return i; 00038 } 00039 } else if (c == 3) { 00040 // ctrl-C abort 00041 return -1; 00042 } else if (i < size) { 00043 buf[i++] = c; 00044 pc.putc(c); 00045 } 00046 } else { 00047 service_something(); 00048 } 00049 } // ...for() 00050 } 00051 00052 void 00053 print_status() 00054 { 00055 printf("LED1:%d\r\n", myled.read()); 00056 printf("my_data:%d\n", my_data); 00057 } 00058 00059 void console() 00060 { 00061 int len, n; 00062 00063 len = get_kbd_str(pcbuf, sizeof(pcbuf)); 00064 if (len < 0) { 00065 printf("abort\r\n"); 00066 return; 00067 } 00068 00069 printf("\r\n"); 00070 if (len == 1) { 00071 /* single character handling */ 00072 switch (pcbuf[0]) { 00073 case '?': 00074 printf(". print status\r\n"); 00075 printf("led toggle LED\r\n"); 00076 printf("da<%%d> get/set my_data\r\n"); 00077 break; 00078 case '.': 00079 print_status(); 00080 break; 00081 } // ...switch (pcbuf[0]) 00082 } else if (pcbuf[0] == 'l' && pcbuf[1] == 'e' && pcbuf[2] == 'd') { 00083 if (myled.read()) // invert LED state 00084 myled = 0; 00085 else 00086 myled = 1; 00087 } else if (pcbuf[0] == 'd' && pcbuf[1] == 'a') { 00088 if (pcbuf[2] >= '0' && pcbuf[2] <= '9') { 00089 sscanf(pcbuf+2, "%d", &n); 00090 my_data = n; // set user data 00091 } 00092 printf("data:%d\r\n", my_data); // show current value; 00093 } 00094 00095 printf("> "); 00096 fflush(stdout); 00097 } 00098 00099 int main() 00100 { 00101 pc.baud(57600); 00102 printf("\r\nreset\r\n"); 00103 00104 printf("> "); 00105 fflush(stdout); 00106 00107 while (1) { 00108 console(); 00109 } 00110 }
Generated on Wed Jul 13 2022 19:25:56 by 1.7.2