demonstration of using serial port as console/terminal
Demonstration of using serial port with a dumb terminal. Such as teraterm. This example uses serial port at 57600bps.
purpose
provide quick/easy user interface.
features
- backspace key stops at start of line
- <enter> on empty line repeats last command
- Ctrl-C can be used to abort something
teraterm console
reset > ? . print status led toggle LED da<%d> get/set my_data > . LED1:0 my_data:0 > led > . LED1:1 my_data:0 > da data:0 > da1337 data:1337 > . LED1:1 my_data:1337 > led > > > >
main.cpp
- Committer:
- dudmuck
- Date:
- 2014-11-06
- Revision:
- 0:9a142eb22e83
File content as of revision 0:9a142eb22e83:
#include "mbed.h"
Serial pc(USBTX, USBRX);
char pcbuf[64];
DigitalOut myled(LED1);
uint16_t my_data;
void service_something()
{
/* poll something while waiting for keyboard */
}
int get_kbd_str(char* buf, int size)
{
char c;
int i;
static int prev_len;
for (i = 0;;) {
if (pc.readable()) {
c = pc.getc();
if (c == 8) { // backspace
if (i > 0) {
pc.putc(8);
pc.putc(' ');
pc.putc(8);
i--;
}
} else if (c == '\r') {
if (i == 0) {
return prev_len; // repeat previous
} else {
buf[i] = 0; // null terminate
prev_len = i;
return i;
}
} else if (c == 3) {
// ctrl-C abort
return -1;
} else if (i < size) {
buf[i++] = c;
pc.putc(c);
}
} else {
service_something();
}
} // ...for()
}
void
print_status()
{
printf("LED1:%d\r\n", myled.read());
printf("my_data:%d\n", my_data);
}
void console()
{
int len, n;
len = get_kbd_str(pcbuf, sizeof(pcbuf));
if (len < 0) {
printf("abort\r\n");
return;
}
printf("\r\n");
if (len == 1) {
/* single character handling */
switch (pcbuf[0]) {
case '?':
printf(". print status\r\n");
printf("led toggle LED\r\n");
printf("da<%%d> get/set my_data\r\n");
break;
case '.':
print_status();
break;
} // ...switch (pcbuf[0])
} else if (pcbuf[0] == 'l' && pcbuf[1] == 'e' && pcbuf[2] == 'd') {
if (myled.read()) // invert LED state
myled = 0;
else
myled = 1;
} else if (pcbuf[0] == 'd' && pcbuf[1] == 'a') {
if (pcbuf[2] >= '0' && pcbuf[2] <= '9') {
sscanf(pcbuf+2, "%d", &n);
my_data = n; // set user data
}
printf("data:%d\r\n", my_data); // show current value;
}
printf("> ");
fflush(stdout);
}
int main()
{
pc.baud(57600);
printf("\r\nreset\r\n");
printf("> ");
fflush(stdout);
while (1) {
console();
}
}