【发布时间】:2014-11-18 14:05:22
【问题描述】:
我需要一次从 Raspberry Pi 向 Arduino 发送 4 个整数。目前 Arduino 不请求或发送数据,但以后可能需要。我的代码有点工作,但是在发送了大约 5 个数组后它崩溃了。
树莓派代码 (Python)
import smbus
import time
bus = smbus.SMBus(1)
address = 0x04
def writeNumber(a,b,c,d):
bus.write_i2c_block_data(address, a, [b, c, d])
return -1
while True:
try:
writeNumber(12,42,-5,0)
time.sleep(1) #delay one second
except KeyboardInterrupt:
quit()
Arduino 代码
#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("----");
}
它将适用于大约 5 个数组,即它将发送 a,b,c,d,然后一秒钟后它会再次发送它,然后一秒钟后再次发送 5 次,然后它崩溃并且 LXTerminal 产生错误:
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
我做错了什么,如何使我的代码更健壮?
【问题讨论】:
-
会不会是
x一直在增加,以至于当大于4时,你开始覆盖一些其他的东西?尝试在每个循环中发送不同的数字,这样您就可以查看是否接收到新数据。现在您每次都发送相同的号码... -
是的。你说对了。我已添加: if(x==4) { x=0;} 问题似乎已解决。感谢您的评论。
标签: python c++ arduino raspberry-pi i2c