Serial Port Programming using Win32 API(转载)


In this tutorial we will learn How to communicate with an external device like a microcontroller board or modem using the Serial port of a windows PC(Windows XP,7). The software is written using C language and communicates with the Serial Port using Win32 API.

In Windows ,Serial ports are named as COM1,COM2 ,COM3.. etc .COM1 and COM2 usually refer to the hardware serial ports present in the PC while COM numbers in double digits likeCOM32,COM54,COM24.. etc are given to USB to Serial Converters or PCI serial port extenders.
If your PC does not have any hardware serial ports (RS232 DB9 ports), you can use USB to Serial Converter's like USB2SERIAL.

If you are interested in setting up an RS485 network controlled by your PC to control a robot or a sensor network ,you can use USB2SERIAL board (buy here).

The Board can also be used as an FT232 development board.

Sourcecodes

All the C sourefiles used in this tutorial can be downloaded from our GitHub Page.If you are new to Github ?Check this article to download code .

Compilers and IDE's used
To Compile the C file you can use either Visual Studio Express edition from Microsoft or MinGW(Windows port of GCC).
Visual Studio 2013 Express Edition for Desktop can be freely downloaded (its a large download) from Microsoft's website. Here is a short tutorial on how to setup a C project in VS 2013.
If you don't want to download the Visual Studio and want something simpler you can use MinGW, which is an open source port of GCC for windows environment. After you have installed the MinGW, package make sure to add gcc to system path so that you can call it from anywhere.

USB2SERIAL)which is recognized as COM24 (this may be different under your system). If you double click on COM24,you can see the details of the corresponding port.

Notepad++ and type the below code and save it as "serial.c".If you are using IDE like VS Express, use the one integrated with it. 

#include<windows.h>
#include
int main()
{
  HANDLE hComm;

  hComm = CreateFile("\\\\.\\COM24",                //port name
                      GENERIC_READ | GENERIC_WRITE, //Read/Write
                      0,                            // No Sharing
                      NULL,                         // No Security
                      OPEN_EXISTING,// Open existing port only
                      0,            // Non Overlapped I/O
                      NULL);        // Null for Comm Devices

  if (hComm == INVALID_HANDLE_VALUE)
      printf("Error in opening serial port");
  else
      printf("opening serial port successful");

  CloseHandle(hComm);//Closing the Serial Port

  return 0;
}

Find out the COM port corresponding to your system and substitute in CreateFile() instead of COM24.

Now compile and run the program by pressing F5 in Visual Studio
or
by running the following command for gcc (MingW).Please make sure that gcc is added to you system path.

D:\> gcc -o serial serial.c

Now let me explain the code ,
windows.h header file contain all the definitions, function prototypes and constants required by the program.

In Windows everything is controlled by using handles.In the first line
HANDLE hComm;
we declare a handle 
hcomm to access and control the serial port.

Next we open a connection to serial port using CreateFile() function. The CreateFile() function on success, returns a valid handle to the hComm variable.

CreateFile() function takes 7 arguments,

1. Name of the serial port to be opened here \\\\.\\COM24.
2. Mode of access, here Read and Write
3. Sharing options, Serial ports can't be shared so 0
4. NULL for Serial ports, used for File operations
5. Open the existing port, OPEN_EXISTING
6. Overlapped IO or Non overlapped IO, here 0 means we are using NonOverlapped IO. Overlapped IO is used for multithreaded programs where
several threads can interact with the port simultaneously.
7. NULL for Serial port, used for file operations

If the function succeeds in opening the serial port, it returns a valid handle to hcomm which is then used for error checking.

After that the connection to the port is closed using

CloseHandle(hComm);

Please note that in Windows, COM port numbers from COM1 to COM9 are reserved by the system. If you are using a serial port whose COM port number falls in that range, you don't need the back slashes (\\\\.\\)shown in the above code.

You can access the serial port like this,

hComm = CreateFile("COM1",          // for COM1—COM9 only
                   GENERIC_READ | GENERIC_WRITE, //Read/Write
                   0,               // No Sharing
                   NULL,            // No Security
                   OPEN_EXISTING,   // Open existing port only
                   0,               // Non Overlapped I/O
                   NULL);

   

USB2SERIAL).

I have interfaced a microcontroller board(MSP430G2553 on Launch Pad) to the serial port using a null modem cable like this

You can use any microcontroller of your choice like 8051,AVR or ARM(LPC2148).The Controller waits for a character to be received and lights up the corresponding LED. The code for MSP430 is included in the zip file.If you want to know how to configure the MSP430 controller UART you can check this tutorial.


Please note that if you are using a DB9 RS232 Serial Port of your PC, you will have to build a RS232 signal level converter at the microcontroller side to decode the RS232 signal.
Directly connecting the PC's RS232 Serial port to MSP430 's pins will damage the chip.
Here is the screen shot of the Program writing into serial port.

   

http://xanthium.in/Serial-Port-Programming-using-Win32-API