Below code is opening the second serial port and I am trying to read and write to it.Now I am using the console functionalities on the first port ( Tera Term Console ) to see the logs there (printf or dmesg ).
But I am not able to read from the port. The console hangs.
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;
}
tcgetattr(). (2) What device is this serial port connected to? If there is no device on the other end of the serial link, then what to you expect to read? (3) Are you sure you want to put the port in raw mode? Depending on the device that is connected (?), you could want/need canonical mode. If it's a text device (as thewrite()output indicates), then you probably should use canonical instead of raw mode.