I'm a C++ / Arduino newbie, trying to build a custom library for the first time. I created a unit called CDSensors.cpp
, which has two methods, SetupSensor
and ReadSensors
. The sensor is a SparkFun accelerometer/magnetometer.
If there are any errors in the settings, the sensor returns all zeros for compass and accelerometer. If there is no pointer or other connection between the SetupSensor
and ReadSensor
methods, the sensor returns all zeros as if it hasn't been setup.
So I'm trying to pass a reference to the sensor library between the methods as shown with the Limu object in the code below. I now get mag data but the accelerometer returns all zeros so something in my object references is messing with the sensor setup? (the accelerometer works ok in the SparkFun demo code, on which my code is based).
Main.ino
#include <CDSensors.h>
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>
CDSensors* LSensors = &CDSensors (0);
CDSerialPrint* LSerialPrint = &CDSerialPrint (0);
MPU9250_DMP Limu = MPU9250_DMP ();
unsigned long LTimeNow = 0;
struct meas {
int BUx;
int acc_x
};
struct meas r;
void setup() {
LSensors->SetupSensors (Limu);
}
void loop() {
LSensors->ReadSensors (Limu, LTimeNow, r.BUx, r.acc_x);
Serial.print((int) (r.BUx) );
Serial.print((int) (r.acc_x) );
}
CDSensors.h
#ifndef CDSensors_h_h
#define CDSensors_h
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>
class CDSensors {
public:
CDSensors(int);
static void SetupSensors(MPU9250_DMP *imu);
void ReadSensors (MPU9250_DMP *imu, unsigned long& TimeNow, int& BUx,int& BUy,int& BUz,int& acc_x,int& acc_y,int& acc_z,int& a0,int& a1,int& a2,int& a3 );
private:
int value;
};
#endif
CDSensors.cpp
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>
#include "CDSensors.h"
//MPU9250_DMP imu;
boolean MPU9250_found = false;
unsigned long TimeNow = 0;
CDSensors::CDSensors(int givenValue) {
value = givenValue;
}
static void CDSensors::SetupSensors(MPU9250_DMP imu) {
if (imu.begin() != INV_SUCCESS) {
while (1) {
Serial.println("No MPU-9250 found, Check connections");
delay(5000);
}
}
imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
imu.setGyroFSR(2000);
imu.setAccelFSR(2);
imu.setLPF(188);
imu.setSampleRate(100);
imu.setCompassSampleRate(100);
}
void CDSensors::ReadSensors(MPU9250_DMP imu, unsigned long& TimeNow, int& BUx, int& acc_x) {
TimeNow = millis();
if (imu.dataReady()) {
imu.update(UPDATE_ACCEL | UPDATE_GYRO | UPDATE_COMPASS);
}
BUx = imu.calcMag(imu.mx);
acc_x = imu.calcAccel(imu.ax);
}
MPU9250_DMP
outside of your class and in your main sketch? If you declare it inside of the class as a member variable you can ditch the reference handling – chrisl May 5 '18 at 18:29MPU9250_DMP& imu
, to the SetupSensors and ReadSensors member functions. – Mikael Patel May 6 '18 at 11:31