Bachalo
Bachalo

Reputation: 7219

Sending numbers greater than 256 over serial connection

A partial solution to my problem is given here http://forum.arduino.cc/index.php?topic=97846.0

But using the Wire class in my arduino code, and don't know how to modify.

here is my complete arduino code. Can any arduino experts chime in?

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        number = Wire.read();
        Serial.print("data received: ");
        Serial.println(number);

        if (number == 1){

            if (state == 0){
                digitalWrite(13, HIGH); // set the LED on
                state = 1;
            }
            else{
                digitalWrite(13, LOW); // set the LED off
                state = 0;
            }
         }
     }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}

Upvotes: 1

Views: 6102

Answers (1)

ladislas
ladislas

Reputation: 3070

I assume you are using an Arduino Uno.

The Arduino Uno stores an int as a 16-bit or 2 bytes value.

Serial.write() only write a byte so you need to tweak it a little.

You could use this kind of function:

void writeInt(unsigned int value){
    Wire.write(lowByte(value));
    Wire.write(highByte(value));
}

You first write the lowByte() and then the highByte.

Note that you then on the slave you'll need to transform two bytes into an int. You can do that this way:

unsigned int value = highByte * 256 + lowByte;

Hope it helps! :)

Upvotes: 2

Related Questions