下面的代码正在打开第二个串行端口,我正在尝试对其进行读写。现在我正在使用第一个端口(Tera Term Console)上的控制台功能来查看那里的日志(printf 或 dmesg)。
但我无法从端口读取。控制台挂起。
int fd; /* File descriptor for the port */
#define BUFF_SIZE 1024
struct termios options;
char to_write[1024];
char to_read[1024];
int bytes_written;
int init_uart()
{
tcgetattr(fd, &options);
/* Set Baud Rate */
cfsetispeed( &options, B115200 );
cfsetospeed( &options, B115200 );
// Set the Charactor size
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= CS8; /* Select 8 data bits */
// Set parity - No Parity (8N1)
options.c_cflag &= ~PARENB;/*no parity bit*/
options.c_cflag &= ~CSTOPB;/* One bit stop bit*/
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;/* 8 Bits Character length*/
// Disable Hardware flowcontrol
options.c_cflag &= ~CRTSCTS;
// Enable Raw Input
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// Disable Software Flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY);
// Chose raw (not processed) output
options.c_oflag &= ~OPOST;
if ( tcsetattr( fd, TCSANOW, &options ) == -1 ){
printf ("Error with tcsetattr = %s\n", strerror ( errno ) );
return -1;
}
return 0;
}
int write_uart()
{
int i=0;
while (i < BUFF_SIZE-2){
to_write[i]='a';
i++;
}
to_write[i]='\n';
to_write[i+1]='\r';
// Write to the port
bytes_written = write(fd, to_write, BUFF_SIZE);
if(bytes_written < BUFF_SIZE){
fputs("write() of 1024 bytes failed!\n", stderr);
return -1;
}
return 0;
}
int
read_port(void)
{
int n = read(fd, to_read, sizeof(BUFF_SIZE));
if (n < 1024){
fputs("read failed!\n", stderr);
return -1;
}
return 0;
}
int main()
{
int i=0;
fd = open("/dev/ttyS1",O_RDWR | O_NOCTTY);
if(fd == -1)
perror("open_port: Unable to open /dev/ttyS1\n");
else
printf("ttyS0 Opened successfully\n");
if(init_uart())
perror("open_port: Unable to initialize /dev/ttyS0 Port\n");
else
printf("Port Initialization is done successfuly\n");
if(write_uart())
perror("write_port: Unable to write to /dev/ttyS0 Port\n");
else
printf("Write to the port happened successfully\n");
if(read_port())
perror("read_port: Unable to read from /dev/ttyS0 Port\n");
else
printf("Read to the port happened successfully\n");
close(fd);
return 0;
}