jason:你好
我不熟BC Build,在此只能给你DELPHI程序,基本用API完成,该程序我用过
没有问题,以供参考
连线方式为:2-3,3-2,5-5,'*'为主要的API函数)
发送:
Var
CommTimeOuts:TCommTimeOuts;
FDCB:TDCB;
SendBuff:Array [0..50] of Char;
OS:TOverlapped;
WriteSize
Word;
Begin
* ComHandle:=CreateFile('COM2',GENERIC_READ or GENERIC_WRITE,
0,nil,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
* SetupComm(ComHandle,512,512);
* GetCommTimeOuts(ComHandle,CommTimeOuts);
CommTimeouts.ReadIntervalTimeout:=250;
CommTimeouts.ReadTotalTimeoutMultiplier:=0;
CommTimeouts.ReadTotalTimeoutConstant:=0;
CommTimeouts.WriteTotalTimeoutMultiplier:=0;
CommTimeouts.WriteTotalTimeoutConstant:=0;
* SetCommTimeOuts(ComHandle,CommTimeOuts);
* GetCommState(ComHandle,FDCB);
FDCB.BaudRate:=CBR_9600;
FDCB.Parity:=ODDPARITY;
FDCB.Stopbits:=ONESTOPBIT;
FDCB.Bytesize:=8;
* SetCommState(ComHandle,FDCB);
StrPCopy(SendBuff,'this is a test');
FillChar(Os,Sizeof(OS),0);
WriteFile(ComHandle,SendBuff,StrLen(SendBuff),WriteSize,@OS);
CloseHandle(ComHandle);
End;
接收:
Var
CommTimeOuts:TCommTimeOuts;
FDCB:TDCB;
SendBuff:Array [0..50] of Char;
OS:TOverlapped;
WriteSize
Word;
PState:TComStat;
DelayTime
Word;
Begin
* ComHandle:=CreateFile('COM2',GENERIC_READ or GENERIC_WRITE,
0,nil,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
* SetupComm(ComHandle,512,512);
* GetCommTimeOuts(ComHandle,CommTimeOuts);
CommTimeouts.ReadIntervalTimeout:=250;
CommTimeouts.ReadTotalTimeoutMultiplier:=0;
CommTimeouts.ReadTotalTimeoutConstant:=0;
CommTimeouts.WriteTotalTimeoutMultiplier:=0;
CommTimeouts.WriteTotalTimeoutConstant:=0;
* SetCommTimeOuts(ComHandle,CommTimeOuts);
* GetCommState(ComHandle,FDCB);
FDCB.BaudRate:=CBR_9600;
FDCB.Parity:=ODDPARITY;
FDCB.Stopbits:=ONESTOPBIT;
FDCB.Bytesize:=8;
* SetCommState(ComHandle,FDCB);
DelayTime:=timeGetTime+12000; //timeGetTime 在MMSystem单元中
While DelayTime>timeGetTime Do
Begin
ClearCommError(ComHandle,WriteSize,@PState);
End;
if PState.cbInQue>0 Then Break;
Begin
FillChar(Os,Sizeof(OS),0);
//此时SendBuff为接收到的数据
ReadFile(ComHandle,SendBuff,PState.cbInQue,WriteSize,@OS);
//下面两句只是作为调试用,在接收窗口标题拦显示接收的数据
SendBuff[WriteSize]:=#0;
Self.Caption:=StrPas(SendBuff);
End;
CloseHandle(ComHandle);
End;