实验描述:串口程序接受与发送
注意事项:注意MIN,和VTIME的设置
应用程序:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc, char **argv)
{
int fd;
fd = open("/dev/ttySAC0", O_RDWR);
if( fd == -1){
perror("open error");
}
struct termios seria_read_write;
tcgetattr(fd,&seria_read_write);
tcflush(fd, TCIFLUSH);
cfsetispeed(&seria_read_write, B9600);
cfsetospeed(&seria_read_write, B9600);
seria_read_write.c_cflag |= CS8;
seria_read_write.c_cflag &= ~CSTOPB;
seria_read_write.c_iflag = ~(INPCK|BRKINT|ICRNL|ISTRIP|IXON);
seria_read_write.c_oflag &= ~OPOST;
seria_read_write.c_cc[VMIN] = 0;
seria_read_write.c_cc[VTIME] = 6;
if (tcsetattr(fd,TCSANOW,&seria_read_write) != 0)
{
perror("Reload SetupSerial!\n");
close(fd);
return -1;
}
char read_buffer[1024];
char write_buffer[1024];
int nread;
int flag = 0;
while(1){
int i;
int count=0;
int len = 0;
while( (nread=read(fd, read_buffer, sizeof(read_buffer))) > 0){
for(i = 0; i < nread ; i++){
write_buffer[count++] = read_buffer[i];
}
flag = 1;
}
if (flag > 0){
write_buffer[count] = '\0';
printf("rec buffer: %d, %d, %s\n", count, sizeof(write_buffer), write_buffer);
write_buffer[0] = 'x';
write(fd, write_buffer, count);
flag = 0;
}
}
close(fd);
return 0;
}