Hi Guys,
I succeeded in writing and reading data back from the DS1307 NV SRAM. The way I did was like:
// Write Data
public void SaveData(int eled, int elen, int gas, int wat)
{
xaction = new I2CDevice.I2CWriteTransaction[1];
byte[] sb = new byte[17] { 0x08,
WriteInt32(eled)[0],
WriteInt32(eled)[1],
WriteInt32(eled)[2],
WriteInt32(eled)[3],
WriteInt32(elen)[0],
WriteInt32(elen)[1],
WriteInt32(elen)[2],
WriteInt32(elen)[3],
WriteInt32(gas)[0],
WriteInt32(gas)[1],
WriteInt32(gas)[2],
WriteInt32(gas)[3],
WriteInt32(wat)[0],
WriteInt32(wat)[1],
WriteInt32(wat)[2],
WriteInt32(wat)[3]
};
xaction[0] = I2CDevice.CreateWriteTransaction(sb);
if (I2C.Execute(xaction, 1000) == 0)
{
new Exception("Failed to send I2C data");
}
}
// Read Data
public int[] ReadData()
{
xaction = new I2CDevice.I2CTransaction[2];
xaction[0] = I2CDevice.CreateWriteTransaction(new byte[] { 0x08 });
byte[] RetCounters = new byte[16];
xaction[1] = I2CDevice.CreateReadTransaction(RetCounters);
if (I2C.Execute(xaction, 1000) == 0)
{
new Exception("Failed to send I2C data");
}
byte[] eled = new byte[4] {RetCounters[0], RetCounters[1], RetCounters[2], RetCounters[3]};
byte[] elen = new byte[4] { RetCounters[4], RetCounters[5], RetCounters[6], RetCounters[7] };
byte[] gas = new byte[4] { RetCounters[8], RetCounters[9], RetCounters[10], RetCounters[11] };
byte[] wat = new byte[4] { RetCounters[12], RetCounters[13], RetCounters[14], RetCounters[15] };
int[] vals = new int[4] { ReadInt32(eled, 0), ReadInt32(elen, 0), ReadInt32(gas, 0), ReadInt32(wat, 0) };
return vals;
}
// helpers
private static byte[] WriteInt32(int value)
{
byte[] result = new byte[4];
result[0] = (byte)((value & 0xFF000000) >> 24);
result[1] = (byte)((value & 0x00FF0000) >> 16);
result[2] = (byte)((value & 0x0000FF00) >> 8);
result[3] = (byte)((value & 0x000000FF));
return result;
}
public static int ReadInt32(byte[] buf, int offset)
{
return (buf[offset + 0] << 24) + (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + (buf[offset + 3]);
}
Now seen that this is somehow limited, I’m looking for a more general approach.
In the code above I’m only using 16 bytes out of a total available of 56 bytes. I would like to use the remaining 40 bytes (in the future) and therefor it would be nice if I can prepare my code now (instead of modifying it later). One nice issue that I’ve read in the DS1307 datasheet is:
Once we can come up with a nice solution I will update the ds1307 driver on code.tinyclr.com so everyone can benefit from this.
One solution I have in mind is working with an address table, so we know what data goes where:
// Value1 to Value4 are in this case Int32 (4bytes)
public enum ValueAddress
{
Value1 = 0x08,
Value2 = 0x12,
Value3 = 0x16,
Value4 = 0x20
}
Are there other solutions?
Greetings,
Eric