hi all i am not sure is this correct category
need help with my code behaving strange!?
everything works good but
i need motor to stop if sensor does not detect object in 2 seconds
and it is not stopping
// Pins
const int IR_SENSOR_PIN = 2;
const int MOTOR_PIN = 9;
const int BUTTON_PIN = 7;
const int COUNTER_PIN = 13; // Digital counter output pin
// Variables
int sensorState = LOW;
int lastSensorState = LOW;
unsigned long sensorStartTime = 0;
const unsigned long SENSOR_TIMEOUT = 2000;
bool sequenceStarted = true;
int counter = 0; // Counter variable
void setup() {
// Initialize the pins
pinMode(IR_SENSOR_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(MOTOR_PIN, OUTPUT);
pinMode(COUNTER_PIN, OUTPUT);
digitalWrite(MOTOR_PIN, LOW); // Start with the motor off
// Set the initial sensor state
sensorState = digitalRead(IR_SENSOR_PIN);
lastSensorState = sensorState;
}
void loop() {
// Check if the button is pressed
if (digitalRead(BUTTON_PIN) == LOW) {
sequenceStarted = false;
digitalWrite(MOTOR_PIN, LOW); // Turn off the motor
delay(100); // Stop the motor for 2 seconds
digitalWrite(MOTOR_PIN, HIGH); // Turn on the motor again
}
// Check the IR sensor state
sensorState = digitalRead(IR_SENSOR_PIN);
// If the sensor state has changed
if (sensorState != lastSensorState) {
// If the sensor is low
if (sensorState == LOW) {
// Start the sequence
sequenceStarted = true;
sensorStartTime = millis();
delay(100); // Record the start time
digitalWrite(MOTOR_PIN, HIGH); // Turn on the motor
counter++; // Increment the counter
digitalWrite(COUNTER_PIN, counter % 2); // Output the counter value to the digital pin
} else {
// Sensor is high, stop the motor
sequenceStarted = false;
digitalWrite(MOTOR_PIN, LOW); // Turn off the motor
}
}
// If the sensor is continuously low for 5 seconds
if (sensorState == LOW && sequenceStarted && millis() - sensorStartTime >= SENSOR_TIMEOUT) {
// Stop the motor
sequenceStarted = true;
digitalWrite(MOTOR_PIN, HIGH); // Turn off the motor
}
// Update the last sensor state
lastSensorState = sensorState;
}
please for support
i am solving this and it just not working for me
thank you in advance