⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 com232.cpp

📁 实现串口数据读写
💻 CPP
字号:
使用c++builder寫的串口通訊源代碼,针对一种仪表所编
使用c++builder寫的串口通訊源代碼
--------------------------------------------------------------
本文為轉載文章
------------------------------------------------------------------
在网上很难找到C++串口通信的源码,因此我将刚做好的程序源码公开。当中如有bug,烦请告知,以便对学习者负责。此程序仅供串口初学者学习。 
我已经在windows 2000下编译测试通过。因为此程序针对厂内一种仪表所编,请按自己情况修改。但核心部分是不需修改的。 
界面右侧可以输入数字进行测试,注意最后请跟一个回车键,测试时将RS-232接口的第2,第3针连接,即可进行自发送,自接收。 
可以随便转载,但请保持完整 --- masa。
----------------------------------------------------------------------------------------------
程序中使用了windows API函数,unit2.h unit2.cpp为监视线程,没有窗口。 

######### 
//--------------unit.h----------- 

#ifndef UnitH 
#define UnitH 
//----------------------------------- 
#include <Classes.hpp> 
#include <Controls.hpp> 
#include <StdCtrls.hpp> 
#include <Forms.hpp> 
#include <ExtCtrls.hpp> 
#include <Graphics.hpp> 
#include <jpeg.hpp> 
#include <ComCtrls.hpp> 
#include <Grids.hpp> 
#include <CheckLst.hpp> 
//------------------------------------------------------------ 
class TForm1 : public TForm 
{ 
__published: // IDE 管理のコンポーネント 
TRadioGroup *RadioGroup1; 
TButton *Button3; 
TButton *Button4; 
TButton *Button5; 
TMemo *Memo2; 
TLabel *Label2; 
TImage *Image1; 
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 <vcl.h> 
#pragma hdrstop 

#include "Unit.h" 
#include "Unit2.h" 
#include <vector> 
#include <algorithm> 
#include <string> 

//--------------------------------------------------------------------------- 
#pragma package(smart_init) 
#pragma resource "*.dfm" 
TForm1 *Form1; 
HANDLE hCom; 
hComWatchThread *Read232; 

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::vector<double>vec; 
//--------------------------------------------------------------------------- 
__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; 
} 

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 !!!"); 
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, 
dat.c_str(), 
comstat.cbInQue, 
&BytesRead, 
&OverRead); 
if (!bResult && GetLastError()==ERROR_IO_PENDING) 
ShowMessage("pending"); 

char s; 
String str; 
for (unsigned int i=0;i<comstat.cbInQue;i++) 
{ 
s=*(dat.c_str()+i); 
str=str+s; 
} 
} 
Form1->Image1->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; 

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); 
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 <Classes.hpp> 
//--------------------------------------------------------------------------- 
class hComWatchThread : public TThread 
{ 
private: 
protected: 
void __fastcall WriteMemo(); 
void __fastcall Execute(); 
public: 
__fastcall hComWatchThread(bool CreateSuspended); 
}; 
//--------------------------------------------------------------------------- 
#endif 


########## 
//---------------------unit2.cpp--------------------- 

#include <vcl.h> 
#pragma hdrstop 

#include "Unit2.h" 
#include "Unit.h" 
#include <algorithim> 

#include <string> 
#include <vector> 
#pragma package(smart_init) 
//--------------------------------------------------------------------------- 


extern HANDLE hCom; 
extern OVERLAPPED OverRead,OverWrite; 
extern hComWatchThread *Read232; 
extern StopCom(); 
int x0=50 , y0=270; //axis of coordinate 

COMSTAT comstat; 
OVERLAPPED os; 
DWORD dwEvtMask=0; 

AnsiString dat; 
int test; 

int x=x0 ; 
bool CanPaint=false; 
std::vector<double> vec; 
double num; 

__fastcall hComWatchThread::hComWatchThread(bool CreateSuspended) 
: TThread(CreateSuspended) 
{ 
} 
//--------------------------------------------------------------------------- 


void __fastcall hComWatchThread::WriteMemo() 
{ 
int y=y0-3*num; 
Form1->Image1->Canvas->Pen->Color=clLime; 
Form1->Image1->Canvas->Pen->Width=1; 
Form1->Image1->Canvas->Pen->Style=psSolid; 

if (x==x0) 
Form1->Image1->Canvas->MoveTo(x,y); 
else 
Form1->Image1->Canvas->LineTo(x,y); 

if ( num>StrToInt(Form1->Edit1->Text) || num<StrToInt(Form1->Edit2->Text) ) 
{ Form1->Image1->Canvas->Pen->Color=clRed; 
Form1->Image1->Canvas->Brush->Color=clRed; 
Form1->Image1->Canvas->Ellipse(x-2,y-2,x+2,y+2); 
} 
x=x+1; 

if ((x-x0) > ((Form1->ComboBox3->ItemIndex)*5+20)*20 ) // when dcb.BaudRate=2400, 20次/秒 in my meter 
{ 
ShowMessage("測定完了!"); 
x=x0; 
CanPaint=false; 
StopCom(); 

std::sort(vec.begin(),vec.end()); 
Form1->LabeledEdit1->Text=*(vec.end()-10); 
Form1->LabeledEdit2->Text=*(vec.begin()+10); 
vec.erase(vec.begin(),vec.end() ); 
} 
} 


void __fastcall hComWatchThread::Execute() 
{ 
memset(&OverRead,0,sizeof(OVERLAPPED)); 
OverRead.hEvent=CreateEvent(NULL,true,true,NULL); 
if (OverRead.hEvent==NULL) Terminate(); 

if (!SetCommMask(hCom,EV_RXCHAR|EV_TXEMPTY)) Terminate(); 

while (!Terminated) 
{ 
WaitForSingleObject(OverRead.hEvent,INFINITE); 

bool WaitComEv; 
DWORD dwError; 
AnsiString Gotstr; 

DWORD ReadStat; 
DWORD BytesRead; 

WaitComEv=WaitCommEvent(hCom,&dwEvtMask,&OverRead); 
if (WaitComEv) 
ClearCommError(hCom,&dwError,&comstat); 
else if (!WaitComEv && GetLastError()==ERROR_IO_PENDING) 
{ 
ClearCommError(hCom,&dwError,&comstat); 

while (comstat.cbInQue>0 && dwEvtMask==EV_RXCHAR) 
{ 
AnsiString Getstr; 
char *pt=Getstr.c_str(); 
ReadStat=ReadFile(hCom,Getstr.c_str(),comstat.cbInQue,&BytesRead,&os); 

if (!ReadStat && GetLastError()==ERROR_IO_PENDING ) 
{ 
while (!GetOverlappedResult(hCom,&os,&BytesRead,true)) 
{ 
dwError=GetLastError(); 
if (dwError==ERROR_IO_INCOMPLETE) 
continue; 
else 
break; 
} 
} 

for (unsigned int i=0;i<comstat.cbInQue;i++) 
{ 
dat=dat+pt[i]; 
if (pt[i]==''\n'') 
{ 
AnsiString everyone; 
char *p=dat.c_str(); 
for (int j=0; j<dat.Length()-2; j++) 
everyone = everyone + p[j]; 
test++; 

if (test>1) num=StrToFloat(everyone); 
dat=NULL; 

if (num>20 ) CanPaint=true; 

if (CanPaint==true) 
{ vec.push_back(num); 
Synchronize(WriteMemo); 
} 
} 
} 

ClearCommError(hCom,&dwError,&comstat); 
dwEvtMask=0; 
} 

} 
} 
} 
//---------------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -