Hello!
I am trying to read data from the UART port telem2
i.e /dev/ttyS2 in pixhawk cube, but read()
returns -1 and errno is 11. write()
is working properly as I am able to send data to uart and read it from my laptop which is connected to pixhawk using a FTDI cable to telem2. I
went through the uart tests in systemcmd tests for reference, but for some reasons cant get the read()
working properly. Any suggestions on where I might be going wrong?
Here is the code for reading data on pixhwak
int dp_uart_test_main(int argc, char *argv[]) {
/* input handling */
char *uart_name = "/dev/ttyS2";
if (argc > 1) {
uart_name = argv[1];
}
/* assuming NuttShell is on UART1 (/dev/ttyS0) */
int test_uart = open(uart_name, O_RDWR | O_NOCTTY); //
if (test_uart < 0) {
printf("ERROR opening UART %s, aborting..\n", uart_name);
return test_uart;
} else {
printf("Writing to UART %s\n", uart_name);
}
// sete the badrate to match in terminbal
struct termios uart2_config;
int termios_state = 0;
// int ret = 0;
if ((termios_state = tcgetattr(test_uart, &uart2_config)) < 0) {
printf("ERROR getting termios config for UART2: %d\n", termios_state);
// ret = termios_state;
}
if (cfsetispeed(&uart2_config, B57600) < 0 ||
cfsetospeed(&uart2_config, B57600) < 0) {
printf("ERROR setting termios config for UART2: %d\n", termios_state);
}
// uart2_config.c_cflag = CRTSCTS | CS8 | CLOCAL | CREAD;
if ((termios_state = tcsetattr(test_uart, TCSANOW, &uart2_config)) < 0) {
printf("ERROR setting termios config for UART2\n");
}
// char sample_test_uart[25]; // = {'S', 'A', 'M', 'P', 'L', 'E', ' ', '\n'};
// int l, n;
// l = 1;
// uint64_t start_time = 0;
// n = sprintf(sample_test_uart, "Hello from other side\n");
// char j;
// for (int i = 0; i < n; i++) {
// j = sample_test_uart[i];
// write(test_uart, &j, 1);
// }
fcntl(test_uart, F_SETFL, 0);
uart2_config.c_cflag = CRTSCTS | CS8 | CLOCAL | CREAD;
uart2_config.c_iflag = IGNPAR | ICRNL;
tcflush(test_uart, TCIFLUSH);
tcsetattr(test_uart, TCSANOW, &uart2_config);
// int interval = 0 - start_time;
// int bytes = l * sizeof(sample_test_uart);
// printf("Wrote %d byteson UART %s\n", bytes, uart_name);
int readval = 0;
int count = 0;
char *readbuf = malloc(10);
do {
usleep(1);
readval = read(test_uart, readbuf, 9);
if (readval < 0) {
printf("\n err : %d", errno);
perror("so this is the error");
}
printf("\n read :%s len : %d\n", readbuf, readval);
count++;
} while (count < 100);
close(test_uart);
return 0;
}
Here’s how I am sending and receiving data on my system :
port = serial.Serial("/dev/ttyUSB0", baudrate=57600)
while True:
# recv = port.readline()
# print(recv)
# print("recieved now sending")
wr = port.write(b"ack\n")
print("bytes written ", wr)
time.sleep(1)