当FT260设备插入USB主机,系统会识别到2个HID设备(当DCNF0和DCNF1配置为0或者3时),此时设备0是I2C设备,而设备1才是UART设备。
FT260支持4种流控:
- 软件流控(默认),只需要链接RXD,TXD,GND
- 通过CTS和RTS的硬件流控
- 通过DTR和DSR的硬件流控
- 没有流控
1. 设置UART的参数(例如波特率,校验位,停止位等等)
byte[] buf = new byte[64];
buf[0] = 0xa1;
buf[1] = 0x41;
buf[2] = getUartFlowctrlType();
UInt32 baud = getUartBaudrate();
buf[3] = (byte)(baud & 0xff);
buf[4] = (byte)((baud >> 8) & 0xff);
buf[5] = (byte)((baud >> 16) & 0xff);
buf[6] = (byte)((baud >> 24) & 0xff);
buf[7] = getUartDatabit();
buf[8] = getUartParity();
buf[9] = getUartStopbit();
buf[10] = getUartBreaking();
hid.setFeature(buf, 64);
其中波特率,数据位,校验位,停止位,是否断开可以参考AN394文档中的说明。
2. 发送数据
发送UART数据使用的是Interrupt Out,即hid类的sendbuf接口函数。其格式如下:
偏移 | 含义 | 说明 |
Byte 0 | Report ID | 0xF0-0xFE, 根据发送的实际数据长度选择,4字节对齐,0xF0表示4字节数据(小于4字节也选择4字节),0xFE表示60字节数据 |
Byte 1 | Length | 后面数据的实际长度 |
Byte 2到Byte61 | Data | 数据 |
private void uartSend(byte[] sendHex)
{
if (sendHex.Length == 0)
return;
byte maxLen;
int length = sendHex.Length;
int index = 0;
while (length > 0)
{
byte[] buf = new byte[hid.OutputReportLength];
maxLen = (byte)(((sendHex.Length - index) > (hid.OutputReportLength - 2)) ?
(hid.OutputReportLength - 2) : (sendHex.Length - index));
buf[0] = (byte)(0xF0 + ((maxLen + 2) >> 2));
buf[1] = maxLen;
for (int i = 0; i < maxLen; i++)
{
buf[i + 2] = sendHex[index + i];
}
hid.SendBuf(buf);
index += maxLen;
length -= maxLen;
}
}
3. 接收数据
接收的数据直接用类Hid的回调函数获取数据。即定义
hid.DataReceived = DataReceived;
private Queue<byte> uartQueue = new Queue<byte>();
public void uartDataReceived(object sender, byte[] e)
{
lock (uartLocker)
{
for (int i = 0; i < e.Length; i++)
{
uartQueue.Enqueue(e[i]);
}
}
}
其中参数e是接收到的数据。
短接RXD和TXD测试:
注:接收数据需要特别注意,每次从hid.DataReceived读回来的数据只有一个字节,程序界面需要特别注意时间,如果没有及时读取该数据可能会导致数据丢失和错误。可以采用Queue先保留数据,后面再处理显示或者其他。另外,需要增加一个lock防止数据错误。