Hi everyone I have a project and I need to run a dc motor for amount of time without using delay I use DelayWithoutBlink technique. In this code the motor should run for 5 second in cw then it will change the direction it will other 5second in ccw direction but it seems that there is something wrong with my code, any help would be greatly appreciated.

unsigned long timeRun = 5000;
boolean choiceOne = false;
boolean choiceTwo = false;
boolean directionOne;
boolean directionTwo;
unsigned long timeRunOne;
unsigned long timeRunTwo;

void setup() {
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

void loop() {
    char t = Serial.read();
    if (t == 'a') {
        while (choiceOne == false) {
            digitalWrite(9, HIGH);
            digitalWrite(8, LOW);
            directionOne = true;
            timeRunOne = millis();
            if (directionOne && (millis()-timeRunOne > timeRun)) {
                choiceOne = true;
    if (t == 'b') {
        while (choiceTwo == false) {
            digitalWrite(9, LOW);
            digitalWrite(8, HIGH);
            timeRunTwo = millis();
            directionTwo = true;
            if (directionTwo && (millis()-timeRunTwo > timeRun)) {
                choiceTwo = true;
  • 1
    I wonder if you understand the concept of blink without delay. Because your code still has delay. The whole point is that without the delay the loop can run really really fast over and over and will catch when it is time to do things. Once you introduce a while loop you have broken that because now loop cannot finish and repeat fast, it has to wait for that while loop.
    – Delta_G
    Aug 2 '20 at 20:08
  • When you do this right there will be no while and no delay. The code will read like, if the motor is on and it's time to turn it of then turn it off. Else if it is off and time to turn it on, check which direction it should be and turn it on
    – Delta_G
    Aug 2 '20 at 20:08
  • You also need to brush up on the difference between = and ==. Google that one.
    – Delta_G
    Aug 2 '20 at 20:09
  • ok I will delete delay
    – yo777
    Aug 2 '20 at 20:16
  • 1
    1. In the question you talk about the direction changing automatically, yet in the code it is controlled by the serial port. What gives? 2. There are too many variables in your program. When you have so many booleans, chances are you really need a finite state machine. Also, the variables directionOne and directionTwo serve no purpose, as they are always true when you read them. Aug 3 '20 at 12:33

Your Answer

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

Browse other questions tagged or ask your own question.