Help controlling two functions at once, understanding millis


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:


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);
  digitalWrite(solenoid, LOW);


Hall Effect:

int NOFIELD = 507;

void setup() 

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: ");

  long compensated = raw - NOFIELD;                 // adjust relative to no applied field 
  long gauss = compensated * TOMILLIGAUSS; // 1000;   // adjust scale to 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

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.