I am trying to send an integer (10000) over I2C between two arduino Uno's. However, the leading zeros are being removed, resulting in an incorrect reconstruction. is there a way to keep the leading zeros?
MASTER
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this
// Created 29 March 2006
// This example code is in the public domain.
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
}
int data = 10000;
byte High = highByte(data);
byte Low = lowByte(data);
void loop() {
Wire.beginTransmission(8); // transmit to device #8
Wire.write(High); // sends five bytes
Wire.write(Low); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(500);
}
SLAVE
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this
// Created 29 March 2006
// This example code is in the public domain.
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output
}
void loop() {
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
while (1 < Wire.available()) { // loop through all but the last
byte High = Wire.read(); // receive byte as a character
Serial.println(High, BIN); // print the character
byte Low = Wire.read(); // receive byte as an integer
Serial.println(Low, BIN); // print the integer
int data_rec = word(High>>8, Low);
Serial.println(data_rec, BIN);
Serial.println(data_rec);
}
}
Thanks GolamMostafa. That looks perfect. The only reason i was using Serial.print was to debug and it was confusing me, but this should help in the future. Thanks!