Home > OS >  There is something wrong with the Linux serial port to read
There is something wrong with the Linux serial port to read

Time:10-04

On the H3 development board to run Linux, want to use he read a serial port information, such as serial port tool sends abcde
But read out the contents of the first read the first loss, a second read out entirely, the third time without a, 4 times and read out, all the time cycle,
Please tell me what's the problem?

The HTML code is as follows:
 # include & lt; Errno. H> 
# include & lt; fcntl.h>
# include & lt; stdio.h>
# include & lt; stdlib.h>
# include & lt; string.h>
# include & lt; Termios. H>
# include & lt; unistd.h>
# include & lt; Iostream>

using namespace std;

Int set_interface_attribs (int fd, int speed)
{
Struct termios tty.

If (tcgetattr (fd, & amp; Tty) & lt; 0 {
Printf (" the Error from tcgetattr: % s \ n ", the strerror (errno));
return -1;
}

Cfsetospeed (& amp; Tty (speed_t) speed);
Cfsetispeed (& amp; Tty (speed_t) speed);

Tty. C_cflag |=(CLOCAL | CREAD);/* ignore modem controls */
Tty. C_cflag & amp;=~ CSIZE;
Tty. C_cflag |=CS8 gives;/* 8-bit characters */
Tty. C_cflag & amp;=~ PARENB;/* no parity bit */
Tty. C_cflag & amp;=~ CSTOPB;/* only need 1 stop bit */
Tty. C_cflag & amp;=~ CRTSCTS;/* no hardware flowcontrol */

/* setup for non - canonical mode */
Tty. C_iflag & amp;=~ (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
Tty. C_lflag & amp;=~ (ECHO | ECHONL | ICANON | ISIG | IEXTEN);
Tty. C_oflag & amp;=~ OPOST;

/* the fetch bytes as they become available */
Tty. C_cc [VMIN]=1;
Tty. C_cc [VTIME]=1;

If (tcsetattr (fd, TCSANOW, & amp; Tty)!=0) {
Printf (" the Error from tcsetattr: % s \ n ", the strerror (errno));
return -1;
}
return 0;
}

Void set_mincount (int fd, int McOunt)
{
Struct termios tty.

If (tcgetattr (fd, & amp; Tty) & lt; 0 {
Printf (" Error tcgetattr: % s \ n ", the strerror (errno));
return;
}

Tty. C_cc [VMIN]=McOunt? 1:0;
Tty. C_cc [VTIME]=5;/* half second timer */

If (tcsetattr (fd, TCSANOW, & amp; Tty) & lt; 0)
Printf (" Error tcsetattr: % s \ n ", the strerror (errno));
}


Int main ()
{
Char * portname="/dev/ttyS0";
Int fd.
Int wlen;

Fd=open (portname, O_RDWR | O_NOCTTY | O_SYNC);
If (fd & lt; 0 {
Printf (" Error opening % s: % s \ n ", portname, strerror (errno));
return -1;
}
/* baudrate 9600, 8 bits, no parity, 1 stop bit */
//set_mincount (fd, 0);/* set to pure timed read */
Set_interface_attribs (fd, B115200);
Char buf [64].
Int rdlen=0;
/* simple noncanonical input */
Do {

Memset (buf, 0, sizeof (buf));
Rdlen=read (fd, buf, sizeof (buf));
If (rdlen & gt; 0 {
cout<" Rdlen: "& lt; } else if (rdlen & lt; 0 {
Printf (" the Error from the read: % d: % s \ n ", rdlen, strerror (errno));
}
Sleep (0);
/* reeat read to get the full message */
} the while (1);
}
  • Related