Delay function causes problems with button!!


I was wondering if someone could help me with my code! I am trying to get vibration and sound after a light sensor detects a change (5 times from dark to light or light to dark), and to let them both stop after pushing a button.
The problem I am having is that the delay between the vibration and the sound (I would like 5 seconds of vibration before the sound starts) is causing problems with the button. I now have to hold the button as long as the delay takes, before the vibration and sound finally stop.

This is my Arduino Code:

const int motorPin=4;
const int sensorPin=A0;
const int buttonPin=3;
const int zoemer=8;

int buttonState=0;
int sensorChangeCounter=0; // counter for the number of state changes
int sensorState=0; //current sensor state
int lastsensorState=0; //previous sensor state
//int sensorValue=0;
int val=0;
int val2=0;

void setup() {

Serial.begin(9600); //Start the Serial connection
pinMode(sensorPin, INPUT); // initialize the sensor pin as a input
pinMode(motorPin,OUTPUT); // initialize the motor pin as an output
pinMode(buttonPin, INPUT); // declare pushbutton as input
pinMode(zoemer, OUTPUT);}

void loop() {

int val2 = digitalRead(buttonPin);
int val = analogRead(sensorPin);
val = map(val, 580, 750, 1, 2);

Serial.print("number of sensor changes: ");


} // end if sensorstate = lastsensorstate loop


if(sensorChangeCounter ==5){
digitalWrite(motorPin, HIGH);
digitalWrite(zoemer, HIGH); }

if (val2 == HIGH) { // check if the input is HIGH (button released)
digitalWrite(motorPin, LOW);
digitalWrite(zoemer, LOW);
// Serial.print(reset);


As you can see, I put a second loop at the end, but this didn't make any difference, sadly. Can someone please help me fix my code? I also tried the millis() function but then the button wouldn't work at all.

welcome to arduino forum . use the code tag for posting your code;

I cant abkle to understand section of your code. please indicate variable description properly.which are vibration variable; sound variable & so on.

I now have to hold the button as long as the delay takes, before the vibration and sound finally stop.

So, get rid of the delay.
Have a look at the blink without delay example in the IDE for clues about how to achieve this.

Yep. Definitely use millis() instead of delay() for your situation.

You need to do:

if (transition) {
   transitionMillis = millis();
   runningState = true;
   digitalWrite(motor, HIGH);

if (runningState && millis() - transitionMillis > 5000) {
   digitalWrite(zoemer, HIGH);

if (buttonReleased) {
   runningState = false;