本帖最后由 qinyunti 于 2022-12-15 22:21 编辑
proj.zip
(2.02 MB, 下载次数: 0)
前言
前面一篇我们实现了串口驱动,提供了串口读写的接口,为了方便调试,我们需要实现标准输入输出。我们可以使用MDK的MicroLIB实现,也可以直接使用源码,比如xprintf。
使用MicroLIB
工程配置中勾选Use MicroLIB
Help->uVision HELP搜索stdio可以找到标准输入输出的底层接口
我们实现接口fgetc和fputc即可。
添加target.c
#include <stdio.h>
#include "uart.h"
int fgetc(FILE *f)
{
/* Your implementation of fgetc(). */
int len=0;
uint8_t ch=0;
do
{
len = uart_read(&ch, 1);
}while(len == 0);
return ch;
}
int fputc(int c, FILE *stream)
{
/* Your implementation of fputc(). */
uint8_t ch=0;
if((uint8_t)ch == (uint8_t)'\n')
{
ch = '\r';
uart_write(&ch,1);
}
ch = (uint8_t)c;
uart_write(&ch,1);
return c;
}
main.c中测试
#include <stdio.h>
uart_init();
while(1)
{
int a;
int b;
printf("Hello World\r\n");
while(1)
{
printf("please input a and b:");
scanf("%d %d",&a,&b);
printf("%d+%d=%d\r\n",a,b,a+b);
}
}
使用xprintf
http://elm-chan.org/fsw/strf/xprintf.html
下载xprintf.c/h添加到工程中
main.c中实现收发接口
#include "xprintf.h"
int xprintf_out(int ch)
{
uint8_t c=ch;
uart_write(&c,1);
return ch;
}
int xprintf_in(void)
{
int len=0;
uint8_t ch=0;
do
{
len = uart_read(&ch, 1);
}while(len == 0);
return ch;
}
初始化设置接口
xdev_out(xprintf_out);
xdev_in(xprintf_in);
Xprintf.h中配置
#define XF_USE_OUTPUT 1 /* 1: Enable output functions */
#define XF_CRLF 1 /* 1: Convert \n ==> \r\n in the output char */
#define XF_USE_DUMP 1 /* 1: Enable put_dump function */
#define XF_USE_LLI 1 /* 1: Enable long long integer in size prefix ll */
#define XF_USE_FP 1 /* 1: Enable support for floating point in type e and f */
#define XF_DPC '.' /* Decimal separator for floating point */
#define XF_USE_INPUT 1 /* 1: Enable input functions */
#define XF_INPUT_ECHO 1 /* 1: Echo back input chars in xgets function */
测试
xprintf("%d\n", 1234); /* "1234" */
xprintf("%6d,%3d%%\n", -200, 5); /* " -200, 5%" */
xprintf("%-6u\n", 100); /* "100 " */
xprintf("%ld\n", 12345678); /* "12345678" */
xprintf("%llu\n", 0x100000000); /* "4294967296" <XF_USE_LLI> */
xprintf("%lld\n", -1LL); /* "-1" <XF_USE_LLI> */
xprintf("%04x\n", 0xA3); /* "00a3" */
xprintf("%08lX\n", 0x123ABC); /* "00123ABC" */
xprintf("%016b\n", 0x550F); /* "0101010100001111" */
xprintf("%*d\n", 6, 100); /* " 100" */
xprintf("%s\n", "abcdefg"); /* "abcdefg" */
xprintf("%5s\n", "abc"); /* " abc" */
xprintf("%-5s\n", "abc"); /* "abc " */
xprintf("%.5s\n", "abcdefg"); /* "abcde" */
xprintf("%-5.2s\n", "abcdefg"); /* "ab " */
xprintf("%c\n", 'a'); /* "a" */
xprintf("%12f\n", 10.0); /* " 10.000000" <XF_USE_FP> */
xprintf("%.4E\n", 123.45678); /* "1.2346E+02" <XF_USE_FP> */
char buffer[64];
long a;
long b;
char* p;
while(1)
{
xprintf("please input a int:\n");
xgets(buffer,sizeof(buffer));
p = buffer;
xatoi(&p,&a);
xprintf("please input a int:\n");
xgets(buffer,sizeof(buffer));
p = buffer;
xatoi(&p,&b);
xprintf("%d+%d=%d\n",a,b,a+b);
}
总结
本文介绍了两种方式实现标注你输入输出,上面scanf输入好像还有点问题,后面再调试下。
推荐使用xprintf有源码,且代码小,比较灵活。