cat如何知道串口的波特率?

sta*_*nri 26 linux devices serial-port

我经常使用cat我的 FPGA 开发板通过串行连接在控制台中查看调试信息,但我从来没有告诉 linux 波特率是多少。cat 如何知道串口连接的波特率是多少?

sta*_*nri 38

stty实用程序设置或报告作为其标准输入设备的终端 I/O 特性。在通过该特定介质建立连接时会使用这些特性。cat不知道波特率,而是打印在从特定连接接收到的屏幕信息上。

例如,stty -F /dev/ttyACM0给出了 ttyACM0 设备的当前波特率。


cla*_*cke 9

cat只使用端口已经配置的任何设置。使用这个小 C 代码片段,您可以看到当前为特定串行端口设置的波特率:

获取波特率.c

#include <termios.h>
#include <unistd.h>
#include <stdio.h>

int main() {
  struct termios tios;
  tcgetattr(0, &tios);
  speed_t ispeed = cfgetispeed(&tios);
  speed_t ospeed = cfgetospeed(&tios);
  printf("baud rate in: 0%o\n", ispeed);
  printf("baud rate out: 0%o\n", ospeed);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行:

./get-baud-rate < /dev/ttyS0 # or whatever your serial port is
Run Code Online (Sandbox Code Playgroud)

您得到的数字可以在 中查找/usr/include/asm-generic/termios.h,其中有#defines 等B9600。请注意,头文件和get-baud-rate输出中的数字都是八进制的。

也许你可以试验一下,看看这些数字在新启动时是什么样的,以及它们以后是否会改变。

  • 我刚刚找到了执行此操作的 `stty` 命令。例如,`stty -F /dev/ttyACM0` 为我提供了当前的波特率,这对我的设备来说是正确的。 (2认同)