My sketch is supposed to calculate the total time used for all assigned tasks and wait until a fixed amount of time has passed before proceeding to start all over again; I calculated in Microseconds how much time total was used as follows. Example Total Time: time used reading a sensor+ time a fan was on + time a door was open... The time allowed to complete all tasks is 300 milliseconds. Sometimes, some jobs don't need to be done, for whatever reason, so time is not used for that job. Most of the time I have unused time; I intended to use the time leftover inside a loop until the 300 milliseconds were up. I haven't being successful. I am going nuts at the moment; I created a billion time variables and I wonder if anyone can give me a hand. Using either microseconds and/or milliseconds is fine. I created couple variables just to see how they helped me, so any variable can be discarded if that's the case. This is my code so far. Sorry about not a clean code
.....
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13
}
uint32_t lastTime = 0L;
int lineCounter = 0;
void loop() {
while (lineCounter <= 4500) {
Serial.print(lineCounter);
Serial.print(" ");
uint32_t currentTime = millis(); // Current time, milliseconds
Serial.print(currentTime = micros());
for (i = 0; i < CHANNEL_COUNT; i++)
{
//Do Something One
}
for (bitNumber = 0; bitNumber < totalBits; bitNumber++) {
//Do something Two
}
for (i = 0; i < CHANNEL_COUNT; i++) {
//Do something Three
}.....
Serial.print(" - ");
Serial.print(lastTime);
Serial.print(" = ");
Serial.print((currentTime - lastTime));
uint32_t timeUsed = currentTime - lastTime;
uint32_t timeRemain = 30000L - timeUsed;
Serial.print(" Remain Time= ");
Serial.print(timeRemain);
uint32_t timeNow = micros();
uint32_t timeCounter = micros();
Serial.print(" Time Now= ");
Serial.print(timeNow );
Serial.print(" math = ");
Serial.println(timeNow - lastTime );
while (timeCounter < timeRemain ) {
timeCounter = timeCounter + (timeNow = micros());
Serial.println("Inside loop");
}
timeCounter = 0;
lastTime = currentTime;
lineCounter++;
}
}