使用c++builder的串口通讯源代码
Page 1 of 12
中国亿万电器网 >> 亿万论坛 >> 其他技术交流区 >> 【其它工控技术】 >> 使用c++builder的串口通讯源代码
使用c++builder的串口通讯源代码 宋伟丽,2004-02-18 09:28:00
在网上很难找到C++串口通信的源码,因此我将刚做好的程序源码公开。当中如有bug,烦请告知,以
便对学习者负责。此程序仅供串口初学者学习。
我已经在windows 2000下编译测试通过。因为此程序针对厂内一种仪表所编,请按自己情况修改。但
核心部分是不需修改的。
界面右侧可以输入数字进行测试,注意最后请跟一个回车键,测试时将RS-232接口的第2,第3针连
接,即可进行自发送,自接收。
可以随便转载,但请保持完整 --- masa。
程序中使用了windows API函数,unit2.h unit2.cpp为监视线程,没有窗口。
#########
//--------------unit.h-----------
#ifndef UnitH
#define UnitH
//-----------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE 管理のコンポーネント
TRadioGroup *RadioGroup1;
TButton *Button3;
TButton *Button4;
TButton *Button5;
TMemo *Memo2;
TLabel *Label2;
TImage *Image1;
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 2 of 12
TGroupBox *GroupBox1;
TEdit *Edit1;
TEdit *Edit2;
TLabel *Label3;
TLabel *Label4;
TLabel *Label12;
TComboBox *ComboBox3;
TLabel *Label7;
TLabeledEdit *LabeledEdit1;
TLabeledEdit *LabeledEdit2;
void __fastcall Button4Click(TObject *Sender);
void __fastcall Button3Click(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
void __fastcall Button5Click(TObject *Sender);
private:
public:
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
##########
//-------------------unit.cpp---------------
#include
#pragma hdrstop
#include "Unit.h"
#include "Unit2.h"
#include
#include
#include
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
HANDLE hCom;
hComWatchThread *Read232;
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 3 of 12
DCB dcb;
OVERLAPPED OverWrite;
OVERLAPPED OverRead;
String comname;
extern int x0,y0;
extern int x,y,test;
extern bool CanPaint;
extern double num;
extern std::vectorvec;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//------ Create COM ----------------------------------------------------------
bool CreateCom(String comname)
{
if (hCom==INVALID_HANDLE_value)
{
ShowMessage("You are using thd HANDLE hCom ,It will be reopen");
CloseHandle(hCom);
}
hCom=CreateFile( comname.c_str(),
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (hCom==INVALID_HANDLE_value)
{
ShowMessage("Can not open the port !");
CloseHandle(hCom);
hCom=0;
Form1->Caption=comname+" 通信失敗!別のポートを使用して下さい!";
return false;
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 4 of 12
}
if (!SetCommMask(hCom,EV_RXCHAR)) ShowMessage("SetCommMask failed");
if (!SetupComm(hCom,1024,1024)) ShowMessage("SetupComm failed");
PurgeComm(hCom,PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
GetCommState(hCom,&dcb);
dcb.BaudRate=2400;
dcb.fParity=0;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
dcb.ByteSize=8;
dcb.fNull=FALSE;
SetCommState(hCom,&dcb);
ShowMessage(IntToStr(dcb.BaudRate) + " fParitu :" +
IntToStr(dcb.fParity) + " Parity :" +
IntToStr(dcb.Parity) + " ByteSize :" +
IntToStr(dcb.ByteSize) + " StopBits :" +
dcb.StopBits + " " + comname + " Open successed");
Form1->Caption=comname+" 通信成功!";
Form1->RadioGroup1->Enabled=false;
Form1->GroupBox1->Enabled=false;
Form1->Button3->Enabled=false;
Form1->Button4->Enabled=true;
Read232=new hComWatchThread(false); // (false/true) (run/not run )WatchThread when begin
Read232->FreeOnTerminate=true;
return true;
}
bool StopCom()
{
if (hCom) //Stop COM
{
if (CloseHandle(hCom))
{ ShowMessage("CloseHandle(hCom) successed");
Read232->Terminate();
}
else
{ ShowMessage("Can not close the com !!!");
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 5 of 12
return false;
}
Form1->RadioGroup1->Enabled=true;
Form1->Caption="通信停止中";
}
else ShowMessage("The com has been stoped !!");
hCom=0;
Form1->Button3->Enabled=true;
Form1->Button4->Enabled=false;
Form1->GroupBox1->Enabled=true;
return true;
}
//------333 Begin Read data From COM 3333333-------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
if (RadioGroup1->ItemIndex==0) comname="COM1";
if (RadioGroup1->ItemIndex==1) comname="COM2";
if (RadioGroup1->ItemIndex==2) comname="COM3";
if (RadioGroup1->ItemIndex==3) comname="COM4";
if (CreateCom(comname)) //ShowMessage(Form1->ComboBox1->Items->operator [](0) );
{
x=x0;
test=0;
CanPaint=false;
num=0;
COMSTAT comstat;
DWORD dwError=0;
String dat;
DWORD bResult;
DWORD BytesRead;
OVERLAPPED OverRead;
OverRead.hEvent=CreateEvent(NULL,true,false,NULL);
ClearCommError(hCom,&dwError,&comstat) ;
if (hCom!=INVALID_HANDLE_value)
{
bResult=ReadFile(hCom,
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 6 of 12
dat.c_str(),
comstat.cbInQue,
&BytesRead,
&OverRead);
if (!bResult && GetLastError()==ERROR_IO_PENDING)
ShowMessage("pending");
char s;
String str;
for (unsigned int i=0;iImage1->Picture=0 ; //LoadFromFile("a.bmp");
Form1->Image1->Canvas->Pen->Color=clBlack;
Form1->Image1->Canvas->Pen->Width=1;
Form1->Image1->Canvas->MoveTo(x0,300) ;
Form1->Image1->Canvas->LineTo(x0,30); // Y axis
Form1->Image1->Canvas->Pen->Width=2;
Form1->Image1->Canvas->LineTo(x0,10); // Y Arrow
Form1->Image1->Canvas->Pen->Width=1;
Form1->Image1->Canvas->MoveTo(20,y0) ;
Form1->Image1->Canvas->LineTo(750,y0); // X axis
Form1->Image1->Canvas->Pen->Width=2;
Form1->Image1->Canvas->LineTo(770,y0); // X Arrow
Form1->Image1->Canvas->Pen->Width=1;
Form1->Image1->Canvas->Pen->Style=psDot;
int line=y0;
for (int cou=0; cou<7; cou++)
{
line=line-30;
if (cou==0 || cou>=5)
Form1->Image1->Canvas->Pen->Color=clRed;
else
Form1->Image1->Canvas->Pen->Color=clGreen;
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 7 of 12
Form1->Image1->Canvas->MoveTo(x0,line) ;
Form1->Image1->Canvas->LineTo(750,line);
}
}
}
//--------444 Write data to COM 444444---------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
BOOL WriteState;
AnsiString str=Form1->Memo2->Text;
unsigned long Written ;
DWORD dwError;
unsigned long StrLen=str.Length();
WriteState=WriteFile(hCom,str.c_str(),StrLen,&Written,&OverWrite);
if (!WriteState && GetLastError()==ERROR_IO_PENDING )
{
while (!GetOverlappedResult(hCom,&OverWrite,&StrLen,false))
{ dwError=GetLastError();
if (dwError==ERROR_IO_INCOMPLETE)
continue;
else
{ ShowMessage("Can not continue GetOverlappedResult()");
break;
}
}
}
else ShowMessage("データ転送失敗!通信状態を確認して下さい!");
}
//-------555 Memo Clear 5555--------------------------------------------------
void __fastcall TForm1::Button5Click(TObject *Sender)
{
StopCom();
if (vec.size()>100)
{
std::sort(vec.begin(),vec.end());
LabeledEdit1->Text=*(vec.end()-10);
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14
使用c++builder的串口通讯源代码
Page 8 of 12
Form1->LabeledEdit2->Text=*(vec.begin()+10);
}
vec.erase( vec.begin(),vec.end() );
}
//-------- Stop COM and Watch Thread -----------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
Form1->Button3->Enabled=true;
Form1->Button4->Enabled=false;
}
###########
//-----------------unit2.h------------------
#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include
//---------------------------------------------------------------------------
class hComWatchThread : public TThread
{
private:
protected:
void __fastcall WriteMemo();
void __fastcall Execute();
public:
__fastcall hComWatchThread(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif
##########
//---------------------unit2.cpp---------------------
#include
#pragma hdrstop
#include "Unit2.h"
#include "Unit.h"
#include
#include
http://bbs.e10000.cn/MINI/Default.asp?310-103-0-0-0-0-0-a-.htm
2012-11-14