raspberry pi - I2C between RPI and Arduino using Processing -
posted here code rpi master , arduino slave project. have analog sensor connected arduino , reading data processing on rpi. using processing because intend on generating graph , waveform data. code below seems work, however, slight movement of setup "disconnects" slave device because following message. "the device did not respond. check cabling , whether using correct address." have narrowed problem down , found out disconnects @ i2c.read();
function. question whether there type of break function when happen processing moves on , tries again in next iteration? or if stuck in loop waiting signal slave device? have suggestions on how approach this?
processing code
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 output wire.begin(slave_address); // join i2c bus 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 last number = wire.read(); // receive byte character //serial.print("data received"); serial.println(number); // print 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; }
looks solution might use try/catch block courtesy of @kevin workman. works need thx.
here updated processing code.
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); } }
Comments
Post a Comment