Search code examples
clinuxiottytermios

Serial I/O in C with termios: unreliable output capitalization


I have a very small C program which sends and receives newline-terminated ASCII strings to and from a serial device. It's plugged into my computer with a USB adapter, on /dev/ttyUSB0.

Most of the time it sends the commands just find, but occasionally it will capitalize all the lower-case letters to upper-case. It leaves all special characters alone.

The string I am sending is /home\n. About 1 out of every five times I run the program (by simply running ./a.out without recompiling), the sent message understood by the device is /HOME\n.

Here is my source code:

#include <stdio.h>
#include <stdlib.h>

#include "zserial.h"

int main() {
    char buf[256];
    int fd = connect("/dev/ttyUSB0");
    char *cmd = "/home\n";
    send(fd, cmd);
    receive(fd, buf, 256);
    puts(buf);

    exit(0);
}

And zserial.c:

#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "zserial.h"

int send(int fd, char *buf) {
    int len = strlen(buf);
    int nb = write(fd, buf, len);
    if (len != nb || nb < 1)  
        perror("Error: wrote no bytes!");
    tcdrain(fd);
    return nb; 
}

int receive(int fd, char *dst, int nbytes) {
    int i;
    char c;
    for(i = 0; i < nbytes;) {
        int r = read(fd, &c, 1); 
        /* printf("Read %d bytes\n", r); */
        if (r > 0) {
            dst[i++] = c;
            if (c == '\n') break;
        }
    }   
    dst[i] = 0; /* null-terminate the string */
    return i;
}

int connect(char *portname) {
    int fd; 
    struct termios tio;

    fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK);
    tio.c_cflag = CS8|CREAD|CLOCAL;
    if ((cfsetospeed(&tio, B115200) & cfsetispeed(&tio, B115200)) < 0) {
        perror("invalid baud rate");
        exit(-1);
    }   
    tcsetattr(fd, TCSANOW, &tio);

    return fd; 
}

What am I doing wrong? Is there some termios flag which modifies the output on a serial port?


Solution

  • c_oflag & OLCUC turns on the mapping of lowercase to uppercase on output. Since you never initialized tio, it's not surprising you got some random flags set.

    You have two choices:

    1. tcgetattr the current settings into a termios struct to initialize it, then modify the ones you're interested in, then write them back with tcsetattr

    2. initialize all the termios fields to known values, not just c_cflag and the speed fields.