I wanted to use millis for the code below but stuck in between . can anyone help to change the given code to millis? Code here:

    void set(){
    digitalWrite(on, HIGH);   // turn the motor on (HIGH is the voltage level)
  digitalWrite(on, LOW);    
  delay(ont);               //waits for given time
  digitalWrite(off, HIGH );    // stop the motor
  digitalWrite(off, LOW );      
  delay(offt);                  //wait for different
  • 1
    See arduino.cc/en/tutorial/BlinkWithoutDelay I see four different things. Use a counter from 0...3 and adjust the interval for each of the four situations. Can you give that a try and show a working sketch (so we can try your sketch). Do you have different pins for turning the motor on and off? – Jot Jan 31 at 7:48

Here is the code for changing pin value without delay. Read it and try it.

#define on 2
#define off 3

//delay times
const unsigned int ont = {1500,  500};
const unsigned int offt = {500, 300};

//last millis
unsigned long last_tm_on = 0;
unsigned long last_tm_off = 0;

byte pos_on = 0;
byte pos_off = 0;

void setup(){
  pinMode(on, OUTPUT);
  pinMode(off, OUTPUT);

void loop(){
  if(millis() - last_tm_on >= ont[pos_on]){   //check if millis() - last millis() is bigger than wanted time
    last_tm_on = millis();   //save last millis() 
      if(pos_on == 0) digitalWrite(on, HIGH); 
      if(pos_on == 1) digitalWrite(on, LOW);    

      pos_on ++;   //add position
      if(pos_on > 1) pos_on = 0;   //check max position 

 if(millis() - last_tm_off >= offt[pos_off]){
    last_tm_off = millis();
      if(pos_off == 0) digitalWrite(off, HIGH);   // turn the motor on (HIGH is the voltage level)
      if(pos_off == 1) digitalWrite(off, LOW);    

      pos_off ++;
      if(pos_off > 1) pos_off = 0;
  • Matej, there is only one motor and you have two independent software timers with millis. – Jot Jan 31 at 20:38
  • @Jot I thought, that on is one motor and off second. Lol – Matej Jan 31 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.