Program not waiting for me to start it with the push button

Hello I was wondering how could i fix this code because it is just starting and not waiting for me to start it with the push button I need some help i am new to this to any tips would help.

int enA = 9; 

int in1 = 8; 

int in2 = 7; 

int enB = 3; 

int in3 = 5; 

int in4 = 4; 

int pushbutton = 2;
 
bool CarIsRunning = 0;

void setup() {
	pinMode(enA, OUTPUT); 
	pinMode(enB, OUTPUT);
	pinMode(in1, OUTPUT);
	pinMode(in2, OUTPUT);
	pinMode(in3, OUTPUT);
	pinMode(in4, OUTPUT);
    pinMode(pushbutton, INPUT);

	
	digitalWrite(in1, LOW);
	digitalWrite(in2, LOW);
	digitalWrite(in3, LOW);
	digitalWrite(in4, LOW);
}


void loop() {
  if (CarIsRunning){
  digitalWrite(enA, HIGH);  
  digitalWrite(enB,HIGH);
  }
  if (CarIsRunning){
  digitalWrite(enA, HIGH);  
  digitalWrite(enB,HIGH);
  }
 int buttonVal = digitalRead(pushbutton);
  if (buttonVal = 1){
   digitalWrite(enA, HIGH);  
  digitalWrite(enB,HIGH);
 
  digitalWrite(in1, HIGH);
	digitalWrite(in2, LOW);
	digitalWrite(in3, HIGH);
  }
}

if (buttonVal = 1)

Is not the same as

if (buttonVal ==1)

1 Like

your a life saver i would have gotten the worst grade in my class tomorrow thanks

As digitalRead() returns HIGH or LOW, then should the above be written as?:

if(buttonVal == HIGH)

In Arduino Programming, HIG/LOW are assigned to int-type variables, true/false are assigned to boolean-type variables, and 1/0 are rarely used.

buttons are typically connected between the pin and ground, the pin configured as INPUT_PULLUP to use the internal pullup resistor which pulls the pin HIGH and when pressed, the button pulls the pin LOW.

a button press can be recognized by detecting a change in state and becoming LOW

and look this over

int enA = 9;
int in1 = 8;
int in2 = 7;

int enB = 3;
int in3 = 5;
int in4 = 4;

int pushbutton = 2;
byte butState;

bool carIsRunning = 0;

void loop ()
{
    if (carIsRunning) {
        digitalWrite (enA, HIGH);
        digitalWrite (enB, HIGH);
    }
    else {
        digitalWrite (enA, LOW);
        digitalWrite (enB, LOW);
    }

    int buttonVal = digitalRead (pushbutton);
    if (butState != buttonVal) {
        butState  = buttonVal;
        delay (20);                         // debounce

        if (LOW == butState)
            carIsRunning = ! carIsRunning;  // toggle
    }
}

void setup () {
    pinMode (enA, OUTPUT);
    pinMode (enB, OUTPUT);
    pinMode (in1, OUTPUT);
    pinMode (in2, OUTPUT);
    pinMode (in3, OUTPUT);
    pinMode (in4, OUTPUT);

    pinMode (pushbutton, INPUT);
    butState = digitalRead (pushbutton);
    
    digitalWrite (in1, HIGH);
    digitalWrite (in2, LOW);
    digitalWrite (in3, HIGH);
    digitalWrite (in4, LOW);
}

As variable buttonVal is of type int, then should the type of butState variable be int instead of byte?

yes, everything "should be" consistent

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.