2017-01-08 150 views
0

CDCを使用するUSB​​デバイスと通信しようとしています。デバイス接続は、デバイスマネージャでシリアルポートとして認識されます。私はデバイスを参照して、シリアルポートを開くことができます。しかし、デバイスにメッセージを送信しようとすると、System.IO.IOExceptionがスローされます。"セマフォのタイムアウト期間が切れました。"私はいくつかのサードパーティのC#シリアルポートターミナルで同じ例外を取得します。私は、シリアルポートに他のデバイスと通信することができるよUSB-RS232コンバータと同じプログラムを使用してC#仮想シリアルポートに書き込むときに、セマフォのタイムアウト期間が満了しませんでした。

ないCDC

CDCデバイスメーカーは、彼らのモジュールは、Windows標準のCDCドライバを使用していることを言います問題は私の終わりです。私は間違って何をしていますか?

マイコード:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO.Ports; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private static readonly SerialPort _serial = new SerialPort(); 
     static void Main(string[] args) 
     { 
      var portList = SerialPort.GetPortNames().ToList(); 
      _serial.PortName = portList[0]; 
      _serial.BaudRate = 9600; 
      _serial.Handshake = Handshake.None; 
      _serial.Parity = Parity.None; 
      _serial.DataBits = 8; 
      _serial.StopBits = StopBits.Two; 
      _serial.ReadTimeout = 3000; 
      _serial.WriteTimeout = 3000; 
      _serial.DataReceived += ReceiveData; 
      _serial.Open(); 

      while (true) 
      { 
       string str = Console.ReadLine(); 

       if (str.Equals("exit")) 
        return; 
       SerialCmdSend(str); 
      } 

     } 

     public static void SerialCmdSend(string data) 
     { 
      if (_serial.IsOpen) 
      { 
       try 
       { 
        byte[] hexstring = Encoding.ASCII.GetBytes(data); 
        foreach (byte hexval in hexstring) 
        { 
         byte[] _hexval = { hexval }; 
    //The exception is thrown 3 sec. after the first call of the Write function 
         _serial.Write(_hexval, 0, 1); 
        } 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.Message); 
        throw; 
       } 
      } 
     } 


     private static void ReceiveData(object sender, SerialDataReceivedEventArgs e) 
     { 
      if (!_serial.IsOpen) 
      { 
       return; 
      } 
      try 
      { 
       while (_serial.BytesToRead > 0) 
       { 
        var b = _serial.ReadChar(); 
        //Handle read data 
       } 

      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
       throw; 
      } 
     } 
    } 
} 
+0

チェック:http://stackoverflow.com/questions/13999439/the-semaphore-timeout-period-has-expired –

+0

ありがとう。私は質問を掲示する前にこれを試しました。 –

答えて

0

DTR(データ端末レディ)が完全に接続を設定する前に有効になっている場合、お使いのUSBデバイスを確認している可能です。私はあなたのcomportを開く前に、あなたのC#プログラムに次のコードを追加することをお勧めします。ここ

_serial.DtrEnable = true; 
関連する問題