run motor for x time without delay and stop it if button presed

hello,

Im working on a project I have to move the motor for x time when the button is pressed. during this time if the second button is pressed I need to stop the motor immadetly .

#include <Wire.h>
#include "i2c.h"

#include "i2c_MMA8451.h"
MMA8451 mma8451;

int RPWM=5;
int LPWM=6;
int L_EN=7;
int R_EN=8;

  void setPWMfrequency(int freq){
   TCCR0B = TCCR0B & 0b11111000 | freq ;
  }

  void MotorActiveStatus(char Side,boolean s){
    boolean state=s;
    if(Side=='R'){
    digitalWrite(R_EN,s);
    }
    if(Side=='L'){
    digitalWrite(L_EN,s);
    }    
  }
  void setMotor(char side,byte pwm){
   if(side=='R'){
    analogWrite(RPWM,pwm);
   }
    if(side=='L'){
    analogWrite(LPWM,pwm);
   }
  }
  void closeMotor(char side){
     if(side=='R'){
    digitalWrite(RPWM,LOW);
     }
     if(side=='L'){
    digitalWrite(LPWM,LOW);
     }

     }
   void saggit(){
        for(int i=0;i<256;i++){
  setMotor('R',i);
  delay(25);
 
  
}
   }
   void sagdur(){
  for(int i=255;i>0;i--){
  setMotor('R',i);
    delay(25);

  closeMotor('R');
}

}
  
 
      
  void dur(){
  closeMotor('R');
  }

char receivedChar;
boolean newData = false;
      
void setup() {
  // put your setup code here, to run once:
  setPWMfrequency(0x02);// timer 0 , 3.92KHz
  for(int i=5;i<9;i++){
   pinMode(i,OUTPUT);
  }
   for(int i=5;i<9;i++){
   digitalWrite(i,LOW);
  }
   delay(1000);
   MotorActiveStatus('R',true);
   MotorActiveStatus('L',true);
       Serial.begin(115200);

    Serial.print("Probe MMA8451: ");
    if (mma8451.initialize()) Serial.println("Sensor found!");
    else
    {
        Serial.println("Sensor missing");
        while(1) {};
    }
 
  }

float deger=0;
      
void loop() {

 
    recvOneChar();//okuma
    static float xyz_g[3];
    mma8451.getMeasurement(xyz_g);
    deger= (xyz_g[0]);

 if (deger<-1){
  
   setMotor('R',255);
 
 //saggit();
 }
 if (receivedChar == 'b'){ 
 sagdur();
 }
 if (deger>1){
  dur();
 }
 newData = false;

 



Serial.println(deger);




}

void recvOneChar() {
 if (Serial.available() > 0) {
 receivedChar = Serial.read();
 newData = true;
 }
}
unsigned long MotorTimer = 0;
const unsigned long X_Time = 5000;  // Five Seconds

void setup()
{
  pinMode(ButtonPin, INPUT_PULLUP);
   MotorRun();
   MotorTimer = millis();
}

void loop()
{
  if (MotorTimer != 0 && millis() - MotorTimer >= X_Time)
  {
    MotorStop();
    MotorTimer = 0;
  }

  if (digitalRead(ButtonPin) == LOW)
  {
    MotorStop();
    MotorTimer = 0;
  }
}

It would help me to understand your code if you can provide the English equivalent of your function names.

Also, if you use the AutoFormat tool in the Arduino IDE it will lay out your code consistently which makes it much easier to read.

I don't see any code to read a button so I presume you mean that you want to control the motor with characters received by Serial.

If you want a responsive program don't use delay(). The functions delay() and delayMicroseconds() block the Arduino until they complete. Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

If you want the motor to stop after a certain time then save the value of millis() when the motor starts and keep checking for when the time expires. Something like

if (receivedChar == 'B') {   // 'B' for begin - but use any character you like 
   motorStartMillis = millis();
   // call function to make motor start
}

if (millis() - motorStartMillis >= motorRunTime) {
   // call function to make motor stop
}

if (receivedChar == 'E') { // 'E' for end
   // call function to make motor stop
}

...R

I make it english,and cleared the loop part.

I didnt added the buttons yet but I will add 3 button. left right and stop buttons.
when I pressed button 1 it should go to left for 10seconds. if I press the button 2 or the values from my sensor are too big Its need to be stopped.

I am trying to figure how can I do this for 2 days and couldt do it.

#include <Wire.h>
#include "i2c.h"

#include "i2c_MMA8451.h"
MMA8451 mma8451;

int RPWM = 5;
int LPWM = 6;
int L_EN = 7;
int R_EN = 8;

void setPWMfrequency(int freq) {
  TCCR0B = TCCR0B & 0b11111000 | freq ;
}

void MotorActiveStatus(char Side, boolean s) {
  boolean state = s;
  if (Side == 'R') {
    digitalWrite(R_EN, s);
  }
  if (Side == 'L') {
    digitalWrite(L_EN, s);
  }
}


void setMotor(char side, byte pwm) {
  if (side == 'R') {
    analogWrite(RPWM, pwm);
  }
  if (side == 'L') {
    analogWrite(LPWM, pwm);
  }
}


void closeMotor(char side) {
  if (side == 'R') {
    digitalWrite(RPWM, LOW);
  }
  if (side == 'L') {
    digitalWrite(LPWM, LOW);
  }

}


void goright() {

  setMotor('R', 255);

}


void golleft() {

  setMotor('L', 255);
}


void stopmotor() {
  closeMotor('R');
  closeMotor('L');
}

char receivedChar;
boolean newData = false;

void setup() {

  setPWMfrequency(0x02);// timer 0 , 3.92KHz
  for (int i = 5; i < 9; i++) {
    pinMode(i, OUTPUT);
  }
  for (int i = 5; i < 9; i++) {
    digitalWrite(i, LOW);
  }
  delay(1000);
  MotorActiveStatus('R', true);
  MotorActiveStatus('L', true);
  Serial.begin(115200);

  Serial.print("Probe MMA8451: ");
  if (mma8451.initialize()) Serial.println("Sensor found!");
  else
  {
    Serial.println("Sensor missing");
    while (1) {};
  }

}

float value = 0;

void loop() {











  recvOneChar();//read the mma8451sensor
  static float xyz_g[3];
  mma8451.getMeasurement(xyz_g);
  value = (xyz_g[0]);
  Serial.println(value);









}





void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}

gerdal:
I am trying to figure how can I do this for 2 days and couldt do it.

The concept I illustrated in Reply #2 can also be used with buttons - try it and see how you get on.

If you run into a problem please post the program that represents your best attempt and tell us in detail what it actually does and what you want it to do that is different. It will make it much easier to focus on the parts you need help with rather than wasting time on things that you can do.

...R

Robin2:
The concept I illustrated in Reply #2 can also be used with buttons - try it and see how you get on.

If you run into a problem please post the program that represents your best attempt and tell us in detail what it actually does and what you want it to do that is different. It will make it much easier to focus on the parts you need help with rather than wasting time on things that you can do.

...R

Thank you very much I figure it now it works.

when I made time 10000 motor doesnt stop

#include <Wire.h>
#include "i2c.h"

#include "i2c_MMA8451.h"
MMA8451 mma8451;

int RPWM = 5;
int LPWM = 6;
int L_EN = 7;
int R_EN = 8;
unsigned long motorStartMillis = 0;

void setPWMfrequency(int freq) {
  TCCR0B = TCCR0B & 0b11111000 | freq ;
}

void MotorActiveStatus(char Side, boolean s) {
  boolean state = s;
  if (Side == 'R') {
    digitalWrite(R_EN, s);
  }
  if (Side == 'L') {
    digitalWrite(L_EN, s);
  }
}


void setMotor(char side, byte pwm) {
  if (side == 'R') {
    analogWrite(RPWM, pwm);
  }
  if (side == 'L') {
    analogWrite(LPWM, pwm);
  }
}


void closeMotor(char side) {
  if (side == 'R') {
    digitalWrite(RPWM, LOW);
  }
  if (side == 'L') {
    digitalWrite(LPWM, LOW);
  }

}


void goright() {

  setMotor('R', 255);

}
void gorights() {

  setMotor('R', 155);

}


void goleft() {

  setMotor('L', 255);
}
void golefts() {

  setMotor('L', 155);
}

void stopmotor() {
  closeMotor('R');
  closeMotor('L');
}

char receivedChar;
boolean newData = false;

void setup() {

  setPWMfrequency(0x02);// timer 0 , 3.92KHz
  for (int i = 5; i < 9; i++) {
    pinMode(i, OUTPUT);
  }
  for (int i = 5; i < 9; i++) {
    digitalWrite(i, LOW);
  }
  delay(1000);
  MotorActiveStatus('R', true);
  MotorActiveStatus('L', true);
  Serial.begin(115200);

  //  Serial.print("Probe MMA8451: ");
  //  if (mma8451.initialize()) Serial.println("Sensor found!");
  //  else
  //  {
  //    Serial.println("Sensor missing");
  //    while (1) {};
  //  }

}

float value = 0;

void loop() {
  recvOneChar();
  int motorRunTime = 100000;


  if (receivedChar == 'a') {   // 'B' for begin - but use any character you like
    motorStartMillis = millis();
    gorights();// call function to make motor start
    Serial.println("working");
  }

  if (receivedChar == 's') {   // 'B' for begin - but use any character you like
    motorStartMillis = millis();
    golefts();// call function to make motor start
    Serial.println("working");
  }
  if (receivedChar == 'd') {   // 'B' for begin - but use any character you like
    motorStartMillis = millis();
    goright();// call function to make motor start
    Serial.println("working");
  }

  if (receivedChar == 'f') {   // 'B' for begin - but use any character you like
    motorStartMillis = millis();
    goleft();// call function to make motor start
    Serial.println("working");
  }
  if (millis() - motorStartMillis >= motorRunTime) {
    stopmotor();// call function to make motor stop
  }

  if (receivedChar == 'e') { // 'E' for end
    stopmotor(); // call function to make motor stop
  }






  //  static float xyz_g[3];
  // mma8451.getMeasurement(xyz_g);
  //value = (xyz_g[0]);
  //Serial.println(value);









}





void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();

10,000 would fit in an int but you have 100,000, which won't. Make it unsigned long instead.

gerdal:
when I made time 10000 motor doesnt stop

In your program you have this

 int motorRunTime = 100000;

which is 100,000 and not 10,000

Also, the maximum value in an int is 32767 so 100,000 won't fit.

All variables associated with millis() should be defined as unsigned long - which can take values up to about 4 billion

unsigned long motorRunTime = 10000;

...R

Robin2:
In your program you have this

 int motorRunTime = 100000;

which is 100,000 and not 10,000

Also, the maximum value in an int is 32767 so 100,000 won't fit.

All variables associated with millis() should be defined as unsigned long - which can take values up to about 4 billion

unsigned long motorRunTime = 10000;

...R

thank you,

one more question:
after the period of time it send all the time the motor stop funtion. How can I make it to do one time?

gerdal:
one more question:
after the period of time it send all the time the motor stop funtion. How can I make it to do one time?

You need another variable - perhaps called motorRunning - which is true when it is running and false otherwise.

Then you would only call the stop function when motorRunning == true

...R

Robin2:
You need another variable - perhaps called motorRunning - which is true when it is running and false otherwise.

Then you would only call the stop function when motorRunning == true

...R

Robin2:
You need another variable - perhaps called motorRunning - which is true when it is running and false otherwise.

Then you would only call the stop function when motorRunning == true

...R

thank you ,

now I have 2 problem
first my times are not aqqured maybe because of the motor freq.
second when I acivate rf433 listening my motor starts spining.

#include <Wire.h>
#include "i2c.h"
#include "i2c_MMA8451.h"
#include<RH_ASK.h>
#include <SPI.h>
MMA8451 mma8451;
RH_ASK rf_driver;
int RPWM = 5;
int LPWM = 6;
int L_EN = 7;
int R_EN = 8;
const int button1 = 9;
const int button2 = 10;
const int button3 = 12;
unsigned long motorStartMillis = 0;
boolean motorRunning = false;
boolean doorposition = false;
char receivedChar;
boolean newData = false;

char flag = '0';

void setPWMfrequency(int freq) {
  TCCR0B = TCCR0B & 0b11111000 | freq ;
}

void MotorActiveStatus(char Side, boolean s) {
  boolean state = s;
  if (Side == 'R') {
    digitalWrite(R_EN, s);
  }
  if (Side == 'L') {
    digitalWrite(L_EN, s);
  }
}

void setMotor(char side, byte pwm) {
  if (side == 'R') {
    analogWrite(RPWM, pwm);
  }
  if (side == 'L') {
    analogWrite(LPWM, pwm);
  }
}

void closeMotor(char side) {
  if (side == 'R') {
    digitalWrite(RPWM, LOW);
  }
  if (side == 'L') {
    digitalWrite(LPWM, LOW);
  }

}

void goright() {
  setMotor('R', 255);
}

void gorights() {
  setMotor('R', 155);
}

void goleft() {
  setMotor('L', 255);
}

void golefts() {
  setMotor('L', 155);
}

void stopmotor() {
  closeMotor('R');
  closeMotor('L');
}

void recvOneChar() {
  if (Serial.available() > 0) {
    receivedChar = Serial.read();
    newData = true;
  }
}
int butonState = 0;
int butonState2 = 0;
void setup() {
  rf_driver.init();
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(button3, INPUT_PULLUP);
  setPWMfrequency(0x02);// timer 0 , 3.92KHz
  for (int i = 5; i < 9; i++) {
    pinMode(i, OUTPUT);
  }
  for (int i = 5; i < 9; i++) {
    digitalWrite(i, LOW);
  }
  delay(1000);
  MotorActiveStatus('R', true);
  MotorActiveStatus('L', true);
  Serial.begin(115200);


  Serial.print("Probe MMA8451: ");
  if (mma8451.initialize()) Serial.println("Sensor found!");
  else
  {
    Serial.println("Sensor missing");
    while (1) {};
  }
  
}

float value = 0;
float degera = 0;

void loop() {


  recvOneChar();

  unsigned long motorRunTime = 10000;//10,000 milis 12second
  unsigned long motorRunTime2 = 9000;//10,000 milis 12second


  if (receivedChar == 'a' ) {
    motorStartMillis = millis();
    motorRunning = true;
    gorights();// call function to make motor start
    Serial.println("a");
    
    receivedChar = '0';
  }

  if (receivedChar == 's') {
    motorStartMillis = millis();
    motorRunning = true;
    golefts();// call function to make motor start
    
    receivedChar = '0';

    Serial.println("s");
  }
  if (receivedChar == 'd') {
    motorStartMillis = millis();
    motorRunning = true;
    flag = '3';
    goright();
    receivedChar = '0';
    
  }

  if (receivedChar == 'f') {
    motorStartMillis = millis();
    motorRunning = true;
    flag = '5';
    receivedChar = '0';

    goleft();// call function to make motor start
    Serial.println("f");
  }
  if (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '0' ) {
    stopmotor();// call function to make motor stop
    motorRunning = false;
    flag = '0';
    Serial.println("dur");

  }
  if (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '1' ) {
    //stopmotor();// call function to make motor stop
    receivedChar = 'd';
    
    motorRunning = true;
    
   

  }
  if (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '3' ) {
    //stopmotor();// call function to make motor stop
    receivedChar = 'a';
    motorRunning = true;
    flag = '0';
    Serial.println("dur");

  }
    if (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '4' ) {
    //stopmotor();// call function to make motor stop
    receivedChar = 'f';
    motorRunning = true;
    
    Serial.println("dur");

  }
      if (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '5' ) {
    //stopmotor();// call function to make motor stop
    receivedChar = 's';
    motorRunning = true;
    flag = '0';
    
    Serial.println("dur");

  }
  if (receivedChar == 'e') { // 'E' for end
    stopmotor(); // call function to make motor stop
    flag = '0';
    motorRunning = false;

  }

  if (degera > 2 && motorRunning == true) {
    receivedChar = 'e';
  }


  butonState = digitalRead(button1);
  butonState2=digitalRead(button2);
  if (butonState == LOW) {
    if (flag == '0') {
      receivedChar = 'a';
      flag = '1';
    }
  }  
  if (butonState2 == LOW) {
    if (flag == '0') {
      receivedChar = 's';
      flag = '4';
    }
  }


  static float xyz_g[3];
  mma8451.getMeasurement(xyz_g);
  value = (xyz_g[0]);
  //Serial.println(value);
  degera = value;

///rf sensor read
     uint8_t buf[24];
   uint8_t buflen=sizeof(buf);
   if(rf_driver.recv(buf,&buflen)){
    Serial.print("message Received: ");
    Serial.println((char*)buf);
   }

}

gerdal:
now I have 2 problem
first my times are not aqqured maybe because of the motor freq.
second when I acivate rf433 listening my motor starts spining.

The first rule of debugging is deal with one problem at a time. So leave out the wireless code until you have the "times" working.

I don't understand what you mean by "first my times are not aqqured maybe because of the motor freq."

I have no experience with 433MHz wireless.

...R

Robin2:
The first rule of debugging is deal with one problem at a time. So leave out the wireless code until you have the "times" working.

I don't understand what you mean by "first my times are not aqqured maybe because of the motor freq."

I have no experience with 433MHz wireless.

...R

when I write working time 50000milis motor turns 6.5second not 5sec

gerdal:
when I write working time 50000milis motor turns 6.5second not 5sec

There is no variable in your program called workingTime so which variable are you referring to?

What is the variable flag intended to represent? It appears regularly.

Maybe you need to use IF and ELSE IF statements rather than a succession of IF statements.

Rather than have a series of long IF statements like this

f (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '0' ) {

I would use cascaded IF tests like this

if (motorRunning == true) {
     if (millis() - motorStartMillis >= motorRunTime) {
 

         if (flag == '0') {

IMHO that makes the logic much easier to follow

...R

Robin2:
There is no variable in your program called workingTime so which variable are you referring to?

What is the variable flag intended to represent? It appears regularly.

Maybe you need to use IF and ELSE IF statements rather than a succession of IF statements.

Rather than have a series of long IF statements like this

f (millis() - motorStartMillis >= motorRunTime && motorRunning == true && flag == '0' ) {

I would use cascaded IF tests like this

if (motorRunning == true) {

if (millis() - motorStartMillis >= motorRunTime) {

if (flag == '0') {



IMHO that makes the logic much easier to follow

...R

O used flag to run difrent motor speed for example I Start with motor funciton low speed then fast speed then low speed. and do it reverse.

Why don't you rename 'flag' to 'motorSpeed'? A "flag" is a term that usually refers to a boolean variable.

aarg:
Why don't you rename 'flag' to 'motorSpeed'? A "flag" is a term that usually refers to a boolean variable.

And even if it was a boolean variable a meaningful name makes a program much easier to understand.

...R