[英]send 2Dimensional Listarray From Raspberry pi to the Arduino with I2c protocol
[英]Send Integer Array via I2C from Raspberry Pi to Arduino
我需要一次从Raspberry Pi向Arduino发送4个整数。 目前Arduino并未要求或传送资料,但稍后可能需要。 我的代码工作正常,但是在发送大约5个数组后崩溃。
Raspberry Pi代码(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
我在做什么错,如何使我的代码更健壮?
只需将地址更改为更大的内容即可。 保留第一个地址(请参阅本文 )。 我使用的地址为0x20
的代码可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.