嵌入式处理器通过UART实现scanf和printf

#include <stdint.h>
#include <stdarg.h>

extern int vsscanf(const char *, const char *, va_list);
extern int vsprintf(const char *, const char *, va_list);

int uart_scanf(const char *fmt, ...)
{
    int i = 0;
    unsigned char ch;
    char buf[80];
    va_list args;

    while(1) {
        ch = uart_getchar();
        uart_putchar(ch);
        if(ch == '\n' || ch == '\r') {
            buf[i] = '\0';
            break;
        } else {
            buf[i++] = ch;
        }
    }

    va_start(args, fmt);
    i = vsscanf(buf, fmt, args);
    va_end(args);
    uart_putchar('\r');
    uart_putchar('\n');
    return i;
}

int uart_printf(const char *fmt, ...)
{
    int i = 0;
    unsigned int n = 0;
    char buf[80];
    va_list args;

    va_start(args, fmt);
    n = vsprintf(buf, fmt, args);
    va_end(args);

    for(i = 0; i < n; ++i) {
        uart_putchar(buf[i]);
    }
    return n;
}

int main(void)
{
    char str[10];
    int a, b, c;
    int n;
    while((n = uart_scanf("%s%d%d%d", str, &a, &b, &c)) != -1) {
        uart_printf("%d Arguments. str = %s, a = %d, b = %d, c = %d\r\n", n, str, a, b, c);
    }
    return 0;
}

 

posted @ 2019-07-29 00:05  BH5HSV  阅读(644)  评论(0编辑  收藏  举报