How can I send "unsigned long" over I2C from slave to master?
I know that "unsigned long" is four bytes and that I can define in Wire.write how many bytes I want to send and in Wire.requestFrom how many bytes I want to read.
But how do I chop 4 bytes long "unsigned long" in to bytes in slave and how do put the bytes back together in master to have "unsigned long"?
Thanks Budvar10, but I'm so newbie that this "The write() has overloaded version for unsigned long" doesn't open up to me.
Can you elaborate little bit?
// create a union to hold the data
union Buffer
{
long longNumber;
byte longBytes[4];
};
Buffer buffer; // create an instance of the union
buffer.longNumber = 0xaabbccdd; // assign a value to the long number
Now the longBytes array contains the pieces of the long number.
Send the longBytes array using the write(data, length) function.
Have an identical union at the receiving end. Read the bytes into the buffer.longBytes array. Now the buffer.longNumber variable holds the long number.
The same method works for float data type. Just replace the long longNumber with
float floatNumber.
In the union the two data types occupy the same addresses in memory. In the union you declare an unsigned long. A long is 4 bytes so, let's say, that the long is in memory locations 100, 101, 102 and 103. Those bytes all empty at first. Then in the union, you declare a byte array of 4 bytes. The memory address of byte[0] is 100, byte[1] is 101 and so on and they are also empty.
Now you write an unsigned long to buffer,longNumber, say 0xaabbccdd. Now buffer.byte[0] = aa, buffer.byte[1] = bb, and so on.
It works the other way, too. If you write the 4 bytes of an unsigned long to buffer.bytes[0] through buffer.bytes[3] you can then read the value of buffer.longNmuber.
The same project continues: Now I'm trying to read two integers over I2C. I ended up trying to do it with <I2C_Anything.h>, but it's not working. At the best I've been able to read the first integer.
What can be wrong with the code below?
Thanks,
Tipo
<I2C_Anything.h>
// Written by Nick Gammon
// May 2012
#include <Arduino.h>
#include <Wire.h>
template <typename T> unsigned int I2C_writeAnything (const T& value)
{
Wire.write((byte *) &value, sizeof (value));
return sizeof (value);
} // end of I2C_writeAnything
template <typename T> unsigned int I2C_readAnything(T& value)
{
byte * p = (byte*) &value;
unsigned int i;
for (i = 0; i < sizeof value; i++)
*p++ = Wire.read();
return i;
} // end of I2C_readAnything