How to modify this program to set a fixed time for running motor without repeat

Hi every one

I am new to Arduino and could make a project with an UNO board to turn a dc motor left and right but according the programming style, the 0 should be dialed to turn off the motor any time the motor is turned right or left by dialing 1 and 2 but I would like to know how to modify the program or using a new recommended program that can enable me set a fixed time for running dc motor without needing to dial 0 to stop turning.

I hereby send the complete code for you study and assistance.

Appreciated your advise in advance

Regards

  • Control DC motor with Smartphone via bluetooth

  • 2013

*/

int motorPin1 = 3; // pin 2 on L293D IC

int motorPin2 = 4; // pin 7 on L293D IC

int enablePin = 5; // pin 1 on L293D IC

int state;

int flag=0; //makes sure that the serial only prints once the state

void setup() {

// sets the pins as outputs:

pinMode(motorPin1, OUTPUT);

pinMode(motorPin2, OUTPUT);

pinMode(enablePin, OUTPUT);

// sets enablePin high so that motor can turn on:

digitalWrite(enablePin, HIGH);

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

void loop() {

//if some date is sent, reads it and saves in state

if(Serial.available() > 0){

state = Serial.read();

flag=0;

}

// if the state is '0' the DC motor will turn off

if (state == '0') {

digitalWrite(motorPin1, LOW); // set pin 2 on L293D low

digitalWrite(motorPin2, LOW); // set pin 7 on L293D low

if(flag == 0){

Serial.println("Motor: off");

flag=1;

}

}

// if the state is '1' the motor will turn right

else if (state == '1') {

digitalWrite(motorPin1, LOW); // set pin 2 on L293D low

digitalWrite(motorPin2, HIGH); // set pin 7 on L293D high

if(flag == 0){

Serial.println("Motor: right");

flag=1;

}

}

// if the state is '2' the motor will turn left

else if (state == '2') {

digitalWrite(motorPin1, HIGH); // set pin 2 on L293D high

digitalWrite(motorPin2, LOW); // set pin 7 on L293D low

if(flag == 0){

Serial.println("Motor: left");

flag=1;

}

}

}

Just put your motor's if commands in the englobing "if something is available on the serial port"

==> there is no point keeping repeating the orders to the motor. You press 1, you turn left and you keep things spinning that way (why set again motorPin1 or motorPin2 to HIGH or LOW they are already there and won't change by magic) until you receive a command on Serial or timeout

This way you don't need your state variable for printing once (because the orders will only get executed once per key press) but you need to memorize if you are turning (use a boolean, call it isTurning, and set it to true when you receive 1 and 2 and false when you receive 0). In the code where now you only run ONCE the order to turn, you memorize in a global unsigned long variable lastTurnTime the values of millis()

Then after the testing block for the serial command, you do test if timeout has occurred

if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {
    // we are turning for too long
    ..... // stop the turn movement
     isTurning = false;  // Remember our new state
}

So overall your code structure looks like this

// declare and initialize variables
...

void setup()
{
  ...
}

void loop()
{
    if(Serial.available() > 0) { 
        command = Serial.read(); // read the command
        
        // handle the command (with switch or nested if/else as you were doing)
        switch (command) {
            case '0': // stop
                ....
                isTurning = false;
                break;

            case '1': // right
                 ....
                  isTurning = true;
                  lastTurnTime = millis();
                  break;

             case '2'; // left
                  ....
                  
        } // end switch
   } // end if something on Serial to check

   if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {
    // we are turning for too long
    ..... // stop the turn movement
     isTurning = false;  // Remember our new state
   } // end if timeout
}

Give it a try, and post your new code but press ctrl-T (or cmd-T on a Mac) to indent the code first and use the code tags so that it is posted properly in the forum (should be in a code box like code I posted above)

Thanks for your advise but the result is as below when i applied to upload your program

Arduino: 1.6.12 (Windows XP), Board: "Arduino/Genuino Uno"

Build options changed, rebuilding all
delay7:2: error: expected unqualified-id before '...' token

...

^

G:\LOCK\Transivers\Bluetooth\arduino\delay7\delay7.ino: In function 'void setup()':

delay7:6: error: expected primary-expression before '...' token

...

^

G:\LOCK\Transivers\Bluetooth\arduino\delay7\delay7.ino: In function 'void loop()':

delay7:12: error: 'command' was not declared in this scope

command = Serial.read(); // read the command

^

delay7:17: error: expected primary-expression before '...' token

....

^

delay7:22: error: expected primary-expression before '...' token

....

^

delay7:24: error: 'lastTurnTime' was not declared in this scope

lastTurnTime = millis();

^

delay7:27: error: expected ':' before ';' token

case '2'; // left

^

delay7:28: error: expected primary-expression before '...' token

....

^

delay7:33: error: 'isTurning' was not declared in this scope

if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {

^

delay7:33: error: 'lastTurnTime' was not declared in this scope

if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {

^

delay7:33: error: 'MAXTURNINGTIME' was not declared in this scope

if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {

^

delay7:35: error: expected primary-expression before '...' token

..... // stop the turn movement

^

exit status 1
expected unqualified-id before '...' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Post the code as it is now.

what is the code I should post? may you write the complete code that i can upload and test

motorlock:
what is the code I should post?

Your new code. The code that gave you the errors.

But as you saw, I got the error while I tried to upload it. please advise with thanks

I got the error while I tried to upload it.

But we don't know what you uploaded.

This is what I uploaded and got that error. please advise and send me complete code if I did it wrongly. Appreciated your assistance and time.

// declare and initialize variables
...

void setup()
{
...
}

void loop()
{
if(Serial.available() > 0) {
command = Serial.read(); // read the command

// handle the command (with switch or nested if/else as you were doing)
switch (command) {
case '0': // stop
....
isTurning = false;
break;

case '1': // right
....
isTurning = true;
lastTurnTime = millis();
break;

case '2'; // left
....

} // end switch
} // end if something on Serial to check

if (isTurning && (millis() - lastTurnTime >= MAXTURNINGTIME)) {
// we are turning for too long
..... // stop the turn movement
isTurning = false; // Remember our new state
} // end if timeout
}

What happened to initialising variables, the content of the setup() function and multiple instances where ... indicates that you need to insert your own code ?

The code in reply #1 was a suggestion for the code structure not the complete code.

Thanks for your advise but as I already told, I am new with this codes and although during past few days I googled several solutions but I could not do the job since I was not familiar wit the code, so as you can see I put here above the code which i am now using and work but without the time limit, so although bi hereby re-write the code here what i am using, but hope you can send me the complete modified code that I should exactly upload that for example after dialing 1 or 2 for turning the motor right and left, the motor stop automatically after 5 seconds without needing to dial 0 to turn the motor off. Thanks and appreciate

  • Control DC motor with Smartphone via bluetooth

  • 2013

*/

int motorPin1 = 3; // pin 2 on L293D IC

int motorPin2 = 4; // pin 7 on L293D IC

int enablePin = 5; // pin 1 on L293D IC

int state;

int flag=0; //makes sure that the serial only prints once the state

void setup() {

// sets the pins as outputs:

pinMode(motorPin1, OUTPUT);

pinMode(motorPin2, OUTPUT);

pinMode(enablePin, OUTPUT);

// sets enablePin high so that motor can turn on:

digitalWrite(enablePin, HIGH);

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

void loop() {

//if some date is sent, reads it and saves in state

if(Serial.available() > 0){

state = Serial.read();

flag=0;

}

// if the state is '0' the DC motor will turn off

if (state == '0') {

digitalWrite(motorPin1, LOW); // set pin 2 on L293D low

digitalWrite(motorPin2, LOW); // set pin 7 on L293D low

if(flag == 0){

Serial.println("Motor: off");

flag=1;

}

}

// if the state is '1' the motor will turn right

else if (state == '1') {

digitalWrite(motorPin1, LOW); // set pin 2 on L293D low

digitalWrite(motorPin2, HIGH); // set pin 7 on L293D high

if(flag == 0){

Serial.println("Motor: right");

flag=1;

}

}

// if the state is '2' the motor will turn left

else if (state == '2') {

digitalWrite(motorPin1, HIGH); // set pin 2 on L293D high

digitalWrite(motorPin2, LOW); // set pin 7 on L293D low

if(flag == 0){

Serial.println("Motor: left");

flag=1;

}

}

}

OK I did mot understand you were starting from that far to not understand that "...." means put relevant code here...

Put your project aside for a couple week and start by the basis. Go read about C programming and study basic arduino examples. Then you'll be ready for tackling that one.

Thanks but may I ask you modify and send the current code I sent you above for once that it can turn off the motor after 5 seconds any time we dial 1 and 2 without needing to dial 0 that i can try it before I go for your suggestion? thanks

You did not even look up how to use code tags to properly use the forum...

You have all the tools to do it yourself. This forum is for learning. Give it a try.

Again - my suggestion is Put your project aside for a couple week and start by the basis. Go read about C programming and study basic arduino examples. Then you'll be ready for tackling that one.

No pain, no gain.

I not only looked it up carefully but you saw I even tried to upload it on my board quickly, so i believe I did all my best and just hoped you, as a professional in this codes can send me the modified code what you suggested after you saw I am not familiar with the code as per as what I honestly informed at the beginning.

We have a proverb that says, not knowing is not bad issue but not asking is a very bad issue, so I asked you what I did not know but you did not follow your help until the end.

Anyway, thanks for your time and hope some one else here in this forum can send the complete modified code if this is hard for you to do.

Regards

Well first of all we have all been beginners. There is nothing wrong with it.

Let me be honest:

Some beginners come here to learn and some other come just to get their homework or experiment done by someone else and they show no interest in investing the time, energy, intellectual power for learning;

I'm happy to help people willing and demonstrating their willingness to learn, the curious minds, the explorers, the tinkerers - and thus modestly contribute to build the next generation supporting the forum and possibly help younger generation embrace a software engineering career.

But I don't see much value in investing my personal time to develop code for people not interested in the art of programing, unless it's a charitable action for someone needing help to build something where he also gives away his personal time for the greater good.

Does not feel that way here, May be some kind soul has a different opinion.

Hope this makes sense, nothing personal.

We have a proverb

We have a proverb too

Give a man a fish and you have fed him for one day
Teach a man to fish and you have fed him for ever

You are being offered the second option. Are you interested in learning or just want a program that works without perhaps even understanding how or why ?

As I already explained, during past few days, i spent more time to googled the information about this issue and maybe more than 100 times I re-programmed the device according to what i could find and I believe this is more than what you can even imagine but at this time I feel tired and I just need to see how that works

I could do many thing with this board until now to make it workable but I am not an electronic expert and i believe even connecting the board, IC, uploading, etc in this project was a good job for me for the first time because although i was completely new to this project but I could do it by study several pages on the net that the project can work now but this is not under my control if i can not understand your electronic language.

Anyway, this is up to you to provide me the code or not but I trust i did my best.

Regards

Let's go with a few quizzes then

How would you declare a variable of type unsigned long, by the name of lastTurnTime

How would you declare a constant value by the name MAXTURNINGTIME and initialize it at 5 seconds, expressed in milliseconds?

Can you write 3 functions

void turnRight() that makes the motor turn right?
void turnLeft() that makes the motor turn left?
void stop() that makes the motor stop?

Here is a hint for the function to make the motor turn right

void turnRight()
{
   digitalWrite(motorPin1, LOW);
   digitalWrite(motorPin2, HIGH);
}

--> please provide this.


Please correct your post above and add code tags around your code:
[code]`` [color=blue]// your code is here[/color] ``[/code].

It should look like this:// your code is here
(Also press ctrl-T (PC) or cmd-T (Mac) in the IDE before copying to indent your code properly)

Thanks for your time but where is the code that you wrote above // YOUR CODE IS HERE?

I can not understand it before you write the complete ready to upload code that I can compare with what I already used to recognize what you tried to teach me, so please send the complete code or forget it because this method of corresponding waste yours and my time.

I hoped I can reach my answer here after several days googling but, seems this is ....

Regards