两个arduino之间的I2C通信的数据格式

时间:2018-09-19 14:17:33

标签: arduino

我有2个通过I2C连接的arduino。我不知道是否相关,但master是nodemcu,slave是nano。我的问题是,当主请求时,以正确的格式将数据从从发送到主。

这是主代码:

#include <Wire.h>

void setup() {
 Serial.begin(9600); /* begin serial for debug */
 Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}

void loop() {
 Wire.beginTransmission(8); /* begin with device address 8 */
 Wire.write("Hello Arduino");  /* sends hello string */
 Wire.endTransmission();    /* stop transmitting */

 Wire.requestFrom(8, 13); /* request & read data of size 13 from slave */
 while(Wire.available()){
    char c = Wire.read();
  Serial.print(c);
 }
 Serial.println();
 delay(1000);
}

这是从代码:

#include <Wire.h>

int value = 2;

void setup() {
 Wire.begin(8);                /* join i2c bus with address 8 */
 Wire.onReceive(receiveEvent); /* register receive event */
 Wire.onRequest(requestEvent); /* register request event */
 Serial.begin(9600);           /* start serial for debug */
}

void loop() {
 delay(100);
}

// function that executes whenever data is received from master
void receiveEvent(int howMany) {
 while (0 <Wire.available()) {
    char c = Wire.read();      /* receive byte as a character */
    Serial.print(c);           /* print the character */
  }
 Serial.println();             /* to newline */
}

// function that executes whenever data is requested from master
void requestEvent() {

 char my_str[8]; // an array big enough for a 5 character string
 //  Serial.begin(9600);
    my_str[0] = 'H'; // the string consists of 5 characters
    my_str[1] = value;
    my_str[2] = 'l';
    my_str[3] = 'l';
    my_str[4] = 'o';
    my_str[5] = 'o';
    my_str[6] = 'o';
    my_str[7] = 0; // 6th array element is a null terminator
    Wire.write(my_str);

}

现在的问题是在主服务器上,在位“ 2”我收到了“”。 而是收到“ H2llooo”,而收到“ Hllooo”。 如果我替换为“ my_str [1] = value;” “ my_str [1] =” 2“;”然后工作正常,但我想使用那个是整数的变量... 我将不胜感激

谢谢

0 个答案:

没有答案