使用Processing处理RPI和Arduino之间的I2C

时间:2016-02-22 19:59:37

标签: arduino raspberry-pi processing i2c

这里发布的是我的RPi master和Arduino slave项目的代码。我有一个连接到Arduino的模拟传感器,我正在使用RPi上的Processing读取这些数据。我正在使用Processing,因为我打算用数据生成图形和波形。下面的代码似乎有效,但是,设置的任何轻微移动都会断开"从设备,因为我收到以下消息。 "设备没有响应。检查电缆连接以及是否使用了正确的地址。"我已经缩小了问题,发现它总是在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代码

 #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;
 } 

1 个答案:

答案 0 :(得分:0)

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

这是更新的处理代码。

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);
}
}
相关问题