1

我有一个非常小的 C 程序,它向串行设备发送和接收以换行符结尾的 ASCII 字符串。它通过 USB 适配器插入我的计算机,在/dev/ttyUSB0.

大多数时候它发送的命令只是 find,但偶尔它会将所有小写字母大写。它只留下所有特殊字符。

我发送的字符串是/home\n. 大约每五次我运行程序(通过简单地运行./a.out而不重新编译),设备理解的发送消息是/HOME\n.

这是我的源代码:

#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);
}

和 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; 
}

我究竟做错了什么?是否有一些 termios 标志可以修改串行端口上的输出?

4

1 回答 1

3

c_oflag & OLCUC在输出上打开小写到大写的映射。由于您从未初始化tio,因此设置了一些随机标志也就不足为奇了。

你有两个选择:

  1. tcgetattr将当前设置放入一个termios结构中以对其进行初始化,然后修改您感兴趣的设置,然后将它们写回tcsetattr

  2. 将所有termios 字段初始化为已知值,而不仅仅是c_cflag速度字段。

于 2014-10-01T03:16:39.327 回答