我在c ++中有一个读入函数的小问题。我正在尝试读取UART的RxD端口上的数据。
运行此代码时,我得到结果(读取< 0)因此它在读取时显示错误消息错误。应该怎么做才能读入并显示读取的数据。我确信RxD端口上有可用的数据我已经用示波器检查了它。
#include <iostream>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#define BAUDRATE B19200
#define PORT "/dev/ttyO4"
#define _POSIX_SOURCE 1
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
void signal_handler_IO(int status);
int wait_flag = TRUE;
main ()
{
int fd=0, res=0, result=0;
char SYNC [] = {0x55};
char PID [] = {0x6A};
struct termios oldtio, newtio;
struct sigaction saio;
char buff[255];
fd = open(PORT, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd<0) {perror(PORT); exit(-1);}
saio.sa_handler=signal_handler_IO;
saio.sa_flags=0;
saio.sa_restorer = NULL;
sigaction(SIGIO, &saio,NULL);
fcntl(fd, F_SETFL, FASYNC);
tcgetattr(fd, &oldtio);
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
//newtio.c_lflag = 0;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
ioctl(fd, TIOCSBRK);
usleep(1300);
ioctl(fd,TIOCCBRK);
usleep(200);
write(fd, SYNC, sizeof(SYNC));
write(fd,PID, sizeof(PID));
res = read(fd, buff,255);
if (res < 0)
{
printf("read error\n");
}
else if (res ==0)
{
printf("read = 0 \n");
}
else
{
sprintf(result, "%x",res);
buff[res]=0;
printf(": %s :%d :%d\n", buff,result,res);
}
close (fd);
}
void signal_handler_IO(int status)
{
printf("received the signal\n");
wait_flag=FALSE;
}