通过串行连接发送大于256的数字

时间:2014-07-16 20:28:09

标签: serial-port arduino

这里给出了我问题的部分解决方案 http://forum.arduino.cc/index.php?topic=97846.0

但在我的arduino代码中使用Wire类,并且不知道如何修改。

这是我完整的arduino代码。任何arduino专家都可以加入吗?

#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);
}

1 个答案:

答案 0 :(得分:1)

我假设您使用的是Arduino Uno。

Arduino Uno将int存储为16位或2字节值。

Serial.write()只能写一个byte,所以你需要稍微调整一下。

你可以使用这种功能:

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

首先编写lowByte(),然后编写highByte

请注意,然后您在奴隶上,您需要将两个bytes转换为int。你可以这样做:

unsigned int value = highByte * 256 + lowByte;

希望它有所帮助! :)

相关问题