Hi. I want to know that how can I transfer an "int" variable by I2C. Be cause by i2c we can transfer just a byte of data.
thanks guys.
Send the high and low byte separately. The details depend on the device.
thanks. can you send me a sample program?
Many could, very few will.
int x = 5124;
char lowbyte = x;
char highbyte = x/256;
Think that should work?
int x = 5124;
byte lowbyte = x & 0xFF;
byte highbyte = x >> 8;
Your version would probably work, but I would prefer mine
(the modulo 256 operation is more obvious and the shift is faster than the division).
And defining a 'char xxxbyte' is not very clever in respect to documentation.
Whandall:
int x = 5124;
byte lowbyte = x & 0xFF;
byte highbyte = x >> 8;
Your version would probably work, but I would prefer mine (the modulo 256 operation is more obvious and the shift is faster than the division). And defining a '**char** xxx**byte**' is not very clever in respect to documentation.
Very true on the char vs byte declare.
I have never had to use the << operator myself so off to look that up!
Thank you very much guys . I will test all of this samples.
Sorry. I have 2 another question.
- How can I send "signed" variable in this method?
- How can I send a 2 bytes "int" variable (from pro mini) to another board that has 4 bytes "int" variable ( for example Due)?
soleimani_m:
thanks. can you send me a sample program?
Pick your Poision:
#include <Wire.h>
void setup(){
Wire.begin();
int X;
uint8_t* bp=(uint8_t*)&X;
Wire.beginTransmission(25);
Wire.write(*bp++);
Wire.write(*bp);
Wire.endTransmission();
bp=(uint8_t*)&X;
Wire.beginTransmission(25);
Wire.write((char*)*bp,2);
Wire.endTransmission();
Wire.beginTransmission(25);
Wire.write(highByte(X));
Wire.write(lowByte(X));
Wire.endTransmission();
Wire.beginTransmission(25);
Wire.write((uint8_t)X&0xFF);
Wire.write((uint8_t)(X>>8)&0xFF);
Wire.endTransmission();
}
void loop(){}
Chuck.
soleimani_m:
How can I send a 2 bytes "int" variable (from pro mini) to another board that has 4 bytes "int" variable ( for example Due)?
There will be no magic extension, 2 bytes sent will result in 2 bytes received.
You could use 'short int' on the Due side, that should give you a compatible type,
I'm not aware of the endianness of the Due, so in-place reception could create errors,
but this is something to be aware of with any non-1-byte value.