If Device is Not Found, Ignore it

I noticed recently that if my compass module is not connected the serial monitor just continues to print that it can’t find the compass and ignores the rest of the code. I think this is the code I am using for the Compass part of my Arduino code. Is there a way to make it so that if I have the Compass module disconnected for testing other devices or if I just in the future decide not to use the compass that the code will ignore it if it does not detect it?
Not sure how to go about that so any help would be apreciated.

#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;
int error = 0;

void setup()
{
Serial.begin(9600);

Serial.println(“Starting the I2C interface.”);
Wire.begin();

Serial.println(“Constructing new HMC5883L”);
compass = HMC5883L();

Serial.println(“Setting scale to +/- 1.3 Ga”);
error = compass.SetScale(1.3); // Set the scale of the compass.
if(error != 0) // If there is an error, print it out.
Serial.println(compass.GetErrorText(error));

Serial.println(“Setting measurement mode to continous.”);
error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode to Continuous
if(error != 0) // If there is an error, print it out.
Serial.println(compass.GetErrorText(error));

pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
}

void loop()
{
// Retrive the raw values from the compass (not scaled).
MagnetometerRaw raw = compass.ReadRawAxis();
// Retrived the scaled values from the compass (scaled to the configured scale).
MagnetometerScaled scaled = compass.ReadScaledAxis();

// Values are accessed like so:
int MilliGauss_OnThe_XAxis = scaled.XAxis;// (or YAxis, or ZAxis)

// Calculate heading when the magnetometer is level, then correct for signs of axis.
float heading = atan2(scaled.YAxis, scaled.XAxis);

// Once you have your heading, you must then add your ‘Declination Angle’, which is the ‘Error’ of the magnetic field in your location.
// Find yours here: http://www.magnetic-declination.com/
float declinationAngle = -0.1742;
heading += declinationAngle;

// Correct for when signs are reversed.
if(heading < 0)
heading += 2*PI;

// Check for wrap due to addition of declination.
if(heading > 2*PI)
heading -= 2*PI;

// Convert radians to degrees for readability.
float headingDegrees = heading * 180/M_PI;

//Light North LED
if(headingDegrees > 325 or headingDegrees < 45)
{
digitalWrite(13, HIGH);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}

//Light South LED
if(headingDegrees > 135 and headingDegrees < 225)
{
digitalWrite(13, LOW);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
}

//Light West LED
if(headingDegrees > 225 and headingDegrees < 325)
{
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}

//Light East LED
if (headingDegrees > 45 and headingDegrees < 135)
{
digitalWrite(13, LOW);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
}

Output(raw, scaled, heading, headingDegrees);
}

void Output(MagnetometerRaw raw, MagnetometerScaled scaled, float heading, float headingDegrees)
{
Serial.print(headingDegrees);
Serial.println(” Degrees \t”);
}

(deleted)

The 'error' variable is global so when the sketch finishes setup() the value of 'error', set in setup(), will carry into loop. Only run the code for the compass if the value of error is 0.

void loop()
{
   if(error == 0)
   {
      // run compass code
   }
// other code
}

groundfungus:
The 'error' variable is global so when the sketch finishes setup() the value of 'error', set in setup(), will carry into loop. Only run the code for the compass if the value of error is 0.

void loop()

{
  if(error == 0)
  {
     // run compass code
  }
// other code
}

Thanks I stand corrected I got my test code mixed up with the one I'm using, the void setup in the one i'm using is like this... sorry for the confusion. :wink:

void setup()
{
  //Serial.begin (9600);
  Serial.begin (115200);
  Serial.setTimeout(13); //Added today Sun Nov 22 ( not sure if this is needed? )
 
 // Serial.println("Dallas Temperature Control Library Demo - TwoPin_DS18B20");
 
  sensor_incar.begin();

  // Initialize Initialize HMC5883L
  Serial.println("Initialize HMC5883L");
  while (!compass.begin())
  {
    Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
    delay(500);
  }

  
  // Set measurement range
  compass.setRange(HMC5883L_RANGE_1_3GA);

  // Set measurement mode
  compass.setMeasurementMode(HMC5883L_CONTINOUS);

  // Set data rate
  compass.setDataRate(HMC5883L_DATARATE_30HZ);

  // Set number of samples averaged
  compass.setSamples(HMC5883L_SAMPLES_8);

  // Set calibration offset. See HMC5883L_calibration.ino
  compass.setOffset(27, -109);

It's not a void setup, it is the setup function (that returns nothing, void==nothing).

In the snippet that was supplied, it appears that compass.begin() is equivalent to the error variable being zero for the purpose of determining whether the compass is present. However, I could be reasoning incorrectly from incomplete code.

Then you could use a flag like spycatcher2k said.

Declare a global flag, assign the flag the value false (not set)

If compass.begin() returns 0, do the compass setup stuff
else (compass.begin returns non zero) set the flag to true and print the error message

in loop, only run the compass code if the flag is false (not set).

I was little hesitant to post the entire code because with all the extra stuff it's pretty complicated.... well to me anyways and I get lost in it a lot :wink:

I can understand your hesitancy, but key elements (like the include statements and the declarations of compass and sensor_incar) get left out that way. For example, we can't tell if variables are local, global, or undeclared.

It is better to post the whole thing and provide a description.

(deleted)

vaj4088:
I can understand your hesitancy, but key elements (like the include statements and the declarations of compass and sensor_incar) get left out that way. For example, we can't tell if variables are local, global, or undeclared.

It is better to post the whole thing and provide a description.

Thanks I did try posting it yesterday but it keeps telling me it exceeded the character limit. :frowning:

spycatcher2k:
you could also wrap them in a #ifdef, and #define at the top of your sketch.

Thanks, I've not heard of that so I have no idea how to use that, code is not really my specialty :wink:

Knightriderguy:
Thanks, I've not heard of that so I have no idea how to use that, code is not really my specialty :wink:

When I don't know how to use something like that, I google it.

aarg:
When I don't know how to use something like that, I google it.

true enough.... but sometime google is about as helpful as a sledge hammer to the face lol :wink: