arduinoatmel

Not able to multitask in Arduino


I've been trying to multi-task in Arduino but my code just prints the 'pHValue'. I'm not using delay() anywhere in the code. Any help would be highly appreciated.

void loop(void) {
  unsigned long currentTime = millis();
  int pHValue = readPH();

  if (currentTime - prevTime > 50) {
    Serial.println(pHValue);
    prevTime = currentTime;
  }

  
  if(currentTime - prevTime > 100) {
    Serial.println("I got printed");
    prevTime = currentTime;
  }
}

Solution

  • For two independent cycles you need two state variables

    unsigned long prevVal; // Value printing cycle
    unsigned long prevMsg; // Message printing cycle
    
    void loop(void) {
      unsigned long currentTime = millis();
      int pHValue = readPH();
    
      if (currentTime - prevVal > 50) {
        Serial.println(pHValue);
        prevVal = currentTime;
      }
    
      
      if(currentTime - prevMsg > 100) {
        Serial.println("I got printed");
        prevMsg = currentTime;
      }
    }
    

    If the cycles are not independent, (e.g. 100 is twice 50 ) you could do other tricks, but there's no reason or advantage here, I guess