RPI 和 Arduino 之间的 I2C 使用处理



张贴在这里是我的RPi主站和Arduino从站项目的代码。我有一个连接到Arduino的模拟传感器,我正在使用RPi上的处理读取此数据。我正在使用处理,因为我打算用数据生成图形和波形。下面的代码似乎有效,但是,设置的任何轻微移动都会"断开"从属设备,因为我收到以下消息。"设备没有响应。检查电缆以及是否使用了正确的地址。我已经缩小了问题的范围,发现它总是在i2c.read();功能上断开连接。我的问题是是否有某种类型的中断函数,以便在发生这种情况时,处理将继续并在下一次迭代中再次尝试?或者,如果它卡在循环中,它是否在等待来自从设备的一些信号?有人对如何处理这个问题有任何建议吗?

处理代码

import processing.io.*;
I2C i2c;
int val = 0;
void setup()
{
 i2c = new I2C(I2C.list()[0]);
}
void draw ()
{
if (I2C.list() != null)
{
 i2c.beginTransmission(0x04);
 i2c.write(8);
 byte[] in = i2c.read(1);
 int accel = in[0];
 println (accel);
}
}

Arduino Code

 #include <Wire.h>
 #define SLAVE_ADDRESS 0x04
 int number = 5;
 int state = 0;
 const int zInput = A0;
 int zRawMin = 493;
 int zRawMax = 530;
 float acceleration;
 int accel;
 void setup() {
 analogReference(EXTERNAL);
 pinMode(13,OUTPUT);
 Serial.begin(9600);           // start serial for output
 Wire.begin(SLAVE_ADDRESS);                // join i2c bus with address #8
 Wire.onReceive(receiveData); // register event
 Wire.onRequest(sendData);
 Serial.println ("Ready");
 }
 void loop() {
 int zRaw = ReadAxis (zInput);
 acceleration = map (float(zRaw), float (zRawMin), float(zRawMax), -9.81, 9.81);
 accel = int(acceleration);
 //delay(100);
 }
 void receiveData(int byteCount) 
 {
 while (0 < Wire.available()) 
 { // loop through all but the last
 number = Wire.read(); // receive byte as a character
 //Serial.print("data received");
 Serial.println(number);         // print the character
 if (number==1)
 {
 if (state == 0)
 {
 digitalWrite(13,HIGH);
 state = 1;
 }
 else
 {
 digitalWrite(13,LOW);
 state = 0;
 }
 }
 }
 }
 void sendData()
 {
 Wire.write(accel);
 }
 int ReadAxis(int axisPin)
 {
 long reading = 0;
 int raw = analogRead(axisPin);
 return raw;
 } 

看起来解决方案可能是使用由 @Kevin Workman 提供的尝试/捕获块。它适用于我需要它做的事情。

下面是更新的处理代码。

import processing.io.*;
I2C i2c;
int val = 0;
void setup()
{
 i2c = new I2C(I2C.list()[0]);
}
void draw ()
{
if (I2C.list() != null)
{
 i2c.beginTransmission(0x04);
 i2c.write(8);
 try
 {
 byte[] in = i2c.read(1);
 }
 catch(Exception e)
 {
  i2c.endTransmission();
 }
 int accel = in[0];
 println (accel);
}
}

最新更新