我正在尝试使用I2C将来自NVIDIA Jetson TX1的数据信号发送到Arduino Uno,然后让Arduino发回数据。最终将从传感器收集回发的Arduino数据。 Arduino通过multiplexer连接到Jetson。
当我从Jetson发送一个字符串时,Arduino接收并正确显示它在串行输出上,但是Jetson收到的信号似乎是两个随机字符,其后32个字节的其余部分是255.还有空格似乎不起作用,但这不是一个问题,更多的只是观察。
这是我在Jetson上使用的代码
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <string>
#include <stdio.h>
using namespace std;
int addr1 = 0x40;
int addr2 = 0x04;
int file_i2c;
int file_i2c2;
const int numBytes = 32;
char *filename = (char*)"/dev/i2c-1";
unsigned char buffer[numBytes] = {0};
bool writeStream(int file_i2c, string output) {
if(write(file_i2c, output.c_str(), output.length()) != output.length()) {
printf("\tFailed to write to the i2c bus.\n");
}
return true;
}
int main() {
//Open i2c bus
if((file_i2c = open(filename, O_RDWR)) < 0) {
printf("\tFailed to open the i2c bus\n");
//exit(1);
}
if(ioctl(file_i2c, I2C_SLAVE, addr2) < 0) {
printf("\tFailed to acquire bus access and/or talk to slave.\n");
//exit(1);
}
string input;
cin >> input;
writeStream(file_i2c, input);
cin >> input; //Using this as a breakpoint
if(ioctl(file_i2c, I2C_SLAVE, addr1) < 0) {
printf("\tFailed to acquire bus access and/or talk to slave.\n");
//exit(1);
}
if(read(file_i2c, buffer,numBytes) != numBytes) {
printf("\tFailed to read from the i2c bus.");
}
cout << "Data read:\n";
for (int i = 0; i < numBytes; i++) {
cout << buffer[i] << "\t" << (int)buffer[i] << endl;
}
cout << "End!\n";
return 0;
}
这是我的Arduino代码:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2591.h>
#define TCAADDR 0x70
int clockSpeed = 100000;
char myOutput[32] = {0};
char sent[32] = {0};
void setup() {
digitalWrite(6, HIGH);
Wire.begin(0x04);
Wire.setClock(clockSpeed);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
tcaselect(1);
}
void loop() {
delay(100);
if(strcmp(myOutput, sent)) {
send(myOutput);
strncpy(sent, myOutput, 32);
}
}
void tcaselect(uint8_t i) {
if (i > 7) return;
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}
void receiveEvent() {
char c[32] = {0};
int count = 0;
while (0 < Wire.available()) {
c[count] = Wire.read();
Serial.print(c[count]);
count++;
}
Serial.println();
strncpy(myOutput, c, 32);
}
void send(char c[]) {
Wire.beginTransmission(0x40);
Serial.print("Sending signal:\t");
Wire.write(c);
Serial.print(c);
Serial.println();
Wire.endTransmission();
}