打开串口:
procedure tform1.OpenSerialPort;
var
  cc:TCommConfig;
  Temp:string;
begin
  Temp:='Com'+inttostr(RadioGroup1.ItemIndex+2);
  hSerialPort:=CreateFile(PChar(Temp),GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,0,0);
  if (hSerialPort=invalid_handle_value) then
  begin
      MessageBox(0,'打开串口失败','',MB_OK);
      Exit;
  end;
  GetCommState(hSerialPort,cc.dcb);
  cc.dcb.BaudRate:=CBR_9600;
  cc.dcb.ByteSize:=8;
  cc.dcb.Parity:=NOPARITY;
  cc.dcb.StopBits:=ONESTOPBIT;
  if not SetCommState(hSerialPort,cc.dcb) then
  begin
      ShowMessage('不能设置串口');
      CloseHandle(hSerialPort);
      Exit;
  end
  else
       ShowMessage('打开,并设置成功!');
end;写数据:procedure TForm1.Button3Click(Sender: TObject);
var
temp:string;
lw:LongWord;
IsWrite:Bool;
begin
if hSerialPort=0 then Exit;
temp:=Memo1.Text;
IsWrite:=WriteFile(hSerialPort,PChar(temp)^,Length(temp),lw,nil);
if IsWrite then showmessage('写数据成功')
else showmessage('写数据失败');
end;读取数据:procedure TForm1.Button4Click(Sender: TObject);
var
tempString:string;
inBuff:array[0..2047]of Char;
bytesRead,dwError:LongWord;
cs:TComStat;
IsRead:Bool;
InBuffLength:Integer;
begin
ClearCommError(hSerialPort,dwError,@cs);
InBuffLength:=SizeOf(inBuff);
showmessage(inttostr(InBuffLength));
if cs.cbInQue>SizeOf(inBuff)then
begin
    PurgeComm(hSerialPort,PURGE_RXCLEAR);
    Exit;
end;
IsRead:=ReadFile(hSerialPort,inBuff,cs.cbInQue,bytesRead,nil);
if IsRead then
begin
  tempString:=Copy(inBuff,1,cs.cbInQue);
  Memo2.Text:=tempString;
end;
end;我现在的问题是打开串口没有任何问题,写数据也成功,为什么我读取数据时候总是为空,我的串口上没有接设备,我想这没有影响吧!但是为什么总是为空?请各位指点!谢谢了!

解决方案 »

  1.   

    要测试很简单,下载个串口监听的软件,
    如:SUDT SerialTrace 等,看收发在哪一步出问题
      

  2.   

    监控写入数据成功!但是读取的数据的时候 (cs.cbInQue为什么一直等于0?)所以读取的数据就一直为空!但是我把cs.cbInQue这个变量用实际的数字代替后读取没有反应!程序好像终止了一样!真实郁闷死了!我的用法有问题吗?大家给看看
      

  3.   

    要求必须用api吗?
    建议用现成控件mscomm,或者spcomm,如果是做项目,不要把浪费时间。