#include <termios.h>
struct termios
{
tcflag_t c_iflag; /* input modes */
tcflag_t c_oflag; /* output modes */
tcflag_t c_cflag; /* control modes */
tcflag_t c_lflag; /* local modes */
cc_t c_cc[NCCS]; /* special characters */
}
int tcgetattr(int fd, struct termios *termios_p); //获取与终端相关的参数
inttcsetattr(int fd, int optional_actions, struct termios *termios_p); //设置终端参数
int tcsendbreak(int fd, int duration);
int tcdrain(int fd); //等待直到所有写入 fd 引用的对象的输出都被传输
int tcflush(int fd, int queue_selector); //刷清(扔掉)输入缓存
int tcflow(int fd, int action); //挂起传输或接受
int cfmakeraw(struct termios *termios_p);// 制作新的终端控制属性
speed_t cfgetispeed(struct termios *termios_p); //得到输入速度
speed_t cfgetospeed(struct termios *termios_p); //得到输出速度
int cfsetispeed(struct termios *termios_p, speed_t speed); //设置输入速度
int cfsetospeed(struct termios *termios_p, speed_t speed) //设置输出速度
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
int main()
{
char sbuf[] = {"Hello, this is a serial port test!
"};
struct termios option;
///dev/pts/?是两个虚拟串口之一
int fd = open("/dev/pts/25", O_RDWR | O_NOCTTY | O_NONBLOCK);
if(fd == -1)
{
perror("Open serial port error!
");
return -1;
}
printf("Open serial port success!
");
tcgetattr(fd, &option);
cfmakeraw(&option);
cfsetispeed(&option, B9600);
cfsetospeed(&option, B9600);
tcsetattr(fd, TCSANOW, &option);
int length = sizeof(sbuf);
int ret = write(fd, sbuf, length);
if(ret == -1)
{
perror("Write data error!
");
return -1;
}
printf("The number of char sent is %d
", ret);
ret = close(fd);
if(ret == -1)
perror("Close the device failure!
");
return 0;
}
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <math.h>
#define MAX_BUFFER_SIZE 512
int main()
{
char hd[MAX_BUFFER_SIZE], *rbuf;
int ret;
struct termios opt;
///dev/pts/?是两个虚拟串口之一
int fd = open("/dev/pts/28", O_RDWR|O_NOCTTY|O_NDELAY);
if(fd == -1)
{
perror("Open serial port error!
");
return -1;
}
printf("Open serial port success!
");
tcgetattr(fd, &opt);
cfmakeraw(&opt);
cfsetispeed(&opt, B9600);
cfsetospeed(&opt, B9600);
tcsetattr(fd, TCSANOW, &opt);
rbuf = hd;
printf("Ready for receiving data...
");
while(1)
{
while((ret = read(fd, rbuf, 1)) > 0)
printf("%c", *rbuf);
}
printf("
");
ret = close(fd);
if(ret == -1)
perror("Close the device failure!
");
return 0;
}
虚拟串口:http://blog.csdn.net/zhangxuechao_/article/details/70670405