日期:2014-05-16 浏览次数:20837 次
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h> /* File control definitions */
#include <errno.h>
#include <termios.h> /* 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 < 5; i++)
{
/*
printf("write to the serial port...\n");
n = write(fd, tmp, sizeof(tmp));
if (n < 0)
{
fputs("write() failed!\n", stderr);
return -1;
}
*/
printf("read the serial port...\n");
n = read(fd, buf, sizeof(buf));
if (n < 0)
{
fputs("read() failed!\n", stderr);
return -1;
}
printf("receive %d characters\n", n);
buf[n] = '\0';
printf("%s\n", buf);
}
if(tcsetattr(fd, TCSANOW, &oldoptions) != 0)
{
printf("setting options&nbs