unsigned t1 = 0, t2 = 0, start = 0; int flag = 0, dFlag = 0; int stepperControlPin = 12, directionPin = 11, level = 0; int count = 0; void setup() { // put your setup code here, to run once: pinMode(stepperControlPin,OUTPUT); pinMode(directionPin,OUTPUT); t1 = millis(); start = millis(); digitalWrite(directionPin,LOW); Serial.begin(9600); } void loop() { if (flag == 0){ flag = 1; } t2 = millis(); if (t2 > (start + 4000)){ start = t2; if(dFlag == 0){ digitalWrite(directionPin,HIGH); dFlag = 1; } else{ digitalWrite(directionPin,LOW); dFlag = 0; } } if (t2 > (t1 + 8)){ Serial.println(t2-t1); t1 = millis(); if (level == 1){ digitalWrite(stepperControlPin,HIGH); level = 0; count ++; } else{ digitalWrite(stepperControlPin,LOW); level = 1; } } }