Python 通过I2C从Raspberry Pi向Arduino发送整数数组

Python 通过I2C从Raspberry Pi向Arduino发送整数数组,python,c++,arduino,raspberry-pi,i2c,Python,C++,Arduino,Raspberry Pi,I2c,我需要一次发送4个整数从树莓圆周率到Arduino。目前Arduino没有请求或发送数据,但以后可能需要。我的代码可以正常工作,但在发送了大约5个数组后崩溃了 Raspberry Pi代码(Python) 阿杜伊诺代码 #include <Wire.h> int data [4]; int x = 0; void setup() { Serial.begin(9600);

我需要一次发送4个整数从树莓圆周率到Arduino。目前Arduino没有请求或发送数据,但以后可能需要。我的代码可以正常工作,但在发送了大约5个数组后崩溃了

Raspberry Pi代码(Python)

阿杜伊诺代码

#include <Wire.h>

int data [4];
int x = 0;

void setup() {                                 

Serial.begin(9600);                        
Wire.begin(0x04);                          
Wire.onReceive(receiveData);               //callback for i2c. Jump to void recieveData() function when pi sends data

}

void loop () {

    delay(100);                            //Delay 0.1 seconds. Something for the arduino to do when it is not inside the reciveData() function. This also might be to prevent data collisions.

}

void receiveData(int byteCount) { 

   while(Wire.available()) {               //Wire.available() returns the number of bytes available for retrieval with Wire.read(). Or it returns TRUE for values >0.
       data[x]=Wire.read();
       x++;
     }
   }

     Serial.println("----");
     Serial.print(data[0]);
     Serial.print("\t");
     Serial.print(data[1]);
     Serial.print("\t");
     Serial.print(data[2]);
     Serial.print("\t");
     Serial.println(data[3]);
     Serial.print("----");

}

我做错了什么?如何使代码更健壮?

只需将地址更改为更大的地址即可。第一个地址是保留的(请参阅)。我将您的代码与地址
0x20
一起使用,效果很好。

可能是
x
不断增加,因此当它大于4时,您开始覆盖其他内容吗?尝试在每个循环中发送不同的数字,这样您可以查看是否接收到新数据。现在你每次都发送相同的号码…是的。你明白了。我添加了:if(x==4){x=0;},这个问题似乎已经解决了。谢谢你的评论。
#include <Wire.h>

int data [4];
int x = 0;

void setup() {                                 

Serial.begin(9600);                        
Wire.begin(0x04);                          
Wire.onReceive(receiveData);               //callback for i2c. Jump to void recieveData() function when pi sends data

}

void loop () {

    delay(100);                            //Delay 0.1 seconds. Something for the arduino to do when it is not inside the reciveData() function. This also might be to prevent data collisions.

}

void receiveData(int byteCount) { 

   while(Wire.available()) {               //Wire.available() returns the number of bytes available for retrieval with Wire.read(). Or it returns TRUE for values >0.
       data[x]=Wire.read();
       x++;
     }
   }

     Serial.println("----");
     Serial.print(data[0]);
     Serial.print("\t");
     Serial.print(data[1]);
     Serial.print("\t");
     Serial.print(data[2]);
     Serial.print("\t");
     Serial.println(data[3]);
     Serial.print("----");

}
Traceback (most recent call last):
File "PS3_ctrl_v2.py", line 44, in <module>
writeNumber(12,42,-5,0)
File "PS3_ctrl_v2.py", line 11, in writeNumber
bus.write_i2c_block_data(address, a, [b, c, d])
IOError: [Errno 5] Input/output error