前言 前面一篇我们实现了串口驱动,提供了串口读写的接口,为了方便调试,我们需要实现标准输入输出。我们可以使用MDK的MicroLIB实现,也可以直接使用源码,比如xprintf。 使用MicroLIB工程配置中勾选Use MicroLIB
Help->uVision HELP搜索stdio可以找到标准输入输出的底层接口
我们实现接口fgetc和fputc即可。 添加target.c
#include
#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中测试
int a;
int b;
printf("Hello Worldrn");
while(1)
{
printf("please input a and b:");
scanf("%d %d",&a,&b);
printf("%d+%d=%drn",a,b,a+b);
//int len=0;
//if((len = uart_read(buffer, sizeof(buffer))) >0)
//{
// uart_write(buffer, len);
//}
}
使用xprintfhttp://elm-chan.org/fsw/strf/xprintf.html 下载xprintf.c/h添加到工程中 Main.c中实现收发接口
#include "xprintf.h"
{
uint8_t c=ch;
uart_write(&c,1);
}
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 ==> rn 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("%dn", 1234); /* "1234" */
xprintf("%6d,%3d%%n", -200, 5); /* " -200, 5%" */
xprintf("%-6un", 100); /* "100 " */
xprintf("%ldn", 12345678); /* "12345678" */
xprintf("%llun", 0x100000000); /* "4294967296" */
xprintf("%lldn", -1LL); /* "-1" */
xprintf("%04xn", 0xA3); /* "00a3" */
xprintf("%08lXn", 0x123ABC); /* "00123ABC" */
xprintf("%016bn", 0x550F); /* "0101010100001111" */
xprintf("%*dn", 6, 100); /* " 100" */
xprintf("%sn", "abcdefg"); /* "abcdefg" */
xprintf("%5sn", "abc"); /* " abc" */
xprintf("%-5sn", "abc"); /* "abc " */
xprintf("%.5sn", "abcdefg"); /* "abcde" */
xprintf("%-5.2sn", "abcdefg"); /* "ab " */
xprintf("%cn", 'a'); /* "a" */
xprintf("%12fn", 10.0); /* " 10.000000" */
xprintf("%.4En", 123.45678); /* "1.2346E+02" */
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=%dn",a,b,a+b);
}
总结本文介绍了两种方式实现标注你输入输出,上面scanf输入好像还有点问题,后面再调试下。 推荐使用xprintf有源码,且代码小,比较灵活。
|