

Using fread in Octave for data analysis I was able to receive the serial data but had no success with fprintf or fwrite to send the commands, even with pausing between characters. Using Realterm with chardly=100ms I can also successfully send the commands. With the python client associated with the device the commands can be successfully sent via keyboard input. ‘abcd’ to change the kind of data it sends. I have a serial device that looks for a simple 4-character command, e.g. The experience has led me to wonder what is behind the failure of serial commands from Octave. It was very educational since this was the first time I compiled anything with Visual Studio. I would like to thank you again and for taking the time to provide such a complete example. Here’s how it looked when I compiled and ran it with gcc (from MinGW). Here’s how it looked when I compiled and ran it using the cl compiler (that’s the C++ compiler used by Visual C++ / Visual Studio). If(!WriteFile(hSerial, bytes_to_send, 5, &bytes_written, NULL))įprintf(stderr, "%d bytes written\n", bytes_written) įprintf(stderr, "Closing serial port.") Send specified text (remaining command line arguments)ĭWORD bytes_written, total_bytes_written = 0 If(SetCommTimeouts(hSerial, &timeouts) = 0)įprintf(stderr, "Error setting timeouts\n") Timeouts.WriteTotalTimeoutMultiplier = 10 Timeouts.ReadTotalTimeoutMultiplier = 10 If(SetCommState(hSerial, &dcbSerialParams) = 0)įprintf(stderr, "Error setting device parameters\n") If (GetCommState(hSerial, &dcbSerialParams) = 0)įprintf(stderr, "Error getting device state\n") Set device parameters (38400 baud, 1 start bit,ĭcbSerialParams.DCBlength = sizeof(dcbSerialParams) OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) Open the highest available serial port numberįprintf(stderr, "Opening serial port.") Define the five bytes to send ("hello") To compile with cl, the Microsoft compiler:

Written by Ted Burke - last updated 13-2-2013 Either way, the resulting program “serial.exe” works the exact same.īy the way, for a simpler way to send arbitrary characters to a serial port without compiling anything at all, see my previous post. I show an example of each approach in the screenshots at the end of this post. In the former case, the file should be saved as “serial.cpp” and compiled as C++, whereas in the latter case, it can simply be saved as “serial.c” and compiled as plain C.

This program can be compiled using cl.exe (the C++ compiler used in Visual C++ / Visual Studio) or using gcc (the C compiler in MinGW). In this case, I’m sending the five characters “hello” via COM22 at 38400 baud, but of course the program can easily be modified to send a different string, or to use a different serial port or baudrate. This is a (relatively) simple example of a C program to send five bytes to a serial port in Windows.
