Help controlling two functions at once, understanding millis

Hello,

I am trying to use an arduino to control a solenoid and a hall effect sensor. The solenoid is meant to go up and down at a certain interval, such as 5 seconds. At the same time, I want the hall effect sensor to read values from a magnet every second. I have two working codes for each the solenoid and the hall effect sensor. Is there a way to make these run simultaneously using millis as a timer?

Here are my codes:

Solenoid:

int solenoid = 13;

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

  pinMode(solenoid, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(solenoid, HIGH);
  delay(5000);
  digitalWrite(solenoid, LOW);
  delay(5000);

}

Hall Effect:

int TOMILLIGAUSS = 977;
int NOFIELD = 507;


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

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() 
{
    //Takes measurements from the Hall effect sensor every second
    delay(1000);
    DoMeasurement();
}

Have a look at the blink without delay example in the IDE for clues.

On any given pass through loop(), it may be time to change the state of the solenoid. What would that decision be based on? Seems to me like you'd need to know when the solenoid last changed state (as millis() will tell you) and how long the solenoid should be in the current state.

On any given pass through loop(), it may be time to read the hall effect sensor. It seems to be like EVERY time through loop(), you'd want to read that sensor. Frankly, I can't see why you stick your head in the sand for ANY length of time.

If you can explain THAT, adapting the blink without delay tactics to reading the hall effect sensor will be trivial, just as adapting the tactics to writing to the solenoid will be.

Have a look at the demo Several Things at a Time which uses millis() to manage timing.

...R