Help implementing a stop for a solenoid based on the reading of another sensor.

Hello all,

So I have a solenoid that I'm turning on and off using Arduino. I also have a Hall effect sensor that is reading positioning. What I want to do is turn the solenoid permanently off if the piston moves past a certain point.

I already have the solenoid and hall effect sensor working, I just need to implement the last part.

I am trying to get it to work by adding another if statement that is added in as a comment. I'm wondering if this is the best way to do this or if there is another approach I should go with.

Thanks!

#include "HX711.h"

#define calibration_factor -11440.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define DOUT  3
#define CLK  2

HX711 scale(DOUT, CLK);

int solenoid = 13;
int TOMILLIGAUSS = 977;
int NOFIELD = 507;

const unsigned long solenoidInterval = 4500;
const unsigned long hallInterval = 200;

unsigned long solenoidTimer = 0;
unsigned long hallTimer = 0;

int solenoidState = LOW;

void setup() {
  // put your setup code here, to run once:

  pinMode(solenoid, OUTPUT);
  solenoidTimer = millis();
  hallTimer = millis();
  
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.set_scale(-11440.0); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare();  //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");
}

void DoMeasurement()
{
// measure magnetic field
  int raw = analogRead(0);   // Range : 0..1024

//  Uncomment this to get a raw reading for calibration of no-field point
  Serial.print("Raw reading: ");
  Serial.println(raw);

  long compensated = raw - NOFIELD; // adjust relative to no applied field 
  long gauss = compensated * TOMILLIGAUSS; // 1000; // adjust scale to Gauss

  Serial.print(gauss);
  Serial.print(" milliGauss ");

  if (gauss > 0)     Serial.println("(South pole)");
  else if(gauss < 0) Serial.println("(North pole)");
  else               Serial.println();
}

void loop() {
  //DoMeasurement is used to read and print data from the Hall effect sensor
  //Measurements will be taken every second
  if( (millis() - solenoidTimer) >= solenoidInterval) {
   //if statement for if the hall effect reads a certain number or more to stop 
      if (solenoidState == LOW)
      solenoidState = HIGH;
       else
      solenoidState = LOW;

    //Write new state
    digitalWrite(solenoid, solenoidState);

    //Reset timer
    solenoidTimer = millis();
  }

  if( (millis() - hallTimer) >= hallInterval) {
    DoMeasurement();
    hallTimer = millis();
  }

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();