2009-07-13 71 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

当串口打开时,设置串口的波特率和其他设置。 我想你正在读取默认值。