我制作了一个简单的C#程序,该程序与FTDI芯片(串行到USB的“ FT232RL”)通信。它应该运行24/7。该代码已正确编译并执行,但是在执行了几个小时/天后,UI随无响应的OS冻结(我必须关闭miniPC并重新启动它)。
应用程序仅每秒将一个字符串写入开发板。
我无法弄清楚问题,我使用的是FTDI的最新认证的Windows驱动程序,以及包含FTD2XX_NET.dll v1.0.14.0的NuGet FTDI软件包。
我也尝试了最新版本的FTD2XX_NET.dll v1.1.0.0,但没有结果。
using FTD2XX_NET;
using System;
using System.Threading.Tasks;
namespace app
{
class FtdiDev
{
FTDI.FT_STATUS ftStatus;
private FTDI device;
const UInt32 numBytesToWrite = 1;
const UInt32 numBystesToRead = 5;
public string state;
public FtdiDev()
{
device = new FTDI();
OpenDev();
//..
}
public string getDescription()
{
device.GetDescription(out string description);
return description;
}
public string getRxBytesBuffer()
{
uint rx = 0;
device.GetRxBytesAvailable(ref rx);
return rx.ToString();
}
public string getTxBytesBuffer()
{
uint tx = 0;
device.GetTxBytesWaiting(ref tx);
return tx.ToString();
}
private bool OpenDev()
{
uint numberOfDev = 0;
device.GetNumberOfDevices(ref numberOfDev);
try
{
if (numberOfDev > 0)
{
ftStatus = device.OpenByDescription("devName");
if (ftStatus != FTDI.FT_STATUS.FT_OK) return false;
ftStatus = device.SetBaudRate(115200);
if (ftStatus != FTDI.FT_STATUS.FT_OK) return false;
ftStatus = device.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
if (ftStatus != FTDI.FT_STATUS.FT_OK) return false;
ftStatus = device.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0);
if (ftStatus != FTDI.FT_STATUS.FT_OK) return false;
}
else
{
return false;
}
}
catch (Exception)
{
//
return false;
}
return true;
}
public void Write(string state)
{
if (device.IsOpen)
{
for (int i = 0; i < state.Length; i++)
{
WriteImplementation(state[i].ToString());
}
Task.Run(() => Read((uint)state.Length));
}
}
private void WriteImplementation(string state)
{
lock (device)
{
try
{
UInt32 numBytesWritten = 0;
ftStatus = device.Write(state, numBytesToWrite, ref numBytesWritten);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
throw new Exception(" write error FTDI exception ");
}
}
catch (Exception exc)
{
throw new Exception(exc.ToString());
}
}
}
public void Read(uint l)
{
lock (device)
{
try
{
UInt32 numBytesRead = 0;
ftStatus = device.Read(out string readData, numBystesToRead, ref numBytesRead);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
return;
}
else
state = readData;
}
catch (Exception exc)
{
throw new Exception(exc.ToString());
}
}
}
}
}
该程序非常简单,它是WinForm应用程序的一部分。
我假设此错误是GUI线程固有的问题,我对此项目提出了另一个问题: WinForm Application stop running and freeze windows
经过一些测试,我发现了问题所在,并将其留在这里。因为它使Windows崩溃,所以我认为它可能是驱动程序或硬件问题...