【杰发科技AC7802x测评】2. 使用printf和scanf重定向串口输入输出

前言

本实验用串口来实现printf输出以及scanf输入。和电脑环境的C语言不一样的是,单片机开发中,printf和scanf的实现是通过串口来完成的,而且不同的IDE的视线方式是不一样的,本文以MDK为例,讲解如何使用串口重定向scanf和printf。

测试环境:

- 系统:win10
- IDE:KEIL V5.34
- 单片机:AC7802X

1 硬件连接

要使用串口功能,首先是查看串口引脚的连接。

查看原理图可知,板载的Type-C连接到了UART1上,所以可以直接通过Type-C来实现串口通信,这点很棒,减少了接线。

 



下图是复用关系,但是不是重点,因为官方提供的例程中已经做好了复用关系的映射,我们只需使用即可。

 



2 代码实现

KEIL下实现printf和scanf的串口重定向,需要实现fputc和fgetc函数,用于输出和输入一个字符,实现如下:
 

/*

@hehung

2023-5-22

email: 1398660197@qq.com

wechat: hehung95

reproduced and please indicate the source @hehung

*/



#include <stdbool.h>

#include "ac780x_gpio.h"

#include "ac780x_uart.h"

#include "ac780x_uart_reg.h"

#include "app_uart.h"





// UART initialization

void UART_Cfg_Init(void)

{

    UART_ConfigType uart_config;



    GPIO_SetFunc(GPIOA, GPIO_PIN4, GPIO_FUN3);    /*! uart tx */

    GPIO_SetFunc(GPIOA, GPIO_PIN5, GPIO_FUN3);    /*! uart rx */



    uart_config.baudrate   = 115200;              /*!  baudrate 115200 */

    uart_config.dataBits   = UART_WORD_LEN_8BIT;  /*! data leng th8bit */

    uart_config.stopBits   = UART_STOP_1BIT;      /*! 停止位1bit */

    uart_config.fifoByteEn = DISABLE;   

    uart_config.sampleCnt  = UART_SMP_CNT0;       /*! 16倍采样 */

    uart_config.callBack   = NULL;                /*! 不设置回调函数 */



    UART_Init(UART1,&uart_config);

}



// fputs for printf or other print function in standard

int fputc(int ch, FILE *f)

{

    UART_SendData(UART1, ch);           /*! 发送数据 */

    while (!UART_TxIsEmpty(UART1)) {};       /*! 等待发送缓冲区为空 */ 



    return ch;

}



// fgets for scanf or other input function in standard

int fgetc(FILE *f) 

{

    (void)f;

    uint8_t ch;



    while(!UART_RxIsDataReady(UART1)) {};    /*! 等待串口1接受到数据 */

    ch = UART_ReceiveData(UART1);       /*! 读取数据 */



    return (int)ch;

}


主函数实现进行测试:

int main(void)

{

    InitDelay();

  

    UART_Cfg_Init();                          /*! 串口1初始化 */



    printf ("This is a printf and scanf TEST for ac7802x\r\n");

    int a;

    printf ("Please input a number with int type\r\n");

    scanf ("%d", &a);

    printf ("The number you input is: %d\r\n", a);



    while(1)

    {

    

    }

}




# 3 注意事项

## 3.1 勾选Use MicroLIB

需要使用KEIL下的printf和scanf功能,还需要勾选 `Use MicroLIB`,不然程序会卡死。

 



# 4 实验效果

如下为测试结果,可以看到,试验成功,后续就可以使用printf来输出一些调试信息,使用scanf来接受控制命令进行调试了。
 

---------------------
作者:hehung
链接:https://bbs.21ic.com/icview-3304954-1-1.html
来源:21ic.com
此文章已获得原创/原创奖标签,著作权归21ic所有,任何人未经允许禁止转载。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值