Linux的串口表现为设备文件。Linux的串口设备文件命名一般为/dev/ttySn(n=0、1、2„„),若串口是USB扩展的,则串口设备文件命名多为/dev/ttyUSBn(n=0、1、2„„)。当然这种命名规则不是绝对的,不同的硬件平台对串口设备文件的命名可能有所区别。
注意:我使用的是虚拟串口;通过 dmesg | grep ttyS 知道我创建的虚拟串口在UBUNTU下是“/dev/ttyS2”
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <asm/termios.h>
#define DEV_NAME "/dev/ttyS2"
int main (int argc, char *argv[])
{
int fd;
int len, i,ret;
char buf[30] = "hello world!
";
fd = open(DEV_NAME, O_RDWR | O_NOCTTY);
if(fd < 0) {
perror(DEV_NAME);
return -1;
}
len = write(fd, buf, sizeof(buf)); /* 向串口写入字符串 */
if (len < 0) {
printf("write data error
");
}
len = read(fd, buf, sizeof(buf)); /* 在串口读入字符串 */
if (len < 0) {
printf("read error
");
return -1;
}
printf("%d : %s
",len, buf); /* 打印从串口读出的字符串 */
return(0);
}
book@ubuntu:/home/linux_c/uart$ sudo ./test_uart_1
注意:若不加sudo,就会打开失败,并打印出"/dev/ttyS2: Permission denied"
运行结果:
先在串口助手上收到 “hello world” ,然后从串口助手发送 “uart : windows” ;
ubuntu收到的信息如下:
book@ubuntu:/home/linux_c/uart$ sudo ./test_uart_1
14 : uart : windows