How to multi-task

Hi :slight_smile: ,

How do I run multiple tasks in Arduino? I tried with a multiplexer 1838HXL (74hc595) via this link but without success! Then I tried with the millis() function by following this [link] (Faire plusieurs choses à la fois avec une carte Arduino | Carnet du maker - L'esprit Do It Yourself) but I doubt the reliability of the data since I connect to analog, I could very well not connect my sensor and still have a result in console. Can you tell me what you think?

int LED1 = 12;
int LED2 = 11;
int buzzer = 10;
int sensorThreshold = 400;

void setup(){
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(buzzer, OUTPUT);
  
  Serial.begin(9600);
  pinMode(A0, INPUT);
}

void loop(){
  task_MQ2();
  task_MQ3();
  task_MQ4();
  task_MQ5();
}

void task_MQ2(){
  int analogSensor = analogRead(A0);
  Serial.print("Pin A0/MQ2: ");
  Serial.println(analogSensor);
  
  if (analogSensor > sensorThreshold)
  {
    digitalWrite(LED1, HIGH);
    digitalWrite(LED2, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, HIGH);
    noTone(buzzer);
  }
  delay(500);
}

void task_MQ3() {
  int analogSensor = analogRead(A1);
  Serial.print("Pin A1/MQ3: ");
  Serial.println(analogSensor);
  delay(500);
}

void task_MQ4() {
  int analogSensor = analogRead(A2);
  Serial.print("Pin A2/MQ4: ");
  Serial.println(analogSensor);
  delay(500);
}

void task_MQ5() {
  int analogSensor = analogRead(A3);
  Serial.print("Pin A3/MQ5: ");
  Serial.println(analogSensor);
  delay(500);
}

...
Pin A0/MQ2: 322
Pin A1/MQ3: 314
Pin A2/MQ4: 480
Pin A3/MQ4: 544
Pin A0/MQ2: 322
Pin A1/MQ3: 313
Pin A2/MQ4: 480
Pin A3/MQ4: 544
Pin A0/MQ2: 322
Pin A1/MQ3: 313
Pin A2/MQ4: 480
Pin A3/MQ4: 544
Pin A0/MQ2: 322
Pin A1/MQ3: 313
Pin A2/MQ4: 480
Pin A3/MQ4: 543
Pin A0/MQ2: 323
...

What do you perceive the problem to be?

1 Like

circuit in series rather than in parallel

I'm sorry, in your original post, you said "without success".
What did that refer to?

1 Like

That's the proper approach. However, delays shouldn't be used. Used millis() to schedule the running inside the functions.

1 Like
void task_MQ3() {
  static unsigned long timeStamp = 0;

  if (millis() - timeStamp >= 500) {
  timeStamp += 500;
  int analogSensor = analogRead(A1);
  Serial.print("Pin A1/MQ3: ");
  Serial.println(analogSensor);
  }
}
1 Like

Ok I will use millis()

I have no other problem so I put this topic as solved

ps. @ TheMemberFormerlyKnownAsAWOL in my first idea, I failed to use un MUX (multiplexer 1838HXL | 74hc595) I didn't understand how it works

Thanks

True. a 74HC595 is not a multiplexer.

1 Like