【发布时间】:2016-02-22 19:59:37
【问题描述】:
这里发布的是我的 RPi master 和 Arduino slave 项目的代码。我有一个连接到 Arduino 的模拟传感器,我正在使用 RPi 上的处理读取这些数据。我正在使用处理,因为我打算用数据生成图形和波形。下面的代码似乎有效,但是,安装程序的任何轻微移动都会“断开”从设备,因为我收到以下消息。 “设备没有响应。检查电缆以及您使用的地址是否正确。”我已经缩小了问题的范围,发现它总是在i2c.read();function 处断开连接。我的问题是是否存在某种类型的中断功能,以便在发生这种情况时继续处理并在下一次迭代中再次尝试?或者如果它卡在一个循环中,它是否正在等待来自从设备的一些信号?有人对如何解决这个问题有任何建议吗?
处理代码
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;
}
【问题讨论】:
-
你从哪里得到这个消息?它是一个例外吗?您是否尝试将您对
read()的调用封装在 try/catch 块中? -
Kevin,我在处理控制台中得到它。不确定是否是异常,但我会尝试 try/catch 块,看看它是否有效。
-
@KevinWorkman 我试过了,它似乎工作得很好,看看下面。
标签: arduino raspberry-pi processing i2c