Making a program that stops a motor after a button is pressed

So today, I started a project with my new Arduino Nano and some 3D printed parts. Basically, it's a small robot that will go forward until two buttons at the front are pressed. For example, if the robot crashed into a wall, the two buttons at the front would detect that, and the robot would stop for 10 seconds.

Currently, I have a "drive" function that will drive the robot, and I'm also trying to make a detect function to detect if the buttons are pressed.
Here's my function code:

int IN1 = 3;
int IN2 = 9;
int IN3 = 10;
int IN4 = 11;
int b1Pin = 8;
int b2Pin = 7;

void drive(int lSpeed, int rSpeed){
    analogWrite(IN1, lSpeed);
    digitalWrite(IN2, 0);
    digitalWrite(IN1, 0);
    analogWrite(IN2, -lSpeed);

    analogWrite(IN3, rSpeed);
    digitalWrite(IN4, 0);
    digitalWrite(IN3, 0);
    analogWrite(IN4, -rSpeed);

void detectCrash() {

void setup() {
  // put your setup code here, to run once:


void loop() {
  // put your main code here, to run repeatedly:

Sadly, this code doesn't work. Does anyone know some (ideally easy-to-understand) code that can achieve my goal?

Thank you!

EDIT: The code is written in Arduino C++

Where is the rest of your code? I see a function and a setup which calls the function. You are missing the main program. Also how do you know it does not work?

Please post your complete code.
Please use code tags when posting code; use e.g. the </> button.

Alright, I put in all the code. Also, I know it doesn't work because when I turn it on and press the buttons, the wheels keep spinning.


This delay() command will not stop either the analogWrite() or the digitalWrite() of an output pin.

You need to explicitly turn off the output on the pin with digitalWrite(pin,LOW).

1 Like

That was quick response once somebody could see the problem.

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