LInux下的串口通信
来源: 互联网 发布时间:2017-05-23
本文导语: 我在Linux下写了下面这样一个串口通信的程序: #include #include #include #include /* File control definitions */ #include #include /* POSIX terminal control definitions */ int main(void) { int fd; /* File descriptor for the port */ ...
我在Linux下写了下面这样一个串口通信的程序:
#include
#include
#include
#include /* File control definitions */
#include
#include /* POSIX terminal control definitions */
int main(void)
{
int fd; /* File descriptor for the port */
char buf[100];
fd = open("/dev/ttyS0", O_RDWR);
if (fd == -1)
{
fputs("open_port: Unable to open /dev/ttyS0 -n", stderr);
return -1;
}
struct termios oldoptions;
struct termios options;
memset(&options, 0, sizeof(options));
if(tcgetattr(fd, &oldoptions) != 0)
{
printf("getting options failed!n");
return -1;
}
tcflush(fd, TCIOFLUSH);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
if(tcsetattr(fd, TCSANOW, &options) != 0)
{
printf("setting options failed!n");
return -1;
}
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
if(tcsetattr(fd, TCSANOW, &options) != 0)
{
printf("setting options failed!n");
return -1;
}
int n, i;
char tmp[] = "serial port test...n";
for(i = 0; i