// https://arduino.stackexchange.com/questions/93115/arduino-dc-motor-control-over-ir-sensor-input
const int sensor_blocked = LOW; // define sensor values
const int sensor_clear = HIGH; // this one is not used
const int motor_on = HIGH;
const int motor_off = LOW;
const int master_enable_pin = 2;
const int motor_pin = 3;
const int sensor_pin = 12;
int sensor_state;
int sensor_previous = sensor_clear;
int motor_state = motor_on;
unsigned long millis_previous = 0;
unsigned long millis_now;
const long interval = 500;
void setup() {
pinMode(master_enable_pin, INPUT_PULLUP);
pinMode(sensor_pin, INPUT_PULLUP);
pinMode(motor_pin, OUTPUT);
}
void loop() {
sensor_state = digitalRead( sensor_pin );
// ---------------------------------------------------------------------------------------------------
if ( sensor_state != sensor_previous ) { // only run this code when sensor state changes
sensor_previous = sensor_state; // remember new sensor state
if ( sensor_state == sensor_blocked ) { // sensor became blocked
motor_state = motor_off; // turn off motor
millis_previous = millis(); // start of "motor off" interval
}
delay(20); // debounce sensor
}
// ---------------------------------------------------------------------------------------------------
if ( motor_state == motor_off ) { // timer check is relevant only when motor is off
millis_now = millis();
if ( millis_now - millis_previous >= interval ) { // check if timer expired
motor_state = motor_on; // enable motor
}
}
// ---------------------------------------------------------------------------------------------------
if ( digitalRead( master_enable_pin ) != LOW ) { // master switch must be on
motor_state = motor_off;
}
// ---------------------------------------------------------------------------------------------------
digitalWrite(motor_pin, motor_state); // translate motor state into action
}
// end ... loop()
slide switch enables the conveyor