也在学习中。。。你参考一下吧。<br>//打开串口<br>function TMainForm.Opencom:Boolean;<br>var<br> cc:TCOMMCONFIG;<br> Temp:string;<br>begin<br> Temp:='COM'+inttostr(rgcom.ItemIndex+1); // 选择所要打开的COM<br> hComm:=CreateFile(PChar(Temp), GENERIC_READ or GENERIC_WRITE,<br> 0, nil, OPEN_EXISTING, 0, 0); // 打开COM<br> if (hComm = INVALID_HANDLE_VALUE) then begin // 如果COM 未打开<br> MessageBox (0, '打开通信端口错误!!','',MB_OK);<br> Result:=False;<br> exit;<br> end;<br> ShowMessage('成功打开端口'+temp);<br><br> GetCommState(hComm,cc.dcb); // 得知目前COM 的状态<br> cc.dcb.BaudRate:=CBR_9600; // 设置波特率为9600<br> cc.dcb.ByteSize:=8; // 字节为 8 bit<br> cc.dcb.Parity:=EVENPARITY; // Parity 为 None<br> cc.dcb.StopBits:=TWOSTOPBITS; // 2 个Stop bit<br><br> if not SetCommState(hComm, cc.dcb) then begin// 设置COM 的状态<br> MessageBox (0, '通信端口设置错误!!!','',MB_OK);<br> CloseHandle(hComm);<br> Result:=False;<br> exit;<br> end;<br> Result:=True;<br>end;<br>//发命令<br>if EdtSend.Text='' then<br> exit;<br> if (hComm=0) then exit; //检查Handle值<br>// Temp:=EdiSend.Text ;//取得传送的字符串<br> //实际的传送动作<br>// WriteFile(hComm,PChar(Temp)^,Length(Temp), lrc, nil); // 送出数据<br> StrToBuffer(EdtSend.Text);<br> if not WriteFile(hComm,buffer,nn,nBytesRead,nil)then<br> begin<br> showmessage('write error');<br> exit;<br> end;<br> Sleep(sleepTime);<br> temp:='';<br> for i:=1 to nn do<br> begin<br> temp:=temp+copy(EdtSend.Text,i*2-1,2)+' ';<br> end;<br> reRes.Lines.Add (SHead+' '+temp);<br> ReceiveData;<br><br> EdtSend.SetFocus;<br> end<br> else<br> showmessage('端口没有打开!');<br>//收命令<br>// 接收COM 的数据接收COM 的数据,并将数据显示于Memo1 上<br>procedure TMainForm.ReceiveData;<br>var<br> inbuff: array[0..2047] of Byte;<br> nBytesRead, dwError:LongWORD ;<br> cs:TCOMSTAT;<br> sTmp:string;<br> i:integer;<br>begin<br> ClearCommError(hComm,dwError,@CS); //取得状态<br> // 数据是否大于我们所准备的Buffer<br> if cs.cbInQue > sizeof(inbuff) then begin<br> PurgeComm(hComm, PURGE_RXCLEAR); // 清除COM 数据<br> exit;<br> end;<br> fillchar(inbuff,sizeof(inbuff),0);<br> ReadFile(hComm, inbuff,cs.cbInQue,nBytesRead,nil); // 接收COM 的数据<br><br> //转移数据到变量中<br> sTmp:='';<br> for i:=1 to cs.cbInQue do //*******?<br> begin<br> sTmp:=sTmp+IntToHex(inbuff[i-1],2)+' ';<br> end;<br><br> reRes.Lines.Add (RHead+' '+sTmp); <br> <br><br>end;<br><br>