Hello!
I'm working on a system consisting of an I2C connected RPi, Nano, and 16 channel Adafruit servo controller. The goal is to have the RPi track faces, send the raw coordinates to the Nano for processing, and then have the Nano send position data to the servos all via the same SDA and SCL lines. The RPi can successfully track faces and send integer coordinates to the Nano, and the Nano can successfully control the servos, but not at the same time! Any Arudino code I make that is able to communicate with the servo controller causes the RPi to generate an error when it tries to send a coordinate and terminates the facial tracking; any code capable of properly interfacing with the RPi will not communicate with the servo controller. This is my first I2C project, and I've been stuck for weeks on this!
The RPi code is fine (well, I think!), so I'll just post the Nano code I'm currently working with. The receiveData() function has a "flip flop" in it because the RPi is alternately sending X and Y coordinates (I know there's probably a better way to do it). I've configured this code a hundred different ways, but so far my debugging has only uncovered the fact that the Wire.endTransmission() at the very end is the line causing my RPi displeasure. If I remove it, the controller stops responding but the RPi has no problem. If I keep it, the controller works but the RPi jams as soon as it tries to send something. If somebody out there could help me at all, I would really appreciate it!! - Brady
#include <Wire.h>
#include <Servo.h>
#include <PID_v1.h>
#include <Adafruit_PWMServoDriver.h>
//=====================================================================================================
void setup() {
Serial.begin(9600);
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
//=====================================================================================================
void loop() {
delay(15);
}
// callback for received data
void receiveData(int byteCount){
if(flag == 0){
Wire.read();
value = Wire.read();
Serial.print("x value: ");
Serial.println(value);
x_ctl.Compute();
move_servo(9, (init_posX + posX));
flag = 1;
}
else{
Wire.read();
value = Wire.read();
Serial.print("y value: ");
Serial.println(value);
y_ctl.Compute();
move_servo(10, (init_posY + posY));
flag = 0;
}
}
//=====================================================================================================
void move_servo(int ch, double pos){
Wire.begin();
Wire.beginTransmission(0x40); //0x06
Wire.write(LED0_ON_L+4*ch);
Wire.write(0);
Wire.write(0>>8);
Wire.write(cast_pos);
Wire.write(cast_pos>>8);
Wire.endTransmission();
Wire.begin(SLAVE_ADDRESS);
}