我试图在linux中编写一个与serialport交互的C程序。该程序有2个线程,一个主要写入和一个监听线程。我的问题在于监听线程。我希望read函数在单个字节到达后立即读取原始数据。
无论我尝试使用termios结构,我只能读取数据,直到收到换行符(\ n或\ r)。我使用连接了Rx和Tx的USB-Serial棒进行测试。提前谢谢。
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <stdlib.h>
#include <pthread.h>
#define RESET_HIGH RESET_HIGH
#define RESET_LOW RESET_LOW
#define SLEEP_TPE usleep(5200) //min 5100usec = 5.1msec
#define FALSE 0
#define TRUE 1
#define BAUDRATE B115200
//function declaration
void *read_port(void);
//variable declaration
volatile int LISTENING=TRUE;
int fd;
unsigned char rx_buffer[255];
int main(int argc, char const *argv[]){
int error;
struct termios oldtty,newtty;
pthread_t txthread;
printf("-------->ZM5304 FLASHING PROGRAM<--------\n");
fd = open_port("/dev/ttyUSB0"); // "/dev/ttymxc3" "/dev/ttyUSB0"
//save current port settings
error = tcgetattr(fd, &oldtty);
if(error==-1){
close(fd);
perror("unable to read portsettings\n");
return(1);
}
//clear new struct
memset(&newtty, 0, sizeof(newtty));
newtty.c_cflag |= CS8 | CSTOPB; //8bit, 2 stopbits
newtty.c_cflag &= ~CRTSCTS; //disable hardware flowcontrol
//newtty.c_lflag |= ICANON; //cannonical
newtty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input
newtty.c_oflag &= ~OPOST;
newtty.c_cc[VMIN] = 1;
newtty.c_cc[VTIME] = 0; //read() blocking
//cfmakeraw(&newtty);
cfsetispeed(&newtty, BAUDRATE);
cfsetospeed(&newtty, BAUDRATE);
//apply portsettings
printf("Applying portsettings\n");
error = tcsetattr(fd, TCSANOW, &newtty);
if(error==-1){
close(fd);
printf("unable to adjust portsettings - %s\n", error);
return(1);
}
//SETUP LISTENING THREAD
error = pthread_create(&txthread, NULL, read_port, (void *)NULL);
if(error){
printf("Error - pthread_create() return code: %d\n", error);
return(2);
}
sleep(1);
write(fd, "A",1);
sleep(1);
write(fd, "B",1);
sleep(1);
write(fd, "C\n",2);
sleep(1);
write(fd, "Talking Serial\n",15);
sleep(1);
write(fd, "q\n",2);
sleep(1);
close(fd);
printf("-------->END OF PROGRAM<--------\n");
pthread_exit(NULL);
return 0;
}
int open_port(char *path){
int fd; // File descriptor for the port
printf("Opening serialport: %s\n", path);
fd = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1){ //Could not open the port.
fprintf(stderr, "Error - Unable to open %s - %s\n", path, strerror(errno));
exit(1);
}
return (fd);
}
void *read_port(){
printf("Reading Tx\n");
int len;
while(LISTENING){
len = read(fd,rx_buffer,255);
rx_buffer[len]=0; /* set end of string, so we can printf */
if(len>0){printf("%s", rx_buffer);}
if(rx_buffer[0]=='q'){LISTENING=FALSE;}
}
printf("Stop listening\n");
}