0

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. Shown below is the MATLAB code.

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.

Thanks

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
Zachary
  • 5
  • 3

1 Answers1

0

Because the port is named "COM1" and not "/dev/ttyS0" I assume you are running on Windows.

You can fopen("COM1:") and fwrite() to it, but that won't give you control over baud rate.

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). Official example

On other (POSIX-like) operating systems, you'd use open, build or modify a termios structure, tcsetattr, write. Examples of termios configuration here on Stack Overflow

There are also some wrapper libraries that abstract away the OS-specific parts, but I can't recommend any of them.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720