1,317
社区成员
发帖
与我相关
我的任务
分享
//--打开和关闭串口--
void __fastcall TMainFrm::OpenComBtnClick(TObject *Sender)
{
//
int ret;
port=portComBox->ItemIndex+1;
if(openport!=1)
{
ret=sio_open(port);
ret=sio_ioctl(port,B9600,P_NONE|BIT_8|STOP_1);
if(ret!=SIO_OK)
{
ShowMessage("打开串口COM"+IntToStr(port)+"失败!");
Shape1->Brush->Color=clGray;
Shape2->Brush->Color=clGray;
}
else
{
Shape1->Brush->Color=clRed;
Shape2->Brush->Color=clGreen;
openport=1;
}
}
else
{
ShowMessage("串口COM"+IntToStr(port)+"已经打开,\n请先关闭再打开其他串口!");
}
}
//---------------------------------------------------------------------------
void __fastcall TMainFrm::CloseComBtnClick(TObject *Sender)
{
//
if(openport==1)
{
sio_close(port);
openport=0;
Shape1->Brush->Color=clGray;
}
}
//---------------------------------------------------------------------------
//发送数据
void __fastcall TMainFrm::SendCheckBtnClick(TObject *Sender)
{
// 5a 02 c6 9f 00 00 00
unsigned char buf[5];
int ret,error=0;
buf[0]=0x5a;
buf[1]=0x02;
buf[2]=0xc6;
buf[3]=0x9f;
buf[5]=0;
buf[6]=0;
buf[7]=0;
do
{
error++;
ret= sio_write(port,buf,8);
Sleep(20);
if(error>5)break;
}while(ret<8);
}
//----------------
reciever *recieverThread;
void __fastcall TMainFrm::FormCreate(TObject *Sender)
{
Shape1->Brush->Color=clGray;
recieverThread=new reciever(true);
recieverThread->Resume();
OpenComBtn->Click();
}
//--接收数据的线程---
//---------------------------------------------------------------------------
#include <Classes.hpp>
//---------------------------------------------------------------------------
class reciever : public TThread
{
private:
protected:
void __fastcall Execute();
public:
__fastcall reciever(bool CreateSuspended);
};
//---------------------------------------------------------------------------
void __fastcall TMyThread::Execute()
{
//inherited;
//struct date dt;
//struct time tm;
Byte xReady;
Byte xInPtr;
Byte xInData,xStart;
Byte xAdress;
// Byte Comm;
int xChk;
Byte xChk1,crcChk1;
Byte xChk2,crcChk2;
Byte xStatus;
// Byte echo;
int ii,jj,ret;
unsigned char xbuf[0x100];
unsigned char xindex,xcount;
unsigned short crchelp;
unsigned char Comm2;
int len,inlen;
len=0;
xReady=0;
xInPtr=0;
xChk=0;
long timeout=0;
long Check_Time=0;
while(!Stop)
{
try
{
//if(xInPtr==0)Sleep(2);
Sleep(1);
ret=sio_iqueue(comm_port);
if(ret>0)
{
xInData=sio_getch(comm_port);
}
}