一、设备树下开启串口
路径:kernel\arch\arm\boot\dts下的对应dts文件 例如:
&uart4{
pinctrl-names = "default";
pinctrl-0 = <&uart4m1_xfer>;
status = "okay";
};
二、查看嵌入式设备是否成功挂载串口
/dev/ 路径下有:ttyS*
三、交叉编译 测试程序 uart_comm.c
执行 arm-linux-gnueabihf-gcc uart_comm.c -o uart_comm
四、拷贝uart_comm到嵌入式设备,然后执行 ./uart_comm
五、嵌入式设备通过USB转串口接到电脑,打开串口调试工具测试
直接上代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
int set_opt(int, int, int, char, int);
void main()
{
int fd, nByte, flag = 1;
char *uart4 = "/dev/ttyS4";
char buffer[512];
char *uart_out = "Please input,waiting....\r\n";
char *uart_demo = "Linux uart demo\r\n";
int i;
memset(buffer, 0, sizeof(buffer));
if ((fd = open(uart4, O_RDWR | O_NONBLOCK)) < 0)
printf("open %s is failed", uart4);
else
{
set_opt(fd, 115200, 8, 'N', 1);
write(fd, uart_demo, strlen(uart_demo));
write(fd, uart_out, strlen(uart_out));
while (1)
{
write(fd, uart_demo, strlen(uart_demo));
write(fd, uart_out, strlen(uart_out));
memset(buffer, 0, sizeof(buffer));
while ((nByte = read(fd, buffer, 512)) > 0)
{
buffer[nByte + 1] = '\0';
printf("%s\r\n", buffer);
write(fd, buffer, strlen(buffer));
memset(buffer, 0, strlen(buffer));
nByte = 0;
}
sleep(1);
printf("send date.\r\n");
}
}
}
int set_opt(int fd, int nSpeed, int nBits, char nEvent, int nStop)
{
struct termios newtio, oldtio;
if (tcgetattr(fd, &oldtio) != 0)
{
perror("SetupSerial 1");
return -1;
}
bzero(&newtio, sizeof(newtio));
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
switch (nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch (nEvent)
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= ~PARENB;
break;
}
switch (nSpeed)
{
case 2400:
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case 4800:
cfsetispeed(&newtio, B4800);
cfsetospeed(&newtio, B4800);
break;
case 9600:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case 115200:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
case 460800:
cfsetispeed(&newtio, B460800);
cfsetospeed(&newtio, B460800);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}
if (nStop == 1)
newtio.c_cflag &= ~CSTOPB;
else if (nStop == 2)
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 100;
newtio.c_cc[VMIN] = 0;
tcflush(fd, TCIFLUSH);
if ((tcsetattr(fd, TCSANOW, &newtio)) != 0)
{
perror("com set error");
return -1;
}
return 0;
}
|