Reputation: 41
I have to use a rs232 serial communication in a C program with a petalinux OS. And I have problem to read data from my serial. As I am not familiar with linux OS I have searched on internet some example of C program to write and read data on a rs2323.
Here is how I setup my serial
int open_uart() {
uart1_fd = open("/dev/ttyUL2", O_RDWR | O_NOCTTY | O_NDELAY);
if (uart1_fd == -1) {
printf("--- no uart ---\n");
return 0;
} else {
printf("--- open uart ok ---\n");
}
struct termios tty;
tcgetattr(uart1_fd, &tty);
tty.c_cflag &= ~PARENB; // Disable parity
tty.c_cflag &= ~CSTOPB; // One stop bit
tty.c_cflag &= ~CSIZE; // Clear size bits
tty.c_cflag |= CS8; // 8 bits per byte
tty.c_cflag &= ~CRTSCTS; // No hardware flow control
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable software flow control
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP); // Disable special characters
tty.c_oflag &= ~OPOST; // No post-processing
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN); // Disable canonical mode
tty.c_cc[VTIME] = 10; // Wait up to 10 deciseconds for data
tty.c_cc[VMIN] = 0; // Don't wait for minimum number of characters
if (cfsetispeed(&tty, B38400) < 0 || cfsetospeed(&tty, B38400) < 0) {
printf("error\n");
}
if (tcsetattr(uart1_fd, TCSANOW, &tty) < 0) {
printf("error\n");
}
return 1;
}
There is no problem to write data but to read if I simply do this
rx_length = read(uart1_fd, (void*) rx_buffer, 32);
rx_length is 0 and nothing is read. To read my data I need to do this
int recvMsg(char* pMsg, int16_t lng) {
int nb = -1;
char rx = 0;
int m = 0;
memset(pMsg, 0, lng);
while (rx != 0xfa && m < lng && nb <= 10000) {
nb++;
if (read(uart1_fd, &rx, 1) > 0)
pMsg[m++] = rx;
}
printf("Réception de: ");
for (int i = 0; i < m; i++) {
printf("%02x ", (uint8_t) pMsg[i]);
}
printf("\r\n");
return m;
}
I suspect my initial configuration is not appropriate. What I expect is that the read function will return only when it has received all the incoming data
Upvotes: 2
Views: 50