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;
}