turning off motors

I have my code configured to when I press a button it turns on a fan for so long then the motor comes on, I have it on a timer for it to shut off, but I would like to be able to turn it off any time during the process. What do I need to do in order for this to work.

This is my code:

int fan = 6;
int button = 2;
int motor = 7;

int buttonState = 0;

void setup() {
// put your setup code here, to run once:
pinMode(motor, OUTPUT);
pinMode(fan, OUTPUT);
pinMode(button, INPUT);

void loop() {

buttonState = digitalRead(button);
if (buttonState == HIGH) {
digitalWrite(fan, HIGH);


Use millis() for timing instead of delay().

What do I need to do in order for this to work.

Start by getting rid of the delay()s

Take a look at Using millis() for timing. A beginners guide, Several things at the same time and the BlinkWithoutDelay example in the IDE

I hate to be greedy about this, but I cannot for the life of me get the millis figured out, is there anyone who could write and example code for me.

Maybe a video would help make it clear:

Recommended tutorial: Blink without delay() explained line-by-line

Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks... Tom... :slight_smile:


Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you take a few moments to Learn How To Use The Forum.
It will help you get the best out of the forum in the future.
Other general help and troubleshooting advice can be found here.

First you need to adjust your code so that you start the sequence when the button state CHANGES from LOW to HIGH, rather than sensing that the button is high.

Have you got a pull_down 10K resistor between the buttonPin 2 and gnd?

Thanks.. Tom.. :slight_smile: