ARM40-A5D27应用程序——串口应用程序示例

ARM40-A5D27应用程序——串口应用程序示例

 本文为串口应用程序示例,测试板为ARM40-A5D27.

一、在shell中测试

 将串口 ttyS5 的TX、RX脚短接,然后:

cat /dev/ttyS5 &
echo 123abc > /dev/ttyS5		//可以看到ttyS5返回123abc

二、 C代码

 文件名为 test_uart.c,代码见本文附录(1)。

三、交叉编译

arm-linux-gnueabihf-gcc -o test_uart test_uart.c 

四、执行程序

 将ARM40-A5D27的ttyS5连接到PC(USB 串口),设置PC端USB串口波特率为115200.
 将交叉编译得到的 test_uart 文件拷贝到ARM40-A5D27板中,执行程序:

./test_uart

 在PC端USB串口可以看到“Hello World!”的打印。
 在PC端USB串口输入123abc,在ARM40-A5D27的ttyS5可以收到“123abc”。

参考文章:

https://microchipdeveloper.com/32mpu:apps-uart
http://kirste.userpage.fu-berlin.de/chemnet/use/info/libc/libc_12.html#SEC237
《UNIX环境高级编程》第18章
https://www.cmrr.umn.edu/~strupp/serial.html#4_2
http://blog.chinaunix.net/uid-2630593-id-2138571.html
http://erwinchang.github.io/2016/10/20/uart-c/
https://www.ibm.com/developerworks/cn/linux/l-serials/
http://digilander.libero.it/robang/rubrica/serial.htm

荟聚计划:共商 共建 共享 Grant

附:

(1)test_uart.c 的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

#define DEV_TTY "/dev/ttyS5"
#define BUF_SIZE 256

int main(int argc, char *argv[])
{
    int fd;
    int ret;
    char tx_buf[] = "Hello World!\n\r";
    char rx_buf[BUF_SIZE] = "";
    struct termios options;

    /* open uart */
    fd = open(DEV_TTY, O_RDWR|O_NOCTTY);
    if (fd < 0) {
        printf("ERROR open %s ret=%d\n\r", DEV_TTY, fd);
        return -1;
    }
    /* configure uart */
    tcgetattr(fd, &options);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cc[VTIME] = 10; // read timeout 10*100ms
    options.c_cc[VMIN]  = 0;
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;
    options.c_iflag &= ~(ICRNL | IXON);
    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);
    options.c_cflag |= (CLOCAL | CREAD);
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &options);

    while (1) {
        /* read uart */
        while ((ret = read(fd, rx_buf, BUF_SIZE-1)) > 0) {
            puts(rx_buf);
            memset(rx_buf, 0, ret);
        }
        /* write uart */
        ret = write(fd, tx_buf, sizeof(tx_buf));
        if (ret != sizeof(tx_buf))
            printf("ERROR write ret=%d\n", ret);
    }

    /* close uart */
    close(fd);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值