我正在尝试在 Arduino nano 33 IOT 和 Jetson Nano 2gb 之间使用 i2c 总线。我正在使用 i2c 总线,并且想将整数数组发送到 Jetson Nano,但是当我通过总线接收数据时,它是乱码,并破坏了从 Jetson 发送到 Arduino 的数据。
Jetson Nano 引脚: 接地,27(SDA),28(SDL) Arduino Nano 33 IoT 引脚: GND、A4(SDA)、A5(SCL)
Arduino代码:
#include <Wire.h>
int data [4];
int x = 0;
void setup() {
Serial.begin(9600);
Wire.begin(0x6a);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop () {
//sendData();
delay(100);
}
void sendData() {
int arr[4] = { 0, 23, 41, 19 };
Serial.println("Sending Data to Jetson ...");
//sendI2C((byte*) arr, sizeof(arr));
Wire.write( (byte*)&arr, sizeof(arr));
Serial.print("Sent...");
Serial.println();
}
//void sendI2C(byte *data, int size) {
// Wire.beginTransmission(0x6a);
// for(int i = 0; i < size; i++) {
// Wire.write(data[i]);
// }
// Wire.endTransmission();
//}
void receiveData(int byteCount) {
while(Wire.available() && x < 4) { //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++;
}
if(x == 4) { x = 0; }
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("----");
//sendData();
}
Jetson Nano - Python3 代码:
import smbus
import time
bus = smbus.SMBus(0)
address = 0x6a
def writeArray(a, b, c, d):
bus.write_i2c_block_data(address, a, [b, c, d])
return -1
def readArray(bytes_nr):
values = bus.read_i2c_block_data(address, 0x00, bytes_nr)
return values
while True:
writeArray(14,42,95,0)
time.sleep(1)
values = readArray(8)
print(values)
发生了两件事:
[14, 42, 95, 0]
[0, 0, 0, 0, 0, 0, 42, 105, 0 , 0, 4, 0 , 0 ,0 ,0 , 56, 0 , 0 , 0 ,0 ,0, 187, 0 , 0 ,0, 0, 0 , 0]
-- And on the Arduino console the data shifts from left to right so instead of receiving `[14, 42, 95, 0]`, It prints
[8, 14, 42, 95]
我只是对从两侧发送 4 个整数的数组感兴趣。怎么办?
Arduino 代码使用原始 I2C 协议,Jetson 在 I2C 之上使用 SMBus。 SMBus 块结构意味着要传输 1 个额外字节的长度。