#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>//进程控制函数库
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>//包含结构体termios,中最重要的是c_iflag
#include <errno.h>
int main()
{
// open com ( com1=/dev/ttyS0 com2=/dev/ttyS1)
int fd ;
fd = open("/dev/ttyS0", O_RDWR) ; // open com1 in read and write mode
if ( fd == -1)
{
perror("Open Com port error\n") ;
exit(1) ;
}
// set com port attribute
struct termios old_term ;// backup the old attribute of com
struct termios new_term ;
tcgetattr(fd, &old_term) ;//取得当前串口的值,并将其保存在 old_term中 tcgetattr(fd, &new_term) ;
cfsetispeed(&new_term, B19200) ; //设置输入和输出波特率
cfsetospeed(&new_term, B19200) ;//这一句好像是为了有的位段不用设置
//控制模式
new_term.c_cflag &= ~CSIZE ;
int data_bit = 7 ;
if (data_bit == 7)
{
new_term.c_cflag |= CS7 ; // 7-bit data
}
else
{
new_term.c_cflag |= CS8 ; // 8-bit data
}
// set parity
int parity = "N" ; // N, E, O, S
switch(parity)
{
case 'n':
case 'N':
// no parity
new_term.c_cflag &= ~PARENB ;
new_term.c_iflag &= ~INPCK ;
break ;
case 'O':
case 'o':
// ji "O"
new_term.c_cflag |= (PARODD | PARENB) ;
new_term.c_iflag |= INPCK ;
break ;
case 'E':
case 'e':
// odd "E"
new_term.c_cflag |= PARENB ;
new_term.c_cflag &= ~PARODD ;
new_term.c_iflag |= INPCK ;
break ;
case 'S':
case 's':
// "S"
new_term.c_cflag &= ~PARENB ;
new_term.c_cflag &= CSTOPB ;
new_term.c_iflag |= INPCK ;
break ;
}// switch(parity)
// set stop bit
int stop_bit = 1 ; // 1, 2
switch(stop_bit)
{
case 1:
new_term.c_cflag &= ~CSTOPB ;
break ;
case 2:
new_term.c_cflag |= CSTOPB ;
break ;
}
tcsetattr(fd, TCSANOW, &new_term) ;//设置当前的串口的参数为 new_term
tcflush(fd, TCIOFLUSH) ;//清空所有队列在串口上的输入输出
// write data
char buffer[1024] ;
int times = 0 ;
while (times++ < 10 )
{
strcpy(buffer, "hello, world!") ;
int length = strlen(buffer) ;
int nWriteBytes ;
nWriteBytes = write(fd, buffer, length) ;
printf("write com data len=%d\n", nWriteBytes) ;
}
tcsetattr(fd, TCSANOW, &old_term) ;//恢复原有的默认的设置
close(fd) ;
}
|