Multiple Devices Over I2C

Status
Not open for further replies.

pzschulte

Member
Hello,

I've been working with the Teensy 3.2 for the last 6 months. I've made great use of this forum, but this is the first time I feel like I've found a problem I couldn't figure out using old posts.

I have 2 Teensy's connected together via I2C. One Teensy (Master) is collecting data from the Sparkfun MPU6050 accelerometer breakout board via I2C. The other (Slave) is collecting data from an AttoPilot Voltage and Current Sense breakout. I have properly setup the Master to collect MPU6050 data, and the slave to collect Voltage/Current data. The problem comes when I try to send the float values of the Voltage/Current measurements from the Slave to the Master. Note that I am powering both Teensys from separate USB COM ports on the same laptop using teensyduino.

If I leave out the code for MPU6050 data collection on the Master, I have been able to use the I2C_Anything library (http://forum.arduino.cc/index.php?topic=104732.0) to send the 2 floats from the Slave to the Master. However, if I try implementing both I2C_Anything and the I2Cdev library for MPU6050 (https://github.com/jrowberg/i2cdevlib) at the same time on the Master, it doesn't work properly. The data does not come through, and after a few seconds both the Master and the Slave freeze up.

I've tried debugging, but since I am very inexperienced with I2C, I thought someone out there might be able to point out where my two I2C libraries are conflicting. All source code is below. Let me know if more information or further clarification is needed.

Thanks!
Peter

Here is my Slave code:
Code:
#include <Wire.h>
#include "I2C_Anything.h"

int VRaw; //This will store our raw ADC data
int IRaw;
float VFinal; //This will store the converted data
float IFinal;
const int ledPin = 13;

volatile byte* INPUT1FloatPtr;
volatile byte* INPUT2FloatPtr;
int Address = 8;  //This slave is address number 8

const byte SLAVE_ADDRESS = 42;

void setup() {

Serial.begin(115200);
pinMode(ledPin, OUTPUT);
Wire.begin();

}


void loop() { 
  
  //Measurement
  VRaw = analogRead(A0);
  IRaw = analogRead(A1);
  
  //Conversion
  VFinal = VRaw/49.44; //45 Amp board
  //VFinal = VRaw/12.99; //90 Amp board
  //VFinal = VRaw/12.99; //180 Amp board  
  
  IFinal = IRaw/14.9; //45 Amp board
  //IFinal = IRaw/7.4; //90 Amp board
  //IFinal = IRaw/3.7; //180 Amp board
    
  //Display
  digitalWrite(ledPin, HIGH);   // set the LED on
  Serial.print(VFinal);
  Serial.println("   Volts");
  Serial.print(IFinal);
  Serial.println("   Amps");
  
   Wire.beginTransmission (SLAVE_ADDRESS);
   I2C_writeAnything (VFinal);
   I2C_writeAnything (IFinal);
   Wire.endTransmission ();
  
  delay(500);
  digitalWrite(ledPin, LOW);    // set the LED off
  delay(500);
}

void requestEvent()
{
  byte* Data;
 INPUT1FloatPtr = (byte*) &VFinal;
 INPUT2FloatPtr = (byte*) &IFinal;
 Data[0] = INPUT1FloatPtr[0]; 
 Data[1] = INPUT1FloatPtr[1]; 
 Data[2] = INPUT1FloatPtr[2]; 
 Data[3] = INPUT1FloatPtr[3]; 
 Data[4] = INPUT2FloatPtr[0];
 Data[5] = INPUT2FloatPtr[1];
 Data[6] = INPUT2FloatPtr[2];
 Data[7] = INPUT2FloatPtr[3];
 Wire.send(Data,Address); 
}

Here is the Master code that collects the data successfully using I2C_Anything:
Code:
#include <Wire.h>
#include "I2C_Anything.h"

const byte MY_ADDRESS = 42;

void setup() 
{
 Wire.begin (MY_ADDRESS);
 Serial.begin (115200);
 Wire.onReceive (receiveEvent);
}  // end of setup

volatile boolean haveData = false;
volatile float fnum;
volatile float foo;

void loop() 
{
 if (haveData)
   {
   Serial.print ("Received fnum = ");
   Serial.println (fnum);  
   Serial.print ("Received foo = ");
   Serial.println (foo);  
   haveData = false;  
   }  // end if haveData

}  // end of loop

// called by interrupt service routine when incoming data arrives
void receiveEvent (int howMany)
{
if (howMany >= (sizeof fnum) + (sizeof foo))
  {
  I2C_readAnything (fnum);   
  I2C_readAnything (foo);   
  haveData = true;     
  }  // end if have enough data

}  // end of receiveEvent

And here is my attempt in the Master code to do both MPU6050 and I2C_Anything (note that there are a few other sensors and data outputs here but none of them are using I2C):
Code:
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"
#include "I2C_Anything.h"
#include "FrSkySPort.h"

#define debugSerial           Serial
#define _MavLinkSerial      Serial2
#define START                   1
#define MSG_RATE            10             // Hertz
#include <AltSoftSerial.h>
#include <OneWire.h> 

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

#define OUTPUT_READABLE_REALACCEL

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
uint8_t TeensyIntPin = 3; //Identify Teensy interrupt pin

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// MAVLINK_FRSKYSPORT Declarations
// Message #0  HEARTHBEAT
uint8_t    ap_type = 0;
uint8_t    ap_autopilot = 0;
uint8_t    ap_base_mode = 0;
uint32_t  ap_custom_mode = 0;
uint8_t    ap_system_status = 0;
uint8_t    ap_mavlink_version = 0;

// Message # 1  SYS_STATUS
uint16_t  ap_voltage_battery = 0;    // 1000 = 1V
int16_t    ap_current_battery = 0;    //  10 = 1A

// Message #24  GPS_RAW_INT
uint8_t    ap_fixtype = 0;                  //   0= No GPS, 1 = No Fix, 2 = 2D Fix, 3 = 3D Fix
uint8_t    ap_sat_visible = 0;           // numbers of visible satelites
// FrSky Taranis uses the first recieved lat/long as homeposition.
int32_t    ap_latitude = 0;               // 585522540;
int32_t    ap_longitude = 0;            // 162344467;
int32_t    ap_gps_altitude = 0;        // 1000 = 1m

// Message #74 VFR_HUD
int32_t    ap_airspeed = 0;
uint32_t  ap_groundspeed = 0;
uint32_t  ap_heading = 0;
uint16_t  ap_throttle = 0;

// FrSky Taranis uses the first recieved value after 'PowerOn' or  'Telemetry Reset'  as zero altitude
int32_t    ap_bar_altitude = 0;    // 100 = 1m
int32_t    ap_climb_rate = 0;      // 100= 1m/s

// Message #27 RAW IMU
int32_t   ap_accX = 0;
int32_t   ap_accY = 0;
int32_t   ap_accZ = 0;

int32_t   ap_accX_old = 0;
int32_t   ap_accY_old = 0;
int32_t   ap_accZ_old = 0;

// These are special for FrSky
int32_t   adc2 = 0;               // 100 = 1.0V
int32_t     vfas = 0;                // 100 = 1,0V
int32_t     gps_status = 0;     // (ap_sat_visible * 10) + ap_fixtype

uint16_t  hb_count;
unsigned long MavLink_Connected_timer;
unsigned long hb_timer;
unsigned long acc_timer;

int led = 13;

AltSoftSerial altSerial;
int DS18S20_Pin = 2; //DS18S20 Signal pin on digital 2 (tempearature sensor)
OneWire ds(DS18S20_Pin);  // on digital pin 2
int count=0;

//Hall Effect Sensor
volatile byte half_revolutions;
unsigned int rpm;
unsigned long timeold;
int US1881_Pin = 4; //US1881 Signal pin on digital 4 (hall effect sensor)
 
//I2C_Anything
volatile boolean haveData=false;
volatile float VFinal;
volatile float IFinal;
const byte MY_ADDRESS = 42;

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
  mpuInterrupt = true;
}

void setup() {
  //Activate internal pullup resistor for DS18S20 temp sensor
  pinMode(DS18S20_Pin, INPUT_PULLUP);
  
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin(MPU6050_DEFAULT_ADDRESS);
  TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  Serial.begin(115200);
  altSerial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Teensy external interrupt TeensyIntPin)..."));  //MattC
    pinMode(TeensyIntPin, INPUT); // sets the digital pin as input  //MattC
    attachInterrupt(TeensyIntPin, dmpDataReady, RISING);  //MattC
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);

  // MAVLINK_FRSKYSPORT Setup
  FrSkySPort_Init();
  _MavLinkSerial.begin(57600);
  debugSerial.begin(57600);
  //MavLink_Connected = 0;
  MavLink_Connected_timer = millis();
  hb_timer = millis();
  acc_timer = hb_timer;
  hb_count = 0;

  pinMode(led, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(14, INPUT);
  analogReference(DEFAULT);

   //Activate internal pullup resistor for DS18S20 temp sensor
   pinMode(US1881_Pin, INPUT_PULLUP);
   
   Serial.begin(115200);
   attachInterrupt(US1881_Pin, magnet_detect, RISING);//Initialize the intterrupt pin (Arduino digital pin 2)
   half_revolutions = 0;
   rpm = 0;
   timeold = 0;

    //Start receive from I2C_Anything
    Wire.begin (MY_ADDRESS);
    Wire.onReceive (receiveEvent);
}

// called by interrupt service routine when incoming data arrives
void receiveEvent (int howMany)
{
if (howMany >= (sizeof VFinal) + (sizeof IFinal))
  {
  I2C_readAnything (VFinal);   
  I2C_readAnything (IFinal);   
  haveData = true;     
  }  // end if have enough data

}  // end of receiveEvent

void loop() {
  
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

#ifdef OUTPUT_READABLE_REALACCEL
    // display real acceleration, adjusted to remove gravity
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetAccel(&aa, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
     
    Serial.print("$");
    if (aaReal.x >= 0) {
      Serial.print(' ');
    }
    if (abs(aaReal.x) < 1000) {
      Serial.print(' ');
    }
    if (abs(aaReal.x) < 100) {
      Serial.print(' ');
    }
    if (abs(aaReal.x) < 10) {
      Serial.print(' ');
    }
    Serial.print(aaReal.x);
    Serial.print("\t");
    if (aaReal.y >= 0) {
      Serial.print(' ');
    }
    if (abs(aaReal.y) < 1000) {
      Serial.print(' ');
    }
    if (abs(aaReal.y) < 100) {
      Serial.print(' ');
    }
    if (abs(aaReal.y) < 10) {
      Serial.print(' ');
    }
    Serial.print(aaReal.y);
    Serial.print("\t");
    if (aaReal.z >= 0) {
      Serial.print(' ');
    }
    if (abs(aaReal.z) < 1000) {
      Serial.print(' ');
    }
    if (abs(aaReal.z) < 100) {
      Serial.print(' ');
    }
    if (abs(aaReal.z) < 10) {
      Serial.print(' ');
    }
    Serial.print(aaReal.z);
    Serial.println();

#endif

    // MAVLINK_FRSKYSPORT Loop
    uint16_t len;

    FrSkySPort_Process();               // Check FrSky S.Port communication

    adc2 = analogRead(0) / 4;            // Read ananog value from A0 (Pin 14). ( Will be A2 value on FrSky LCD)

    if ((millis() - acc_timer) > 1000) {   // Reset timer for AccX, AccY and AccZ
      ap_accX_old = ap_accX;
      ap_accY_old = ap_accY;
      ap_accZ_old = ap_accZ;
      acc_timer = millis();
      //debugSerial.println(adc2);
    }

      float temperature = getTemp();
      Serial.print("$T");
      Serial.print(temperature);
      Serial.println("          a");
      count=0;

     //Measure RPM
     if (half_revolutions >= 20) { 
     rpm = 30*1000/(millis() - timeold)*half_revolutions;
     timeold = millis();
     half_revolutions = 0;
     //Serial.println(rpm,DEC);
     }

   //Read voltage and current via I2C_Anything
   if (haveData)
   {
   Serial.print ("$V");
   Serial.println (VFinal);  
   Serial.print ("$I");
   Serial.println (IFinal);
   haveData = false;  
   }  // end if haveData
   Serial.println();
   
    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
  }
}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);    
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }
  
  ds.reset_search();
  
  byte MSB = data[1];
  byte LSB = data[0];

  float tempRead = ((MSB << 8) | LSB); //using two's compliment
  float TemperatureSum = tempRead / 16;
  
  return TemperatureSum;
  
}

void magnet_detect()//This function is called whenever a magnet/interrupt is detected by the arduino
 {
   half_revolutions++;
   Serial.println("==================detect==================");
 }
 
Maybe this will help, maybe not. I know nothing about I2C_Anything. Try i2c_t3 which should let you do this. I've been using it on complex I2C systems with multiple devices and am in process of adding I2C with multiple I2C networks on a Teensy 3.2 - only normal I2C at 400 kHz and the other PMBus at 100 KHz. Each will be a master so not exactly what you are doing. i2c_t3, IMHO is WAY better than the standard Wire library. Here is the user doc: https://forum.pjrc.com/threads/21680-New-I2C-library-for-Teensy3

Use TyQt to manage multiple USB targets at the same time. I am doing this now. Otherwise TD and Arduino can get into a struggle with more than one USB/Teensy active at a time.

Your Master should be able to have both its MPU6050 and a slave Teensy 3.2 as its slaves.

Only one device on I2C can be creating the clock at a time. It is possible to have I2C peers (we have done this) but it takes some special care. We used custom code for that.

Your slave Teensy device wants to have two separate I2C nets: one where it is a master to its I2C sensor and another where it is a slave to the Master Teensy. It looks to me that your Slave Teensy is really acting like a Master since it is using Wire.beginTransmission to start a message. That means it will be outputting the I2C clock. Now your Master Teensy will also be trying to drive the clock to access its MPU6050 so you have clashing clocks. The Slave Teensy should not be starting a cycle that way, but only responding to the clock of the master. There is documentation about this at the link above and the basic_slave and advanced_slave examples. You start the slave more like this:
// Setup for Slave mode, address 0x66, pins 18/19, external pullups, 400kHz
Wire.begin(I2C_SLAVE, 0x66, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);

Put an oscillloscope on the Master SCL and SDA, triggered with SCL going low (start of I2C message) and see what is there to make sure all is as it should be.

Hope that is some help.

i2c_t3 is really a wonderful library! Thanks to nox711 for writing, sharing, and maintaining it!
 
Last edited:
Thanks bboyes, I will try these things!

Maybe this will help, maybe not. I know nothing about I2C_Anything. Try i2c_t3 which should let you do this. I've been using it on complex I2C systems with multiple devices and am in process of adding I2C with multiple I2C networks on a Teensy 3.2 - only normal I2C at 400 kHz and the other PMBus at 100 KHz. Each will be a master so not exactly what you are doing. i2c_t3, IMHO is WAY better than the standard Wire library. Here is the user doc: https://forum.pjrc.com/threads/21680-New-I2C-library-for-Teensy3

Use TyQt to manage multiple USB targets at the same time. I am doing this now. Otherwise TD and Arduino can get into a struggle with more than one USB/Teensy active at a time.

Your Master should be able to have both its MPU6050 and a slave Teensy 3.2 as its slaves.

Only one device on I2C can be creating the clock at a time. It is possible to have I2C peers (we have done this) but it takes some special care. We used custom code for that.

Your slave Teensy device wants to have two separate I2C nets: one where it is a master to its I2C sensor and another where it is a slave to the Master Teensy. It looks to me that your Slave Teensy is really acting like a Master since it is using Wire.beginTransmission to start a message. That means it will be outputting the I2C clock. Now your Master Teensy will also be trying to drive the clock to access its MPU6050 so you have clashing clocks. The Slave Teensy should not be starting a cycle that way, but only responding to the clock of the master. There is documentation about this at the link above and the basic_slave and advanced_slave examples. You start the slave more like this:


Put an oscillloscope on the Master SCL and SDA, triggered with SCL going low (start of I2C message) and see what is there to make sure all is as it should be.

Hope that is some help.

i2c_t3 is really a wonderful library! Thanks to nox711 for writing, sharing, and maintaining it!
 
Deconflicting Wire and i2c_t3 libraries

Sorry it has taken a while for me to follow up on this topic. I have been able to successfully implement some simple sending/receiving of data from the AttoPilot Voltage and Current Sense breakout using i2c_t3 with the modified basic_master and basic_slave example scripts below:

Code:
// -------------------------------------------------------------------------------------------
// Basic Slave
// -------------------------------------------------------------------------------------------
//
// This creates a simple I2C Slave device which will print whatever text string is sent to it.
// It will retain the text string in memory and will send it back to a Master device if 
// requested.  It is intended to pair with a Master device running the basic_master sketch.
//
// This example code is in the public domain.
//
// Modified by Peter Schulte 3/21/17 to send data from AttoPilot Current/Voltage sensor
// -------------------------------------------------------------------------------------------

#include <i2c_t3.h>

// Function prototypes
void receiveEvent(size_t count);
void requestEvent(void);

// Memory
#define MEM_LEN 256
uint8_t databuf[MEM_LEN];
volatile uint8_t received;
int VFinal; //This will store the converted data
int IFinal;

//
// Setup
//
void setup()
{
    pinMode(LED_BUILTIN,OUTPUT); // LED

    // Setup for Slave mode, address 0x66, pins 18/19, external pullups, 400kHz
    Wire.begin(I2C_SLAVE, 0x66, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);

    // Data init
    received = 0;
    memset(databuf, 0, sizeof(databuf));
    VFinal=0;
    IFinal=100;

    // register events
    Wire.onReceive(receiveEvent);
    Wire.onRequest(requestEvent);

    Serial.begin(115200);
}

void loop()
{
    delay(500);

    //Measurement
    VFinal = analogRead(A0);
    IFinal = analogRead(A1);
  
    //Increment VFinal and IFinal and print
    //VFinal++;
    //IFinal++;
    
    // print received data - this is done in main loop to keep time spent in I2C ISR to minimum
    if(received)
    {
        digitalWrite(LED_BUILTIN,HIGH);
        Serial.printf("Slave received: '%s'\n", (char*)databuf);
        received = 0;
        digitalWrite(LED_BUILTIN,LOW);
    }
}

//
// handle Rx Event (incoming I2C data)
//
void receiveEvent(size_t count)
{
    size_t idx=0;
    
    while(idx < count)
    {
        if(idx < MEM_LEN)                     // drop data beyond mem boundary
            databuf[idx++] = Wire.readByte(); // copy data to mem
        else
            Wire.readByte();                  // drop data if mem full
    }
    
    received = count; // set received flag to count, this triggers print in main loop
}

//
// handle Tx Event (outgoing I2C data)
//
void requestEvent(void)
{
    //Wire.write(databuf, MEM_LEN); // fill Tx buffer (send full mem)

    char Vf[MEM_LEN];
    sprintf(Vf,"V%f A%f",(double)VFinal/12.99,(double)IFinal/7.4);
    Wire.write(Vf);
    Serial.printf("Sending '%s'\n",Vf);
    //Wire.write((byte)VFinal); // fill Tx buffer (send full mem)
    //Wire.write(Vfinal); // fill Tx buffer (send full mem)
}

Code:
// -------------------------------------------------------------------------------------------
// Basic Master
// -------------------------------------------------------------------------------------------
//
// This creates a simple I2C Master device which when triggered will send/receive a text 
// string to/from a Slave device.  It is intended to pair with a Slave device running the 
// basic_slave sketch.
//
// Pull pin12 input low to send.
// Pull pin11 input low to receive.
//
// This example code is in the public domain.
//
// -------------------------------------------------------------------------------------------

#include <i2c_t3.h>

// Memory
#define MEM_LEN 256
char databuf[MEM_LEN];
int count;

void setup()
{
    pinMode(LED_BUILTIN,OUTPUT);    // LED
    digitalWrite(LED_BUILTIN,LOW);  // LED off
    //pinMode(12,INPUT_PULLUP);       // Control for Send
    //pinMode(11,INPUT_PULLUP);       // Control for Receive
    pinMode(12,INPUT);       // Control for Send
    pinMode(11,INPUT);       // Control for Receive

    // Setup for Master mode, pins 18/19, external pullups, 400kHz, 200ms default timeout
    Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);
    Wire.setDefaultTimeout(200000); // 200ms

    // Data init
    memset(databuf, 0, sizeof(databuf));
    count = 0;

    Serial.begin(115200);
}

void loop()
{
    uint8_t target = 0x66; // target Slave address
    size_t idx;

    //Set pin 12 LOW to send
    delay(1000);
    digitalWrite(12,LOW);
//    if(digitalRead(12) == LOW)
//    {
//      Serial.printf("\nSet pin 12 LOW to send\n");    
//    }
    
    // Send string to Slave
    //
    if(digitalRead(12) == LOW)
    {
        digitalWrite(LED_BUILTIN,HIGH);   // LED on

        // Construct data message
        sprintf(databuf, "Data Message #%d", count++);

        // Print message
        Serial.printf("Sending to Slave: '%s' ", databuf);
        
        // Transmit to Slave
        Wire.beginTransmission(target);   // Slave address
        for(idx = 0; idx <= strlen(databuf); idx++) // Write string to I2C Tx buffer (incl. string null at end)
            Wire.write(databuf[idx]);
        Wire.endTransmission();           // Transmit to Slave

        // Check if error occured
        if(Wire.getError())
            Serial.print("FAIL\n");
        else
            Serial.print("OK\n");

        digitalWrite(LED_BUILTIN,LOW);    // LED off
        delay(100);                       // Delay to space out tests
    }
    
    //Set pin 12 HIGH to stop sending
    //digitalWrite(12,HIGH);
//    if(digitalRead(12) == HIGH)
//    {
//      Serial.printf("Set pin 12 HIGH to stop sending\n\n");    
//    }
    
    //Set pin 11 LOW to receive
    delay(1000);
    digitalWrite(11,LOW);
//    if(digitalRead(11) == LOW)
//    {
//      Serial.printf("Set pin 11 LOW to receive\n");    
//    }
//    
    // Read string from Slave
    //
    if(digitalRead(11) == LOW)
    {
        digitalWrite(LED_BUILTIN,HIGH);   // LED on

        // Print message
        Serial.print("Reading from Slave: ");
        
        // Read from Slave
        Wire.requestFrom(target, (size_t)MEM_LEN); // Read from Slave (string len unknown, request full buffer)

        // Check if error occured
        if(Wire.getError())
            Serial.print("FAIL\n");
        else
        {
            // If no error then read Rx data into buffer and print
            idx = 0;
            while(Wire.available())
                databuf[idx++] = Wire.readByte();
            Serial.printf("'%s' OK\n",databuf);
        }

        digitalWrite(LED_BUILTIN,LOW);    // LED off
        delay(100);                       // Delay to space out tests
    }
    
    //Set pin 11 HIGH to stop recieving
    //digitalWrite(11,HIGH);
//    if(digitalRead(11) == HIGH)
//    {
//      Serial.printf("Set pin 11 HIGH to stop receiving\n\n");    
//    }
}

However, when I try to add in the i2c_t3 library to my MPU6050 sketch (identical code to the MPU6050 sketch from the first post on 12/7/16, but with #include <i2c_t3.h> added in), in order to implement the same behavior from basic_master, I get the following compiler error messages:

Code:
Arduino: 1.8.1 (Windows 8.1), TD: 1.35, Board: "Teensy 3.2 / 3.1, Serial, 24 MHz, Fast, US English"

In file included from C:\Users\Peter\Documents\Arduino\TeensyTutorials\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect.ino:100:0:

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h: In member function 'uint8_t MPU6050::dmpInitialize()':

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h:497:21: warning: variable 'mpuIntStatus' set but not used [-Wunused-but-set-variable]

             uint8_t mpuIntStatus = getIntStatus();

                     ^

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h:347:13: warning: unused variable 'hwRevision' [-Wunused-variable]

     uint8_t hwRevision = readMemoryByte();

             ^

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h:355:13: warning: unused variable 'otpValid' [-Wunused-variable]

     uint8_t otpValid = getOTPBankValid();

             ^

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h: In member function 'uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t, uint8_t*)':

C:\Users\Peter\Documents\Arduino\libraries\MPU6050/MPU6050_6Axis_MotionApps20.h:723:41: warning: value computed is not used [-Wunused-value]

         if (processed != 0) *processed++;

                                         ^

In file included from C:\Users\Peter\Documents\Arduino\TeensyTutorials\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect.ino:108:0:

C:\Users\Peter\Documents\Arduino\libraries\i2c_t3/i2c_t3.h: At global scope:

C:\Users\Peter\Documents\Arduino\libraries\i2c_t3/i2c_t3.h:994:15: error: conflicting declaration 'i2c_t3 Wire'

 extern i2c_t3 Wire;

               ^

In file included from C:\Users\Peter\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:0,

                 from C:\Users\Peter\Documents\Arduino\TeensyTutorials\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect.ino:98:

C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\Wire/Wire.h:104:16: error: 'Wire' has a previous declaration as 'TwoWire Wire'

 extern TwoWire Wire;

                ^

MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect: In function 'float getTemp()':
MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect:342: warning: unused variable 'present' 
   byte present = ds.reset();

        ^

MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect: In function 'void receiveEvent(int)':
MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect:493: warning: comparison between signed and unsigned integer expressions 
 if (howMany >= (sizeof VFinal) + (sizeof IFinal))

                                                ^

MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect: In function 'void loop()':
MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect:732: warning: unused variable 'len' 
     uint16_t len;

              ^

FrSkySPort: In function 'void FrSkySPort_Process()':
FrSkySPort:32: warning: unused variable 'temp' 
   uint32_t temp = 0;

            ^

Multiple libraries were found for "i2c_t3.h"
 Used: C:\Users\Peter\Documents\Arduino\libraries\i2c_t3
 Not used: C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\i2c_t3
Error compiling for board Teensy 3.2 / 3.1.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The key issue is this:

In file included from C:\Users\Peter\Documents\Arduino\TeensyTutorials\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect.ino:108:0:

C:\Users\Peter\Documents\Arduino\libraries\i2c_t3/i2c_t3.h: At global scope:

C:\Users\Peter\Documents\Arduino\libraries\i2c_t3/i2c_t3.h:994:15: error: conflicting declaration 'i2c_t3 Wire'

extern i2c_t3 Wire;

^

In file included from C:\Users\Peter\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:0,

from C:\Users\Peter\Documents\Arduino\TeensyTutorials\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect\MPU6050_DMP6_Teensy_FrSkySPort_Temp_HallEffect.ino:98:

C:\Program Files (x86)\Arduino\hardware\teensy\avr\libraries\Wire/Wire.h:104:16: error: 'Wire' has a previous declaration as 'TwoWire Wire'

extern TwoWire Wire;

Because "Wire" is already declared (since it is used by the MPU6050 libraries), the additional declaration of a new "Wire" from i2c_t3 conflicts with it.
Is there any way around this so I can use both i2c_t3 and the MPU6050 library without rewriting one of them? I have tried playing around with this (for example changing the name of "Wire" to something else in i2c_t3) but haven't been able to get it working easily.

Thanks!
pzschulte
 
Did you get this going? You can't have the Arduino Wire and the i2c_t3 library active on the same Teensy at the same time. They just can't share the hardware. So use i2c_t3. It has Wire-compatible methods so it should just work.

I do the following to deconflict whether code is using the Teensy i2c_t3 or Wire library, in my .h files:
Code:
// include this only one time
#ifndef PCA9557_H_
#define PCA9557_H_

#include <Arduino.h>

// Include the lowest level I2C library
#if defined (__MK20DX256__) || defined (__MK20DX128__) 	// Teensy 3.1 or 3.2 || Teensy 3.0
#include <i2c_t3.h>		
#else
#include <Wire.h>	// for AVR I2C library
#endif

// rest of .h file 

#endif	// PCA9557_H_
 
Did you get this going? You can't have the Arduino Wire and the i2c_t3 library active on the same Teensy at the same time. They just can't share the hardware. So use i2c_t3. It has Wire-compatible methods so it should just work.

Thanks bboyes, I did figure out that part; I just use i2c_t3 with the other Wire libraries now. Have had some time to work on this in the last few weeks but haven't finalized it. Have moved over to this thread:
https://forum.pjrc.com/threads/21680-New-I2C-library-for-Teensy3/page23
 
Status
Not open for further replies.
Back
Top