2009-07-13 70 views
0

您好我需要找到串口的波特率和其他設置,在網絡上看,它看起來像我應該使用GetCommConfig,這將返回一個TCommConfig記錄與什麼我認爲是我需要的數據。問題是我wote的函數返回錯誤的值。查找在Delphi中的串口設置

下面的代碼看起來像是在工作,但波特率始終是1200,它在Windows設備管理器(和更改端口設置)中查找是錯誤的。

我曾嘗試調用它像這樣:

ComPort('com1'); 
ComPort('COM1'); 
ComPort('COM1:'); 
ComPort('COM4'); 
ComPort('COM9'); 

前4個是有效的,但回到1200和5日是無效的,返回0

function ComPort(l_port:String):TCommConfig; 
{Gets the comm port settings} 
    var 
    ComFile: THandle; 
    PortName: array[0..80] of Char; 
    size: cardinal; 
    CommConfig:TCommConfig; 
begin 
    FillChar(Result, SizeOf(TCommConfig), 0);//blank return value 

    try 
     StrPCopy(PortName,l_port); 
     ComFile := CreateFile(PortName,GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,0{ FILE_ATTRIBUTE_NORMAL},0); 
     try 
      if (ComFile <> INVALID_HANDLE_VALUE) then 
      begin 
       FillChar(CommConfig, SizeOf(TCommConfig), 0);//blank record 
       CommConfig.dwSize := sizeof(TCommConfig);//set size 
       //CommConfig.dcb.DCBlength := SizeOf(_dcb); 
       size := sizeof(TCommConfig); 

       if (GetCommConfig(ComFile,CommConfig,size)) then 
       begin 
        Result := CommConfig; 
       end; 
      end; 
     finally 
      CloseHandle(ComFile); 
     end; 
    except 
     Showmessage('Unable to open port ' + l_port); 
    end; 
end; 

單步調試代碼,第4總是打線結果:= CommConfig;,所以GetCommConfig重新調用一個有效的代碼,所以我必須錯過一些東西。

我已經tryed verious其他的東西,如設置DCB記錄的長度,但都具有相同的結果,作爲1200

波特有誰知道我要去的地方錯了嗎?

+0

您是否試過GetCommState? http://msdn.microsoft.com/en-us/library/aa363260%28VS.85%29.aspx – stukelly 2009-07-13 19:36:11

+0

是的相同的結果,據我所知,GetCommConfig內部使用GetCommState填充DCB記錄。 – Re0sless 2009-07-13 21:12:37

回答

3

原來我使用了錯誤的功能,我應該使用GetDefaultCommConfig而不是我使用的GetCommConfig

通過看看它是否正確,如果我錯了,請糾正我,GetDefaultCommConfig從窗口返回設置,GetCommConfig返回打開連接到端口的設置,writefile打開端口,因爲它認爲合適(忽略默認設置),這是1200波特率來自的地方。

如果這對將來的任何人有所幫助,下面是我提出的功能。

function ComPort(l_port:String):TCommConfig; 
{Gets the comm port settings (use '\\.\' for com 10..99) } 
    var 
    size: cardinal; 
    CommConfig:TCommConfig; 
begin 
    FillChar(Result, SizeOf(TCommConfig), 0); 

    //strip trailing : as it does not work with it 
    if (RightStr(l_port,1) = ':') then l_port := LeftStr(l_port,Length(l_port)-1); 

    try 
     FillChar(CommConfig, SizeOf(TCommConfig), 0); 
     CommConfig.dwSize := sizeof(TCommConfig); 

     size := sizeof(TCommConfig); 

     if (GetDefaultCommConfig(PChar(l_port),CommConfig,size)) then 
     begin 
      Result := CommConfig; 
     end 
     //if port is not found add unc path and check again 
     else if (GetDefaultCommConfig(PChar('\\.\' + l_port),CommConfig,size)) then 
     begin 
      Result := CommConfig; 
     end 
    except 
     Showmessage('Unable to open port ' + l_port); 
    end; 
end; 
3

當串口打開時,設置串口的波特率和其他設置。 我想你正在讀取默認值。