全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:2902
推到 Plurk!
推到 Facebook!

RS232 Developer's refence

 
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#1 引用回覆 回覆 發表時間:2003-09-15 15:31:00 IP:61.218.xxx.xxx 未訂閱

RS232 Developer's refence

資料來源:不詳
 Communications Resource Handles 
 1. A process uses the CreateFile function to open a handle to a 
    communications resource. For example, specifying COM1 opens a 
    handle to a serial port, and LPT1 opens a handle to a parallel 
    port. 
 2. When the process uses CreateFile to open a communications
    resource, it must specify certain values for the following 
    parameters: 
    The fdwShareMode parameter must be zero, opening the resource for exclusive access.  
    The fdwCreate parameter must specify the OPEN_EXISTING flag.  
    The hTemplateFile parameter must be NULL. 
 
 Modification of Communications Resource Settings 
 1. Members of the DCB structure specify the configuration settings 
    such as the baud rate, the number of data bits per byte, and the 
    number of stop bits per byte. 
 2. To determine the initial configuration of a serial 
    communications resource, a process calls the GetCommState 
    function, which fills in a serial port DCB structure with the 
    current configuration settings. 
 3. To modify this configuration, a process specifies a DCB 
    structure in a call to the SetCommState function. 
 4. When a process needs to modify only a few of the DCB 
    configuration settings, it should first call GetCommState to 
    fill in a DCB structure with the current configuration. 
    Then the process can adjust the important values in the DCB 
    structure and reconfigure the device by calling SetCommState and 
    specifying the modified DCB structure. 
    This procedure ensures that the unmodified members of the DCB 
    structure contain appropriate values. 
  
 Read and Write Operations 
 1. The Win32 API supports both synchronous and asynchronous
    (overlapped) file I/O operations on serial communications 
    resources.  
 2. Overlapped operations enable the calling thread to perform other 
    tasks while the operation executes in the background.  
 3. A thread uses the ReadFile or ReadFileEx function to read from a 
    communications resource, and the WriteFile or WriteFileEx 
    function to write to a communications resource.  
 4. ReadFile and WriteFile can be performed synchronously or 
    asynchronously.  
 5. ReadFileEx and WriteFileEx can only be performed asynchronously. 
   
 Overlapped Operations 
 1. To enable overlapped I/O operations on a communications
    resource, the thread must specify the FILE_FLAG_OVERLAPPED flag
    in the CreateFile function when the handle is opened.  
 2. To execute the ReadFile or WriteFile function as an overlapped 
    operation, the calling thread must specify a pointer to an 
    OVERLAPPED structure. 
 3. The OVERLAPPED structure must contain a handle to a manual-reset
    (not an auto-reset) event object. 
 4. The system sets the state of the event object to not-signaled 
    when a call to the I/O function returns before the operation has 
    been completed.  
 5. The system sets the state of the event object to signaled when 
    the operation has been completed. 
   
 Time-Outs
 1. Time-outs can cause a ReadFile, ReadFileEx, WriteFile, or 
    WriteFileEx operation to conclude when a time-out interval 
    elapses, even though the specified number of characters have not 
    been read or written. 
 2. An application should always determine the current time-out 
    values after opening the resource, and then explicitly set them 
    to meet its requirements.  
 3. To determine the current time-out values of a communications 
    resource, use the GetCommTimeouts function. To change the time-
    out values, use the SetCommTimeouts function.  
 4. Two types of time-outs are enabled by the time-out parameters: 
    interval time-out and total time-out. 
 5. An interval time-out occurs when the time between the receipt of
    any two characters exceeds a specified number of milliseconds. 
 6. A total time-out occurs when the total amount of time consumed 
    by a read operation exceeds a calculated number of milliseconds. 
 7. Write operations support only total time-outs.  
 8. Read operations support both interval and total time-outs, 
    which can be used separately or combined. 
   
 Communications Events 
 1. A process can monitor a set of events that occur in a
    communications resource. For example, an application can use
    event monitoring to determine when the CTS (clear-to-send) and 
    DSR (data-set-ready) signals change state.  
 2. A process can monitor events on a given communications resource 
    by using the SetCommMask function to create an event mask. 
 3. To determine the current event mask for a communications 
    resource, a process can use the GetCommMask function. 
 4. The following values specify events that can be monitored: 
    EV_BREAK   A break was detected on input. 
    EV_CTS     The CTS (clear-to-send) signal changed state. 
    EV_DSR     The DSR (data-set-ready) signal changed state. 
    EV_ERR     A line-status error occurred. Line-status errors are 
               CE_FRAME, CE_OVERRUN, and CE_RXPARITY. 
    EV_RING    A ring indicator was detected. 
    EV_RLSD    The RLSD (receive-line-signal-detect) signal changed 
               state. 
    EV_RXCHAR  A character was received and placed in the input 
               buffer. 
    EV_RXFLAG  The event character was received and placed in the
               input buffer. The event character is specified in the 
               device's DCB structure, which is applied to a serial
               port by using the SetCommState function. 
    EV_TXEMPTY The last character in the output buffer was sent. 
 5. After a set of events is specified, a process uses the 
    WaitCommEvent function to wait for one of the events to occur 
/*生活是一種藝術,用心生活才能享受生活*/
發表人 - axsoft 於 2003/09/15 15:51:21
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#2 引用回覆 回覆 發表時間:2003-09-15 15:53:08 IP:61.218.xxx.xxx 未訂閱

Configuring a Communications Resource

資料來源:不詳
This example opens a handle to COM1 and fills in a DCB structure 
with the current configuration. The DCB structure is then modified 
and used to reconfigure the device.    Unit1.cpp    //---------------------------------------------------------------------------
// The following example opens a handle to COM1 and fills in a DCB structure
// with the current configuration. The DCB structure is then modified and
// used to reconfigure the device.    #include 
#pragma hdrstop    #include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------    void __fastcall TForm1::FormCreate(TObject *Sender)
{
   DCB dcb;
   HANDLE hCom;
   DWORD dwError;
   BOOL fSuccess;       hCom = CreateFile("COM1",
       GENERIC_READ | GENERIC_WRITE,
       0,    /* comm devices must be opened for exclusive-access */
       NULL, /* no security attrs */
       OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
       0,    /* not overlapped I/O */
       NULL  /* hTemplate must be NULL for comm devices */
       );       /* handle error */
   if (hCom == INVALID_HANDLE_VALUE) {
       dwError = GetLastError();
   }       /*
    * Omit the call to SetupComm to use the default queue sizes.
    * Get the current configuration.
    */       fSuccess = GetCommState(hCom, &dcb);       if (fSuccess) {
      Label2->Caption=IntToStr(dcb.BaudRate);
   }       /* Handle the error. */
   if (!fSuccess) {
      /* Fill in the DCB: baud=9600, 8 data bits, no parity, 1 stop bit. */
      dcb.BaudRate = 9600;
      dcb.ByteSize = 8;
      dcb.Parity = NOPARITY;
      dcb.StopBits = ONESTOPBIT;          fSuccess = SetCommState(hCom, &dcb);
   }
}
//---------------------------------------------------------------------------
     Unit1.h    /---------------------------------------------------------------------------    #ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
        TLabel *Label1;
        TLabel *Label2;
        void __fastcall FormCreate(TObject *Sender);
private: // User declarations
public:  // User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
/*生活是一種藝術,用心生活才能享受生活*/
發表人 - axsoft 於 2003/09/15 15:54:28
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#3 引用回覆 回覆 發表時間:2003-09-15 15:56:37 IP:61.218.xxx.xxx 未訂閱

Monitoring Communications Events

資料來源:不詳
     This example code opens the serial port for overlapped I/O, 
creates an event mask to monitor CTS and DSR signals, and then waits 
for an event to occur. The WaitCommEvent function should be executed 
as an overlapped operation so the other threads of the process 
cannot perform I/O operations during the wait.     Unit1.cpp     // The following example code opens the serial port for overlapped I/O,
// creates an event mask to monitor CTS and DSR signals, and then waits
// for an event to occur. The WaitCommEvent function should be executed
// as an overlapped operation so the other threads of the process cannot
// perform I/O operations during the wait.    //---------------------------------------------------------------------------    #include 
#pragma hdrstop    #include "Unit1.h"
#include     // for assert()
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"    DWORD dwError;    TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------    void __fastcall TForm1::FormCreate(TObject *Sender)
{
   HANDLE hCom;
   OVERLAPPED o;
   BOOL fSuccess;
   DWORD dwEvtMask;       hCom = CreateFile("COM1",
       GENERIC_READ | GENERIC_WRITE,
       0, /* exclusive access */
       NULL, /* no security attrs */
       OPEN_EXISTING,
       FILE_FLAG_OVERLAPPED,
       NULL
       );       if (hCom == INVALID_HANDLE_VALUE) {
       dwError = GetLastError();
   }       /*** Set the event mask. ***/
   fSuccess = SetCommMask(hCom, EV_CTS | EV_DSR);       if (!fSuccess) {
       dwError = GetLastError();
   }       /*** Create an event object for use in WaitCommEvent. ***/
   o.hEvent = CreateEvent(NULL,  /* no security attributes */
                          FALSE, /* auto reset event */
                          FALSE, /* not signaled */
                          NULL   /* no name */
                         );       assert(o.hEvent);       if (WaitCommEvent(hCom, &dwEvtMask, &o)) {
       if (dwEvtMask & EV_DSR) {
       Label1->Caption="The DSR (data-set-ready) signal changed state";
       }           if (dwEvtMask & EV_CTS) {
       Label1->Caption="The CTS (clear-to-send) signal changed state.";
       }
   }
}
//---------------------------------------------------------------------------    Unit1.H
//---------------------------------------------------------------------------    #ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
        TLabel *Label1;
        void __fastcall FormCreate(TObject *Sender);
private: // User declarations
public:  // User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
/*生活是一種藝術,用心生活才能享受生活*/
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#4 引用回覆 回覆 發表時間:2003-09-15 15:59:51 IP:61.218.xxx.xxx 未訂閱

Receiving Characters

資料來源:不詳
This example code opens the serial port for receiving characters. It
consists of a Form with a Memo object and a Thread object that 
handles incoming serial data. The thread uses the ReadFile function 
to read data from the serial port     
Unit1..cpp  
//---------------------------------------------------------------------------    #include 
#pragma hdrstop    #include "Unit1.h"
#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"    // GLOBAL VARIABLES
HANDLE hComm = NULL;
TRead *ReadThread;   // the pointer of the assigned thread
COMMTIMEOUTS ctmoNew = {0}, ctmoOld;    TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------    void __fastcall TForm1::FormCreate(TObject *Sender)
{
  DCB dcbCommPort;      // OPEN THE COMM PORT.
  // REPLACE "COM2" WITH A STRING OR "COM1", "COM3", ETC. TO OPEN
  // ANOTHER PORT.      hComm = CreateFile("COM1",
                      GENERIC_READ | GENERIC_WRITE,
                      0,
                      0,
                      OPEN_EXISTING,
                      0,
                      0);      // IF THE PORT CANNOT BE OPENED, BAIL OUT.      if(hComm == INVALID_HANDLE_VALUE) Application->Terminate();      // SET THE COMM TIMEOUTS IN OUR EXAMPLE.
  //Timeout = (MULTIPLIER * number_of_bytes)   CONSTANT      GetCommTimeouts(hComm,&ctmoOld);  // while terminating, turn back to the old setting
  ctmoNew.ReadTotalTimeoutConstant = 100;
  ctmoNew.ReadTotalTimeoutMultiplier = 0;
  SetCommTimeouts(hComm, &ctmoNew);      // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
  // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
  // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
  // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
  // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.      dcbCommPort.DCBlength = sizeof(DCB);
  GetCommState(hComm, &dcbCommPort);
  BuildCommDCB("9600,N,8,1", &dcbCommPort);
  SetCommState(hComm, &dcbCommPort);      // ACTIVATE THE THREAD. THE FALSE ARGUMENT SIMPLY MEANS IT HITS THE
  // GROUND RUNNING RATHER THAN SUSPENDED.      ReadThread = new TRead(false);    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
  // TERMINATE THE THREAD.      ReadThread->Terminate();      // WAIT FOR THREAD TO TERMINATE,
  // PURGE THE INTERNAL COMM BUFFER,
  // RESTORE THE PREVIOUS TIMEOUT SETTINGS,
  // AND CLOSE THE COMM PORT.      Sleep(250);
  PurgeComm(hComm, PURGE_RXABORT);
  SetCommTimeouts(hComm, &ctmoOld);
  CloseHandle(hComm);    }
//---------------------------------------------------------------------------    Unit1.h    //---------------------------------------------------------------------------    #ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
        TMemo *Memo1;
        void __fastcall FormCreate(TObject *Sender);
        void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
private: // User declarations
public:  // User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif        --------------------------------------------------------------------------------    Unit2.cpp    // DisplayIt() it must be declared as a __fastcall type in the header file.
//---------------------------------------------------------------------------    #include 
#pragma hdrstop    #include "Unit1.h"
#include "Unit2.h"
#pragma package(smart_init)
extern HANDLE hComm;
char InBuff[100];    //---------------------------------------------------------------------------    //   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall Unit2::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------    __fastcall TRead::TRead(bool CreateSuspended)
        : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall TRead::Execute()
{
  //---- Place thread code here ----      DWORD dwBytesRead;      // MAKE THE THREAD OBJECT AUTOMATICALLY DESTROYED WHEN THE THREAD
  // TERMINATES.      FreeOnTerminate = true;      while(!Terminated)
  {       // TRY TO READ CHARACTERS FROM THE SERIAL PORT.
   // IF THERE ARE NONE, IT WILL TIME OUT AND TRY AGAIN.
   // IF THERE ARE, IT WILL DISPLAY THEM.         ReadFile(hComm, InBuff, 50, &dwBytesRead, NULL);                 if(dwBytesRead)
     {
       InBuff[dwBytesRead] = 0; // NULL TERMINATE THE STRING
       Synchronize(DisplayIt);
     }       }
}
//---------------------------------------------------------------------------
void __fastcall TRead::DisplayIt()
{      // NOTE THAT IN THIS EXAMPLE, THERE IS NO EFFORT TO MONITOR
  // HOW MUCH TEXT HAS GONE INTO Memo1. IT CAN ONLY HOLD ABOUT 32K.
  // ALSO, NOTHING IS BEING DONE ABOUT NON-PRINTABLE CHARACTERS
  // OR CR-LF'S EMBEDDED IN THE STRING.      // DISPLAY THE RECEIVED TEXT.      Form1->Memo1->SetSelTextBuf(InBuff);    }    Unit2.cpp    /---------------------------------------------------------------------------    #ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include 
//---------------------------------------------------------------------------
class TRead : public TThread
{
private:
protected:
        void __fastcall DisplayIt(void);
        void __fastcall Execute();
public:
        __fastcall TRead(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif
/*生活是一種藝術,用心生活才能享受生活*/
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#5 引用回覆 回覆 發表時間:2003-09-15 16:03:31 IP:61.218.xxx.xxx 未訂閱

Transmitting a Specified Character

資料來源:不詳
  This example code opens the serial port for overlapped I/O, 
creates an event mask to monitor CTS and DSR signals, and then waits 
for an event to occur. The WaitCommEvent function should be executed 
as an overlapped operation so the other threads of the process 
cannot perform I/O operations during the wa    Unit1.cpp    // The following example code opens the serial port for transmitting a
// specified character ahead of any pending data in the output buffer.
// The TransmitCommChar function is executed.    //---------------------------------------------------------------------------    #include 
#pragma hdrstop    #include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"    // GLOBAL VARIABLES
HANDLE hComm = NULL;    TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------    void __fastcall TForm1::FormCreate(TObject *Sender)
{
 DCB dcbCommPort;      // OPEN THE COMM PORT.
  hComm = CreateFile("COM1",
                      GENERIC_READ | GENERIC_WRITE,
                      0,
                      0,
                      OPEN_EXISTING,
                      0,
                      0);      // IF THE PORT CANNOT BE OPENED, BAIL OUT.
  if(hComm == INVALID_HANDLE_VALUE) Application->Terminate();      // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
  // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
  // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
  // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
  // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
  dcbCommPort.DCBlength = sizeof(DCB);
  GetCommState(hComm, &dcbCommPort);
  BuildCommDCB("9600,N,8,1", &dcbCommPort);
  SetCommState(hComm, &dcbCommPort);
}
//---------------------------------------------------------------------------    void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
  // IF A PORT WAS OPENED, CLOSE IT
  if(hComm) {
     Sleep(250); // WAIT FOR THREAD TO FINISH
     CloseHandle(hComm);
  }
}
//---------------------------------------------------------------------------    void __fastcall TForm1::Memo1KeyPress(TObject *Sender, char &Key)
{
 // TRANSMITS ANYTHING TYPED INTO THE MEMO AREA.
  TransmitCommChar(hComm, Key);      // THIS PREVENTS TYPED TEXT FROM DISPLAYING GARBAGE ON THE SCREEN.
  // IF YOU ARE CONNECTED TO A DEVICE THAT ECHOES CHARACTERS, SET
  // Key = 0 WITHOUT THE OTHER STUFF.
  if(Key != 13 && (Key < ' ' || Key > 'z')) Key = 0;
}
//---------------------------------------------------------------------------         Unit1.h    //---------------------------------------------------------------------------    #ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
        TMemo *Memo1;
        void __fastcall FormCreate(TObject *Sender);
        void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
        void __fastcall Memo1KeyPress(TObject *Sender, char &Key);
private: // User declarations
public:  // User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
/*生活是一種藝術,用心生活才能享受生活*/
axsoft
版主


發表:681
回覆:1056
積分:969
註冊:2002-03-13

發送簡訊給我
#6 引用回覆 回覆 發表時間:2003-09-15 16:05:47 IP:61.218.xxx.xxx 未訂閱

Transmitting and Receiving Characters

資料來源:不詳
Unit1,cpp    //---------------------------------------------------------------------------
#include 
#pragma hdrstop    #include "Unit1.h"    // YOU MUST INCLUDE THE HEADER FOR UNIT2 (THE THREAD UNIT)
#include "Unit2.h"    // GLOBAL VARIABLES
HANDLE hComm = NULL;
TRead *ReadThread;
COMMTIMEOUTS ctmoNew = {0}, ctmoOld;    //---------------------------------------------------------------------------
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
 : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
  // TERMINATE THE THREAD.
  ReadThread->Terminate(); // TERMINATE THE THREAD      // IF A PORT WAS OPENED, CLOSE IT
 if(hComm) {
    Sleep(250); // WAIT FOR THREAD TO FINISH
    SetCommTimeouts(hComm, &ctmoOld);
   CloseHandle(hComm);
  }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Memo1KeyPress(TObject *Sender, char &Key)
{
 // TRANSMITS ANYTHING TYPED INTO THE MEMO AREA.      TransmitCommChar(hComm, Key);      // THIS PREVENTS TYPED TEXT FROM DISPLAYING GARBAGE ON THE SCREEN.
  // IF YOU ARE CONNECTED TO A DEVICE THAT ECHOES CHARACTERS, SET
  // Key = 0 WITHOUT THE OTHER STUFF.      if(Key != 13 && (Key < ' ' || Key > 'z')) Key = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
 DCB dcbCommPort;      // OPEN THE COMM PORT.      hComm = CreateFile("COM1",
                      GENERIC_READ | GENERIC_WRITE,
                      0,
                      0,
                      OPEN_EXISTING,
                      0,
                      0);      // IF THE PORT CANNOT BE OPENED, BAIL OUT.      if(hComm == INVALID_HANDLE_VALUE) Application->Terminate();      // SET THE COMM TIMEOUTS.      GetCommTimeouts(hComm,&ctmoOld);
  ctmoNew.ReadTotalTimeoutConstant = 100;
  ctmoNew.ReadTotalTimeoutMultiplier = 0;
  ctmoNew.WriteTotalTimeoutMultiplier = 0;
  ctmoNew.WriteTotalTimeoutConstant = 0;  
  SetCommTimeouts(hComm, &ctmoNew);      // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
  // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
  // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
  // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
  // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.      dcbCommPort.DCBlength = sizeof(DCB);
  GetCommState(hComm, &dcbCommPort);
  BuildCommDCB("9600,N,8,1", &dcbCommPort);
  SetCommState(hComm, &dcbCommPort);      // ACTIVATE THE THREAD. THE FALSE ARGUMENT SIMPLY MEANS IT HITS THE
  // GROUND RUNNING RATHER THAN SUSPENDED.      ReadThread = new TRead(false);
}
//---------------------------------------------------------------------------    Unit1.h
//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include 
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
 TMemo *Memo1;
 void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
 void __fastcall Memo1KeyPress(TObject *Sender, char &Key);
 void __fastcall FormCreate(TObject *Sender);
private: // User declarations
public:  // User declarations
 __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern TForm1 *Form1;
//---------------------------------------------------------------------------
#endif         Unit2.cpp    /---------------------------------------------------------------------------
#include 
#pragma hdrstop    // YOU MUST INCLUDE THE HEADER FOR UNIT1
#include "Unit1.h"
#include "Unit2.h"    extern HANDLE hComm;
char InBuff[100];    //---------------------------------------------------------------------------
//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall TRead::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------
__fastcall TRead::TRead(bool CreateSuspended)
 : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall TRead::DisplayIt(void)
{
  Form1->Memo1->SetSelTextBuf(InBuff);
}
//---------------------------------------------------------------------------
void __fastcall TRead::Execute()
{
 //---- Place thread code here ----      DWORD dwBytesRead;      // MAKE THE THREAD OBJECT AUTOMATICALLY DESTROYED WHEN THE THREAD
  // TERMINATES.      FreeOnTerminate = true;      while(1)
  {        // SEE IF THERE ARE ANY CHARACTERS IN THE INTERNAL RECEIVE BUFFER.
    // IF THERE ARE, READ THEM. OTHERWISE, WAIT FOR CHARACTERS
    // TO ARRIVE OR LEAVE IF THE THREAD IS TERMINATED.        if(Terminated) return;       ReadFile(hComm, InBuff, 50, &dwBytesRead, NULL);
    if(dwBytesRead)
    {
      InBuff[dwBytesRead] = 0; // NULL TERMINATE THE STRING
      Synchronize(DisplayIt);
    }      }    }
//---------------------------------------------------------------------------    Unit2.cpp    //---------------------------------------------------------------------------
#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include 
//---------------------------------------------------------------------------
class TRead : public TThread
{
private:
protected:
  void __fastcall DisplayIt(void);
  void __fastcall Execute();
public:
 __fastcall TRead(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif
 
/*生活是一種藝術,用心生活才能享受生活*/
系統時間:2024-04-18 15:28:26
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!