views:

1364

answers:

5

Hi,

I am working with a peripheral device that needs to be communicated through serial. I can send it commands using Hyperterminal, but now I need to write programs that will let me do it without Hyperterminal. Can somebody point me to a website and/or show me a sample hello world program to get me started? I have searched for many sites which give me uncompilable/ancient VC6 code.

Thanks

+3  A: 

In order to interface with the serial port, you open a file with one of the special filenames "COM1" through "COM9". For serial ports with higher numbers, the special filename begins with \\?\, which in C/C++ code must be escaped as "\\\\?\\COM10", etc.

http://msdn.microsoft.com/en-us/library/ms810467.aspx has a really good tutorial on using the serial port. Note that you should use the Windows file I/O functions such as CreateFile(), ReadFile(), and WriteFile(). I'm not sure if it will work to use standard I/O functions such as fopen(), fread(), and fwrite().

Adam Rosenfield
+2  A: 

Microsoft provides an article with sample code describing how to do this under Win32.

Glomek
A: 

I believe you will find plenty of sample code for C# as well if you find VC6 too ancient. I think there are also a bunch of "free" serial/COM port wrappers but I just wrote my own when I wrote an RS232 device controller piece of software.

google C# and serial port or rs232

I got these:

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx

You should have no problem finding suitable code with a google search.

Tim
+1  A: 

Boost:asio may be able to help as a serial device was added recently.

Fair warning though; the serial port documentation is light, presumably since it's quite new (it was added in asio 1.1.1 which was included in boost 1.36).

But working your way through asio is, IMHO, a better solution than using the raw Win32 API. Why? It'll be easier to read and maintain (it's a higher level API) and it'll be cross platform (except where you need to specify the OS-specific device name).

The Boost - Users and asio.user mailing lists are quite active and friendly and ought to be able to help you out if you get stuck.

MattyT
A: 

If using .NET 2.0 see System.IO.Ports and this article should be helpful. If direct Win32, then Adam's answer is best.

kenny