// start cond. + slave addr (rd) + read bytes (Cnt), no stop cond. public static bool ReadBytes(byte Addr, byte Cnt) { int BytesRead = 0, i; if (I2c.StartCond((byte)(Addr + 1)) == true) { bWrBuffer[0] = (byte)(0x80 + Cnt - 1); ComPort._serialPort.DiscardInBuffer(); ComPort._serialPort.Write(bWrBuffer, 0, 1); for (i = 0; i < 10; i++) { BytesRead += ComPort._serialPort.Read(bRdBuffer, BytesRead, Cnt); if (BytesRead == Cnt) { break; } } if (i == 10) { return(false); } else { return(true); } } else { return(false); } }
// start cond. + slave addr (wr) + write bytes (bTxCnt), no stop cond. public static bool WriteBytes(byte Addr, String TxbTxData) { byte[] Ack = new byte[1]; byte I, K; Byte bTxCnt; Byte bTxCnt1; bool ack; string Log = ""; if (TxbTxData == "") { return(true); } Ack[0] = 0xff; ComPort._serialPort.DiscardInBuffer(); ack = I2c.StartCond(Addr); if (ack == true) { bTxCnt1 = (Byte)TxbTxData.Length; bTxCnt = 0; K = 1; for (I = 0; I < bTxCnt1; I++) { if (TxbTxData[I] != ' ') { bTxCnt++; if ((Byte)TxbTxData[I] < 0x3a) { I2c.bWrBuffer[K] = (Byte)((TxbTxData[I++] - 0x30) * 16); if ((Byte)TxbTxData[I] < 0x3a) { I2c.bWrBuffer[K++] += (Byte)(TxbTxData[I] - 0x30); } else { I2c.bWrBuffer[K++] += (Byte)(TxbTxData[I] - 0x57); } } else { I2c.bWrBuffer[K] = (Byte)((TxbTxData[I++] - 0x57) * 16); if ((Byte)TxbTxData[I] < 0x3a) { I2c.bWrBuffer[K++] += (Byte)(TxbTxData[I] - 0x30); } else { I2c.bWrBuffer[K++] += (Byte)(TxbTxData[I] - 0x57); } } } } bWrBuffer[0] = (byte)(0xc0 + bTxCnt - 1); ComPort._serialPort.Write(bWrBuffer, 0, bTxCnt + 1); ComPort._serialPort.Read(Ack, 0, 1); if (Ack[0] == 0x31) // "1" bei Ack, "0" bei Nack { ack = true; } else { ack = false; } } if (LogOn == true) { fs = new FileStream("I2cDriver2.log", FileMode.Append); sw = new StreamWriter(fs); Log = "Wr: " + TxbTxData + " "; if (ack == true) { Log += "ACK"; } else { Log += "NACK"; } sw.WriteLine(Log); LogCounter++; sw.Close(); fs.Close(); } return(ack); }