LIS2MDL code ***help request***

Hello folks, I have the majority of the code written that is needed for my project (reading earth magnetic values utilizing the LIS2MDL module).

Backstory: I'll be using this as a magnetometer for subsurface surveying of our farm land, this device will be attached to the rear of our UTV in an electronically isolated manner to help reduce interference from loose EMF.

in the code I wrote for the ERT (Electronic Resistance Tomography) sensor, I was able to add an if/else statement, I had this wired up to a simple switch that allowed me to turn the sensor "off" when I was turning around outside of my grid coordinates. I'm guessing I've done something wrong; as soon as I activate the switch using the code below, the sensor begins reading and doesn't stop unless I power off the board.

Any help is appreciated!

#include <Adafruit_LIS2MDL.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_LIS2MDL lis2mdl = Adafruit_LIS2MDL(12345);
#define LIS2MDL_CLK 13
#define LIS2MDL_MISO 12
#define LIS2MDL_MOSI 11
#define LIS2MDL_CS 10

const int buttonPin = 1;     
const int buttonOut =  3;      
int buttonState = 0;

void setup(void) {

  pinMode(buttonOut, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonOut, HIGH);

  while (!Serial)

  Serial.println("LIS2MDL Magnetometer Test");


  if (!lis2mdl.begin()) {  // I2C mode
    Serial.println("Ooops, no LIS2MDL detected ... Check your wiring!");
    while (1) delay(10);


void loop(void) {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
  sensors_event_t event;
  Serial.print(event.magnetic.z, 15);
  Serial.print("  ");

else {
    Serial.println ("OPEN");


The Serial Tx pin?

...Didn't even realize I did that, which pins would you suggest I use that won't interfere with the operation?

Don't use 10, 11, 12, 13 or 3.
Or 0, obviously.

I tried 2 and 7 - same issue

You have a pull-down resistor on the pin, don't you?

I believe so, using Nano

Why not check?

Well, I've search and can only find that the first couple A pins have pull up not pull down. I'll have to do some more digging to see what else can be done.

All pins except A6 and A7 have built-in pullups; why not use those instead?

I tried 2& 3, as well as commanding the pin mode to be a INPUT_PULLUP and it still doesn't seem to respond, oddly.

Ok, strip it down.
Put that code aside, and concentrate on reading a single input using the built-in pullup

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.