IIC的2个pin都是开漏输出,所以外部需要接2个上拉电阻。
1. 设置IIC的频率
IIC的频率支持范围为60KHz-3.4MHz,通过setFeature写入参数,其中freq是以KHz为单位的。
buf[0] = 0xa1;
buf[1] = 0x22;
buf[2] = (byte)(freq & 0xff);
buf[3] = (byte)((freq >> 8) & 0xff);
hid.setFeature(buf, 64);
读取设置的频率判断是否设置成功
buf[0] = 0xC0;
hid.getFeature(buf, 64);
int freqSet = 0;
freqSet = (int)buf[2] | (int)buf[3] << 8;
if(freqSet == freq)
{
Console.WriteLine("Initial frequece OK!");
btI2COpen.Text = "Close I2C";
}
else
{
Console.WriteLine("Setting frequece is " + freqSet);
Console.WriteLine("I2C Status is " + buf[1]);
}
2. IIC写请求
与UART写类似,只是命令字变成了0xDx
偏移 | 含义 | 说明 |
Byte 0 | Report ID | 0xD0-0xDE, 根据发送的实际数据长度选择,4字节对齐,0xF0表示4字节数据(小于4字节也选择4字节),0xFE表示60字节数据 |
Byte 1 | SlaveAddr | IIC从地址(7位) |
Byte 2 | Flag | IIC通信的条件标志: 0x00 – NONE 0x02 – START 0x03 – Repeat Start 0x04 – STOP 0x06 – START_AND_STOP |
Byte 3 | Length | 有效数据的长度 |
Byte 4 - 63 | Data | 数据 |
其中Flag有低3位的组合,例如如果要实现Repeat Start + Stop的数据格式,则Flag选择0x03 | 0x04 = 0x07.
private bool ft260Write(byte slaveAddr, byte option, byte[] dat, byte len)
{
byte wrLen = len;
if (len == 0 && len > hid.OutputReportLength - 4)
return false;
byte[] buf = new byte[hid.OutputReportLength];
buf[0] = 0xD0;
buf[1] = slaveAddr;
buf[2] = option;
buf[3] = (byte)len;
wrLen = (byte)(wrLen + 4);
// update report ID
buf[0] = (byte)(buf[0] + (wrLen >> 2));
Array.Copy(dat, 0, buf, 4, len);
return hid.SendBuf(buf);
}
3. IIC读
偏移 | 含义 | 说明 |
Byte 0 | Report ID | 0xC0 |
Byte 1 | SlaveAddr | IIC从地址(7位) |
Byte 2 | Flag | IIC通信的条件标志: 0x00 – NONE 0x02 – START 0x03 – Repeat Start 0x04 – STOP 0x06 – START_AND_STOP |
Byte 3 - 4 | Length | 读取数据的长度 |
private bool ft260Read(byte slaveAddr, byte option, UInt32 len)
{
UInt32 rdLen = len;
if (len == 0)
return false;
byte[] buf = new byte[64];
buf[0] = 0xC2;
buf[1] = slaveAddr;
buf[2] = option;
buf[3] = (byte)(len & 0x00ff);
buf[4] = (byte)((len & 0xff00) >> 8);
if (hid.SendBuf(buf) == false)
return false;
return true;
}
4. 写数据到AT24C02
4.1 写入AT24C02的Memory地址,Flag选择0x02,即START
buf[0] = (byte)(addr & 0xff);
ft260Write(slaveAddr, 0x02, buf, 1); //0x02: START
4.2 写入数据,因为每次最多写入60字节,所以只有最后一笔数据需要带STOP。
while(len > 0)
{
byte count = (byte)((len > (hid.OutputReportLength - 4)) ?
(byte)(hid.OutputReportLength - 4) : len);
Array.Copy(dat, offset, buf, 0, count);
if(count == len)//last
{
ft260Write(slaveAddr, 0x04, buf, count); //0x04 : STOP
}
else
{
ft260Write(slaveAddr, 0x00, buf, count); //0x00 : NONE
}
offset += count;
len -= count;
}
5. 从AT24C02读数据
5.1 写入AT24C02的Memory地址,Flag选择0x02,即START
buf[0] = (byte)(addr & 0xff);
ft260Write(slaveAddr, 0x02, buf, 1); //0x02: START
5.2 写入读请求命令
ft260Read(slaveAddr, 0x03 | 0x04, len);
5.3 同UART读一样,从类Hid的回调函数获取数据
读写AT24C02的结果: