#define led 13 enum {sample_state,high_state,low_state}; //Enumerate(give values to) the variables so they are 0,1,2 respectivly unsigned int state=sample_state; unsigned int val1,val2,val3,mVal,hiVal,loVal; unsigned int timer; /*----------------------------------------Main loop--------------------------------------*/ void setup() { Serial.begin(115200); pinMode(13,OUTPUT); } void loop() { switch(state){ //There are 3 different states that take place, take sample from inputs, set high duration, set low duration case sample_state: val1 = analogRead(pwmPin); val2 = 1023 -analogRead(pwmPin); val3 = analogRead(freqPin); mVal = map(Val3,0,1023,60,2000); //Mapped from 60-2000millisec hiVal = map(Val1,0,1023,0,mVal); loVal = map(Val2,0,1023,0,mVal) +1; bpm = (2000 / mVal) * tempoMin; // tempoMin = 30 Serial.print(bpm); state=high_state; //We have inputs, next we go on to high state mode digitalWrite(led,HIGH); //Set the pin high as the next state is just a timer timer=millis(); //Set timer to the time when this code block finishes break; case high_state: if(millis()>=timer+hiVal){ //Sit in this state until the timer threashold reaches the end of the high state state=state_low; //Move on to low state tmer digitalWrite(led,LOW); //Set pin low timer=millis(); //Reset timer } break; case low_state: if(millis()>=timer+loVal){ //Sit in this state until the timer threashold reaches end of the low state state=state_sample; //Cycle completed, go back to taking a new sample and repeat cycle } break; default: //This should never happen Serial.println("state variable not valid"); while(1); break; } //The rest of your code can go here and will be executed every loop cycle }