简体   繁体   English

使用 MATLAB 参考代码中的 C/C++ 串行写入 COM 端口

[英]serial write to COM port using C/C++ from MATLAB reference code

I am using a simple matlab code to send serial data to a COM port device, however I am having issues and would like an equivalent C/C++ code to achieve the same result.我正在使用一个简单的 matlab 代码将串行数据发送到 COM 端口设备,但是我遇到了问题,想要一个等效的 C/C++ 代码来实现相同的结果。 Shown below is the MATLAB code.下面显示的是 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");

I attempted to use MATLAB coder, but I don't think there is a stock equivalent to matlab's serialwrite function.我尝试使用 MATLAB 编码器,但我认为没有与 matlab 的 serialwrite function 相当的库存。

Thanks谢谢

Because the port is named "COM1" and not "/dev/ttyS0" I assume you are running on Windows.因为端口被命名为“COM1”而不是“/dev/ttyS0”,所以我假设您在 Windows 上运行。

You can fopen("COM1:") and fwrite() to it, but that won't give you control over baud rate.您可以对其进行fopen("COM1:")fwrite() ,但这不会让您控制波特率。

For control over serial port settings (baud rate, parity, stop bits, flow control), you need to use the Win32 API ( CreateFile , build or modify a DCB structure , SetCommState , WriteFile ).要控制串口设置(波特率、奇偶校验、停止位、流控制),您需要使用 Win32 API( CreateFile ,构建或修改DCB structureSetCommStateWriteFile )。 Official example 官方示例

On other (POSIX-like) operating systems, you'd use open , build or modify a termios structure, tcsetattr , write .在其他(类似 POSIX 的)操作系统上,您将使用open 、构建或修改termios结构、 tcsetattrwrite Examples of termios configuration here on Stack Overflow Stack Overflow 上的 termios 配置示例

There are also some wrapper libraries that abstract away the OS-specific parts, but I can't recommend any of them.还有一些包装库可以抽象出特定于操作系统的部分,但我不能推荐其中任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM