【发布时间】:2017-01-08 13:07:40
【问题描述】:
我正在尝试与使用 CDC 的 USB 设备通信。设备连接在设备管理器中显示为串行端口。我看到了设备并且能够打开串口。但是,当我尝试向设备发送消息时,抛出 System.IO.IOException 说:“信号量超时期限已过期。” 我得到了同样的异常与多个第三方C#串口终端。
使用与 USB-RS232 转换器相同的程序,我能够与具有串行端口的另一个设备通信(不是 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;
}
}
}
}
【问题讨论】:
-
谢谢。我在发布问题之前尝试过这个。
标签: c# serial-port usb cdc