Tausen
Tausen

Reputation: 55

C: read() hangs without getting input from serial port on unix

I'm having some issues getting data from a serial port using C on my Ubuntu 12 system.

I'm using open() and read(), and here is my code:

Fd = open("/dev/ttyUSB0", O_RDONLY | O_NOCTTY);
if (Fd == -1) {
    printf("Could not open serial port: %s\n", strerror(errno));
    return 1;
}

fcntl(Fd, F_SETFL, 0);

char buf;
while (1) {
    read(Fd, &buf, 1);
    printf("%c", buf);
}

However - my serial device is set to send "Boot.\r\n" followed by "To send: ", but when I attach the device and start the program, I only get the first line ("Boot.") and then no more. If I start gtkterm/picocom, I get both lines straight away.

I've also tried adding a signal handler for SIGTERM to get the port closed properly, using:

void signal_callback_handler(int signum) {
    printf("Caught SIGTERM\n");
    close(Fd);
    exit(signum);
}

and

signal(SIGINT, signal_callback_handler);

Using this, I get the following when I press CTRL-C:

Boot.
^CTo send: Caught SIGTERM

I've also tried setting up the port first, using:

struct termios port_settings;          // structure to store the port settings in
cfsetispeed(&port_settings, B115200);  // set baud rates
cfsetospeed(&port_settings, B115200);
port_settings.c_cflag &= ~PARENB;      // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcsetattr(Fd, TCSANOW, &port_settings);// apply the settings to the port

This only makes the situation worse - I get spammed with � :(

I'd be very appreciative of any help, thanks in advance!

Upvotes: 3

Views: 2221

Answers (1)

TJD
TJD

Reputation: 11896

Looks like your printf is just not being flushed until it hits a newline. That's why you get the first part of the output, but not the second. You could add fflush(stdout) after your printf to see the output immediately.

Upvotes: 5

Related Questions