//打开串口
bool OpenPort(int Port)
{
int ret;
ret = sio_open(Port);
if (ret != SIO_OK) return(false);
sio_DTR(Port,0); //关闭DTR状态
sio_RTS(Port,0); //关闭RTS状态
sio_flush(Port,2); //清空输入输出缓冲区 0是输入 1是输出 2是输入输出
ret = sio_ioctl(Port,B9600,P_NONE|BIT_8|STOP_1);
if (ret != SIO_OK)
{
sio_close(Port);
return(false);
}
else
return(true);
}
//------------------------------------------------------------------------------
//关闭串口
bool ClosePort(int Port)
{
sio_close(Port);
return(true); //正常返回
}
//------------------------------------------------------------------------------
//以下为输出函数
//下载数据
bool MachineOnline(int Port,int MNumber)
{
unsigned char SendData[3];
unsigned char ReceiveData[3];
int CRC;
int ret;
SendData[0] = 0xF0;
SendData[1] = MNumber;
SendData[2] = 0xFE;
CRC = (SendData[0] + SendData[1]) % 256;
SendData[3] = CRC;
if(!OpenPort(Port)) return(false);
sio_write(Port,SendData,sizeof(SendData)+1);
Sleep(100);
ret = sio_iqueue(Port);
if(ret==4)
{
sio_read(Port,ReceiveData,4);
for(int i=0;i<4;i++)
{
if(ReceiveData[i] != SendData[i])
{
ClosePort(Port);
return(false);
}
}
}
return(ClosePort(Port));
}
//------------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if(MachineOnline(1,0))
ShowMessage("在线!");
else
ShowMessage("不在线!");
}
//---------------------------------------------------------------------------
程序如上,错误如图