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:
Here is the Master code that collects the data successfully using I2C_Anything:
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):
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==================");
}