使用来自 MATLAB 参考代码的 C/C++ 串行写入 COM 端口
serial write to COM port using C/C++ from MATLAB reference code
我正在使用一个简单的 matlab 代码将串行数据发送到 COM 端口设备,但是我遇到了问题并且想要等效的 C/C++ 代码来实现相同的结果。下面显示的是 MATLAB 代码。
s_port = serialport('COM1',9600);
configureTerminator(s_port,'CR');
write(s_port,char([50 01]),"char");
pause(1)
write(s_port,char([16 2 150]),"char")
write(s_port,char([55 18]),"char")
write(s_port,char(54),"char");
我尝试使用 MATLAB 编码器,但我认为没有与 matlab 的 serialwrite 函数等效的股票。
谢谢
因为端口被命名为“COM1”而不是“/dev/ttyS0”我假设你是 运行 on Windows.
您可以 fopen("COM1:")
和 fwrite()
,但这不会让您控制波特率。
为了控制串口设置(波特率、奇偶校验、停止位、流量控制),您需要使用Win32 API(CreateFile
,构建或修改一个DCB structure
, SetCommState
, WriteFile
). Official example
在其他(POSIX-like)操作系统上,您将使用 open
,构建或修改 termios
结构,tcsetattr
,write
。 Examples of termios configuration here on Stack Overflow
还有一些包装器库抽象出 OS 特定的部分,但我不能推荐它们中的任何一个。
我正在使用一个简单的 matlab 代码将串行数据发送到 COM 端口设备,但是我遇到了问题并且想要等效的 C/C++ 代码来实现相同的结果。下面显示的是 MATLAB 代码。
s_port = serialport('COM1',9600);
configureTerminator(s_port,'CR');
write(s_port,char([50 01]),"char");
pause(1)
write(s_port,char([16 2 150]),"char")
write(s_port,char([55 18]),"char")
write(s_port,char(54),"char");
我尝试使用 MATLAB 编码器,但我认为没有与 matlab 的 serialwrite 函数等效的股票。
谢谢
因为端口被命名为“COM1”而不是“/dev/ttyS0”我假设你是 运行 on Windows.
您可以 fopen("COM1:")
和 fwrite()
,但这不会让您控制波特率。
为了控制串口设置(波特率、奇偶校验、停止位、流量控制),您需要使用Win32 API(CreateFile
,构建或修改一个DCB structure
, SetCommState
, WriteFile
). Official example
在其他(POSIX-like)操作系统上,您将使用 open
,构建或修改 termios
结构,tcsetattr
,write
。 Examples of termios configuration here on Stack Overflow
还有一些包装器库抽象出 OS 特定的部分,但我不能推荐它们中的任何一个。