Go Down

Topic: Problem with receiving data from 2 devices through i2c (Read 204 times) previous topic - next topic

hameddam

Hello all

I'm trying to read from a MPU6050 and at the same time receive some data from a raspberry pi both over i2c, this is the code I'm using:

Code: [Select]

#include "I2Cdev.h"
#include "MPU6050.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

int data[4];
int x=0;

MPU6050 accelgyro;

int16_t ax, ay, az;
int16_t gx, gy, gz;

#define OUTPUT_READABLE_ACCELGYRO

void setup() {
    Serial.begin(115200);
    accelgyro.initialize();
}

void receiveData() {
  Wire.begin(0x04);
  while(Wire.available()) {              
      if(x==4) { x=0;}
      data[x]=Wire.read();
      x++;
    }
}
void imu(){
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
  #endif
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
}
void loop() {
    imu();
    receiveData();
    Serial.print("a/g:\t");
    Serial.print(ax); Serial.print("\t");
    Serial.print(ay); Serial.print("\t");
    Serial.print(az); Serial.print("\t");
    Serial.print(gx); Serial.print("\t");
    Serial.print(gy); Serial.print("\t");
    Serial.print(gz); Serial.print("\t");
    Serial.println(data[1]);
}



And following is the code I'm using on the raspberry pi:

Code: [Select]

import smbus
import time

bus = smbus.SMBus(1)
address = 0x04

def writeNumber(a,b,c,d):
    bus.write_i2c_block_data(address, a, [b, c, d])
    return -1


while True:
    try:
        x = raw_input("Enter:")
        x = int(x)
        y = x/10
        z = round(y)
        k = int(z)
        writeNumber(0,k,2,3)
        time.sleep(0.01)
    except KeyboardInterrupt:
        quit()



Values from the IMU are being received but the data sent from RPi dont and I'm kind of new to this.

What am I doing wrong?

pylon

The Wire library is not completely multimaster capable and multimaster setups in general are never reliable (at least I never heard of any setup that worked reliable).

Quote
What am I doing wrong?
The slave part is not implemented correctly. You need to implement onReceive and onRequest events, keep in mind that these are run in interrupt context.

I strongly suggest that you change the interface to the Raspberry Pi. If the connection is short you may use SPI, otherwise UART (maybe over RS-485) might be an option.

Go Up