Hello,
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);
Serial.println(val2);
int val = analogRead(sensorPin);
delay(100);
val = map(val, 580, 750, 1, 2);
Serial.println(val);
sensorState=val;
if(sensorState!=lastsensorState){
if(sensorState==2){
sensorChangeCounter++;
Serial.println("on");
Serial.print("number of sensor changes: ");
Serial.println(sensorChangeCounter);
}
else{
Serial.println("off");
}
} // end if sensorstate = lastsensorstate loop
lastsensorState=sensorState;
if(sensorChangeCounter ==5){
digitalWrite(motorPin, HIGH);
delay(2000);
digitalWrite(zoemer, HIGH); }
{
if (val2 == HIGH) { // check if the input is HIGH (button released)
digitalWrite(motorPin, LOW);
digitalWrite(zoemer, LOW);
sensorChangeCounter=0;
// 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.