I want to communicate with my PC using the RS232 port. I can open "/dev/ttyS0" and write data using write() function, But i can't read correct data from "dev/ttyS0" by using read(). read() function read the unnecessary data.Please tell me how to solve this problem?
My program code here :
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int n = 0, fd = 0, bytes = 0;
char buffer[10];
struct termios term;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
return;
}
else
{
fcntl(fd, F_SETFL, 0);
perror("Port");
}
tcgetattr(fd, &term);
cfsetispeed(&term, B115200);
cfsetospeed(&term, B115200);
term.c_cflag |= (CLOCAL | CREAD);
term.c_cflag &= ~PARENB;
term.c_cflag &= ~CSTOPB;
term.c_cflag &= ~CSIZE;
term.c_cflag |= CS8;
term.c_cflag &= ~CRTSCTS;
term.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
term.c_iflag &= ~(IXON | IXOFF | IXANY);
term.c_oflag &= ~OPOST;
term.c_cc[VMIN] = 0;
term.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &term);
printf("Enter the string...\n");
scanf("%s", buffer);
write(fd, buffer, sizeof(buffer));
perror("write");
// fcntl(fd, F_SETFL, FNDELAY);
sleep(1);
bytes = read(fd, buffer, sizeof(buffer));
perror("read");
buffer[bytes] = '\0';
printf("Bytes : %d\n", bytes);
printf("%s\n", buffer);
memset(buffer, '\0', 10);
}
fdisn't ready whentcgetattris called (so maybe it just returns-EAGAIN. The code doesn't check errors on anything, so I'd suggest usingstraceto see what system calls are made, and what their return values are. Also, use a known-good terminal emulator likeminicomto make sure things work properly.errno. That's a POSIX rule.