【问题标题】:How to redirect stdout to a COM Port如何将标准输出重定向到 COM 端口
【发布时间】:2015-08-24 15:37:58
【问题描述】:

谁能告诉我如何将标准输出重定向到 C 中的 COM 端口?

在 Windows 机器上工作。在线阅读微软使用设备文件和设备关键字,如控制台的 CON。他们也有一些用于 COM 端口,“COM1”。

但是,这样做似乎没有用? >>freopen( "COM5", "w", stdout );

感谢您的帮助。

cjg199

【问题讨论】:

  • 有什么不好的地方?
  • 改完后跑了个print f语句,没出现?
  • 返回错误了吗?
  • 代码在开发套件上运行,我在 COM5 端口上使用 puTTy,以提供输入和读取输出。该工具集有一系列打印功能,但它们不会打印浮点数,这是我需要的。感谢您的帮助

标签: c windows serial-port stdout


【解决方案1】:

COMx 是串行设备,必须进行配置。在底层,putty(或 kermit 或超级终端)会配置波特率、大小、奇偶校验和停止位。

并且应该以独占访问方式打开 COM 设备。这意味着如果腻子已经控制了线路,您将无法在其他程序中打开它。

所以正常的用法是:

  • 打开设备(CreateFileWinAPI函数)
  • 配置设备 (GetCommState - SetCommState)
  • 获取窗口句柄的文件描述符 (_open_osfhandle)
  • dup2复制文件描述符到fd 1

之后,您应该能够写入到 fd 1 的 stdout 并在串行线上获得输出。

有限的代码(没有错误处理和未经测试,因为我目前没有串口设备):

HANDLE hCom;
DCB dcb;
BOOL fSuccess;
int fd, cr;
hCom = CreateFile( TEXT("COM5"), GENERIC_READ | GENERIC_WRITE,
    0,    // exclusive access 
    NULL, // default security attributes 
    OPEN_EXISTING, 0, NULL);

// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.

SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
fSuccess = GetCommState(hCom, &dcb);

// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit - adapt to YOUR config

dcb.BaudRate = CBR_57600;     // set the baud rate
dcb.ByteSize = 8;             // data size, xmit, and rcv
dcb.Parity = NOPARITY;        // no parity bit
dcb.StopBits = ONESTOPBIT;    // one stop bit

fSuccess = SetCommState(hCom, &dcb);

fd = _open_osfhandle(hCom, 0);
cr = _dup2(fd, 1);

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多