如何在 Linux 上将波特率设置为 307,200? [英] How can I set the baud rate to 307,200 on Linux?

查看:26
本文介绍了如何在 Linux 上将波特率设置为 307,200?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我使用下面的代码来设置串口的波特率:

Basically I'm using the following code to set the baud rate of a serial port:

struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
tcsetattr(fd, TCSANOW, &options);

这很好用.但是知道我必须与使用波特率 307,200 的设备通信.我该如何设置?cfsetispeed(&options, B307200); 不起作用,没有定义 B307200.

This works very well. But know I have to communicate with a device that uses a baud rate of 307,200. How can I set that? cfsetispeed(&options, B307200); doesn't work, there is no B307200 defined.

我使用 MOXA Uport 1150(实际上是一个 USB 转串口转换器)和英特尔主板的标准串口进行了尝试.我不知道后者的确切类型,setserial 只是将其报告为 16550A.

I tried it using a MOXA Uport 1150 (that's actually a USB-to-serial converter) and the standard serial port of an Intel motherboard. I don't know the exact kind of the latter, setserial just reports it as 16550A.

推荐答案

Linux 对非标准波特率使用了一种肮脏的方法,称为波特率别名".基本上,您告诉串行驱动程序以不同的方式解释值 B38400.这由 serial_struct 成员 flags 中的 ASYNC_SPD_CUST 标志控制.

Linux uses a dirty method for non-standard baud rates, called "baud rate aliasing". Basically, you tell the serial driver to interpret the value B38400 differently. This is controlled with the ASYNC_SPD_CUST flag in serial_struct member flags.

您需要手动计算自定义速度的除数,如下所示:

You need to manually calculate the divisor for the custom speed as follows:

// Configure port to use custom speed instead of 38400
ioctl(port, TIOCGSERIAL, &ss);
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed;
closestSpeed = ss.baud_base / ss.custom_divisor;

if (closestSpeed < speed * 98 / 100 || closestSpeed > speed * 102 / 100) {
    fprintf(stderr, "Cannot set serial port speed to %d. Closest possible is %d
", speed, closestSpeed));
}

ioctl(port, TIOCSSERIAL, &ss);

cfsetispeed(&tios, B38400);
cfsetospeed(&tios, B38400);

当然,您需要具有合适的 baud_base 和除数设置的串行驱动程序.前面的代码段允许 2% 的偏差,这对于大多数用途来说应该是可以的.

Of course, you need a serial driver with suitable baud_base and divisor settings. The preceding snippet allows for 2% deviation, which should be ok for most purposes.

并告诉驱动程序将 B38400 再次解释为 38400 波特:

And to tell the driver to interpret B38400 as 38400 baud again:

ioctl(mHandle, TIOCGSERIAL, &ss);
ss.flags &= ~ASYNC_SPD_MASK;
ioctl(mHandle, TIOCSSERIAL, &ss);

请注意:我不确定此方法是否可以在其他 *nix 风格之间移植.

As a word of caution: I'm not sure if this method is portable between other *nix flavors.

这篇关于如何在 Linux 上将波特率设置为 307,200?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆