如需更多一般性建議,請查看the System.IO.Ports namespace,該示例有更完整的示例。就我個人而言,我會調整他們在那裏設置您的通用端口設置,然後在調試模式下嘗試幾種不同的波特率(一些不好的,一個已知的好)。你會很快看到一個糟糕的配置給出了一個好的配置。我假設你有權在這裏測試設備?
值得注意的是,你不會看到打開端口的調用有任何問題(只是打開它只會測試你已經設置了端口支持的一些參數)。當您嘗試讀取/寫入設備時,您會看到問題,並且您需要對有效的波特率進行錯誤檢查。
[編輯]嘗試沿着這些路線的東西(注:我沒有與任何硬件測試這一點,但它至少編譯):
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
namespace SerialPortExperiments
{
class Program
{
public static void Main()
{
// Create a new SerialPort object with default settings.
SerialPort _serialPort = new SerialPort();
// Set some generic settings
SetBasicSettings(ref _serialPort);
// Try and find something valid
int baudRate = FindValidBaud(ref _serialPort);
if (baudRate > 0)
{
Console.WriteLine(String.Format("Found baudrate: {0}", baudRate));
}
else
{
Console.WriteLine("ERROR: Failed to identify baudrate");
}
}
public static void SetBasicSettings(ref SerialPort port)
{
port.PortName = "COM1";
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = 0;
port.Handshake = Handshake.None;
port.ReadTimeout = 500;
port.WriteTimeout = 500;
}
public static int FindValidBaud(ref SerialPort port)
{
bool buadrateIdentified = false;
// Pick some baudrates to try
List<int> baudrates = new List<int>();
baudrates.Add(9600);
baudrates.Add(19200);
// Try and open the port at each baud rate in turn, trying one write/read to verify success
for (int i = 0; i < baudrates.Count; i++)
{
// Pick a baud rate
port.BaudRate = baudrates[i];
// Try opening a connection and exchanging some data
port.Open();
buadrateIdentified = AttemptValidExchange(ref port);
port.Close();
if (buadrateIdentified)
{
return port.BaudRate;
}
}
return -1;
}
public static bool AttemptValidExchange(ref SerialPort port)
{
try
{
// Send a test command
port.Write("SOME_TEST_COMMAND");
// Check to see what the device responded with
const int expectedReturnLength = 1024;
byte[] buffer = new byte[expectedReturnLength];
port.Read(buffer, 0, expectedReturnLength);
if (buffer.ToString().Equals("EXPECTED_RETURN_VALUE"))
{
return true;
}
}
catch (TimeoutException) // NOTE: You'll probably need to catch other exceptions like parity errors here
{
}
return false;
}
}
}
嗨喬恩, 感謝您的。 是的,我有權訪問要測試的單元。 我會讓你知道結果。 謝謝,喬治。 – George 2009-09-07 13:50:35