首页 > 解决方案 > 如何在 Linux 中检查对串行设备 /dev/ttySX 的正确写入

问题描述

我需要通过串行设备实现特定协议。我已经完成了消息构造器并准备好发送的字节列表。我遇到的问题是我无法验证我是否正确地将字节发送到/dev/ttyS2接口中。我的串行消息遵循结构PATTERN + MESSAGE

我可以通过以下方式从串行设备读取并过滤一些收到的已知消息:

cat /dev/ttyS2 | grep PATTERN

在我的程序(下面的代码)中,如果我发送消息,我无法使用前面的命令看到我的帧:

static FILE * file_stream = NULL;
static int file_des = 0;

static void printSampleMessage(void) {
struct termios SerialPortSettings; /* Create the structure                          */

/* Open linux device */
file_des = open("/dev/ttyS2", O_RDWR | O_NOCTTY);

/*---------- Setting the Attributes of the serial port using termios structure --------- */

tcgetattr(file_des, &SerialPortSettings);   /* Get the current attributes of the Serial port */

/* Setting the Baud rate */
cfsetispeed(&SerialPortSettings,B38400); /* Set Read  Speed as 38400                       */
cfsetospeed(&SerialPortSettings,B38400); /* Set Write Speed as 38400                       */

/* 8N1 Mode */
SerialPortSettings.c_cflag &= ~PARENB;   /* Disables the Parity Enable bit(PARENB),So No Parity   */
SerialPortSettings.c_cflag &= ~CSTOPB;   /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
SerialPortSettings.c_cflag &= ~CSIZE;    /* Clears the mask for setting the data size             */
SerialPortSettings.c_cflag |=  CS8;      /* Set the data bits = 8                                 */

SerialPortSettings.c_cflag &= ~CRTSCTS;       /* No Hardware flow Control                         */
SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines       */


SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          /* Disable XON/XOFF flow control both i/p and o/p */
SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode                            */

SerialPortSettings.c_oflag &= ~OPOST; /*No Output Processing RAW mode*/


if((tcsetattr(file_des,TCSANOW,&SerialPortSettings)) != 0) {/* Set the attributes to the termios structure*/
} else {
}

/* Obtain file stream descriptor */
file_stream = fdopen(file_des, "r+");
fputs ( "PATTERN+MESSAGE", file_stream);
}

cat /dev/ttyS2 | grep PATTERN但是,使用该命令时,我无法看到自己的消息。如何检查我是否真的在串行设备中发送我的PATTERN+ 消息?

我在程序选项方面非常有限。我的设置是嵌入式 linux 与板上的另一个微控制器通信(没有连接物理嗅探器的测试点)并且没有可用的 minicom,因为我使用的 linux 发行版非常基本,我不能只是apt-get install XX

标签: linuxserial-port

解决方案


推荐阅读