HANDLE m_hCom;
  BOOL  InitilizeCom()//初始化串口
 {
         m_hCom = CreateFile( "COM2", GENERIC_READ | GENERIC_WRITE, 0, 
NULL, OPEN_EXISTING, ILE_ATTRIBUTE_NORMAL, NULL );
if ( INVALID_HANDLE_VALUE==m_hCom )
{
              return FALSE;
}
SetupComm( m_hCom, 2048, 2048 ); DCB dcb;
GetCommState( m_hCom, &dcb );
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY; if ( !SetCommState( m_hCom, &dcb ) )
{
CloseHandle( m_hCom );
                  return false;
}
    PurgeComm( m_hCom, PURGE_TXABORT | PURGE_RXABORT |
                                      PURGE_TXCLEAR | PURGE_RXCLEAR ) ;    COMMTIMEOUTS CommTimeOuts;
    CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF ;
    CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
    CommTimeOuts.ReadTotalTimeoutConstant = 0 ;
    CommTimeOuts.WriteTotalTimeoutMultiplier = 1;
    CommTimeOuts.WriteTotalTimeoutConstant = 0 ;
    SetCommTimeouts( m_hCom, &CommTimeOuts ) ;
     return true;
     
     }
    
    BOOL SendDataToCom(char* buf)//把要发送的数据放到buf中
   {
         ULONG uByteOfSend = 0;
         int uSend = strlen(buf);
         if( !WriteFile(m_hCom, buf, uSend, &uByteOfSend, NULL) )
{
return FALSE;
}
      return true;
    }首先初始化串口,设置波特率,停止位,数据位,校验位。

解决方案 »

  1.   

    HANDLE CreateFile(    LPCTSTR lpFileName, // pointer to name of the file 
        DWORD dwDesiredAccess, // access (read-write) mode 
        DWORD dwShareMode, // share mode 
        LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes 
        DWORD dwCreationDistribution, // how to create 
        DWORD dwFlagsAndAttributes, // file attributes 
        HANDLE hTemplateFile // handle to file with attributes to copy  
      );#include <vcl.h>
    #pragma hdrstop#include "Unit1.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TForm1 *Form1;
    // Define may be used at same time,
    // extern TForm2 *Form2;
    HANDLE hcom;
    HANDLE xModemThreadHandle;
    DWORD  idxModemThread;
    // Define one extern thread and used serier port,
    // extern void xModemThread();
    //---------------------------------------------------------------------------
    bool __fastcall TForm1::InitPort(AnsiString PortName)
    {
    _DCB        myDCB;
    COMMTIMEOUTS  myTMO;
    bool  Result;  // simply define communication handle,if existing and closing
      // renew to create,
      if(hcom != 0/*INVALID_HANDLE_VALUE*/)
        CloseHandle(hcom);  //create communication handle,
      hcom=CreateFile(PortName.c_str(), // port name
                    GENERIC_READ&brvbar;GENERIC_WRITE,  // RW access mode
                      0, // exclusive mode
                      NULL, // no security attributes
                      OPEN_EXISTING, // open existing port
                      0, // not overlapped
                      0);
      Result = (hcom!=INVALID_HANDLE_VALUE);
      if(!Result)
          MessageDlg("not open port:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0);
      else
        {
        //set communlcation mask,set of events to be monitored,
        if(!SetCommMask(hcom,EV_RXFLAG))
          {
          if(MessageDlg("not set mask:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!= mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
        //initializes the communications parameters,
        if(!SetupComm(hcom,4096,4096))//4096 is specifies send and recvieve size,
          {
          if(MessageDlg("not setup communiation:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!= mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
        //get the communications state and DCB struct,
        if(!GetCommState(hcom,&myDCB))
          {
          if(MessageDlg("not get state:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!= mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
        //set dcb state,include baudrate/bytebit/stopbit/parity,
        myDCB = GetDCBParater(myDCB);
        // if(!BuildCommDCB("COM1:baud=1200 parity=N data=8 stop=1",&myDCB));
        // { 以上个的函数用法同下 }
        if(!SetCommState(hcom,&myDCB))
          {
          //unsigned long TTT = GetLastError();
          if(MessageDlg("not set state:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!=mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
        if(!GetCommTimeouts(hcom,&myTMO))
          {
          if(MessageDlg("not get out time:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!= mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
        //set out time function and coeff.
          myTMO.ReadIntervalTimeout = MAXDWORD;
          myTMO.ReadTotalTimeoutMultiplier = 0;
          myTMO.ReadTotalTimeoutConstant = 0;
          myTMO.WriteTotalTimeoutMultiplier =0;
          myTMO.WriteTotalTimeoutConstant =1000;
        if(!SetCommTimeouts(hcom,&myTMO))
          {
          if(MessageDlg("not set out time:"+PortName,
                      mtConfirmation,TMsgDlgButtons()<<mbYes<<mbNo,0)!=mrYes)
          {
          CloseHandle(hcom);
          Result=false;
          exit(1);
          }
          else{
          CloseHandle(hcom);
          Result=true;
          exit(1);
          }
          }
      //API_Function: clear send buffer,
        PurgeComm(hcom,PURGE_TXCLEAR);
      //API-Function: clear recvive buffer,
        PurgeComm(hcom,PURGE_RXCLEAR);
        }
      return Result;
    }bool __fastcall TForm1::RecvData()
    {
      bool Result;
      AnsiString ReadStr;
      unsigned char  ReadBuffer[100];
      unsigned long  ReadNum;  memset(ReadBuffer,0,sizeof(ReadBuffer));
      Result = ReadFile(hcom,ReadBuffer,sizeof(ReadBuffer),&ReadNum,NULL);
      Form1->RECommand->Lines->Add("Receive:\r"+ReadStr );
      if(Result)
        {
        for(int i=0;i<sizeof(ReadBuffer);i++)
          ReadStr = ReadStr + (char)ReadBuffer[i];
        if(sizeof(ReadStr) == 4)
            ReadStr = "0";
        }
    RECommand->Lines->Add(ReadStr );
      return 1;
    }
    //在这里我发送的是字符串。
    bool __fastcall TForm1::SendStrToPort(AnsiString ReadStr)
    {
    bool Result;
    unsigned char B[100];
    unsigned long  SendNum;
    for(int i=1;i<=ReadStr.Length();i++)
      {
        B[i-1]= (int)ReadStr[i];
      }
      SendNum = ReadStr.Length();
      WriteFile(hcom,B,SendNum,&SendNum,NULL);
      if(!WriteFile(hcom,B,SendNum,&SendNum,NULL))
        {
        Result = false;
        if(Application->MessageBox("without write", NULL, MB_OKCANCEL) != IDOK)
          exit(1);
        }
    return Result;
    }转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载
    转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载转载
      

  2.   

    太长了
    其实就是:初始化
    修改串口的一些参数,比如说波特率之类的然后用writefile,如果读取,请用readfile