I'm running a dc motor using esp32 and mosfet by taking readings of IR.
Program works fine when used delay() but same program doesn't work when uploaded using millis().
//This uses fixed delay()
// Pin definitions
const int irSensorPin = 34; // IR sensor connected to GPIO 2
const int motorPin = 32; // DC motor connected to GPIO 4
// Variables
bool isObjectDetected = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(irSensorPin, INPUT);
pinMode(motorPin, OUTPUT);
}
void loop() {
// Check if object is detected
if (digitalRead(irSensorPin) == LOW) {
if (!isObjectDetected) {
// Object detected for the first time
isObjectDetected = true;
Serial.println("Object detected. Stopping motor.");
digitalWrite(motorPin, LOW); // Stop the motor
delay(500); // Wait for 500ms
Serial.println("Resuming motor.");
digitalWrite(motorPin, HIGH); // Start the motor
}
} else {
if (isObjectDetected) {
// Object is no longer detected
isObjectDetected = false;
}
}
}
//This uses millis()
// Pin definitions
const int irSensorPin = 34; // IR sensor connected to GPIO 34
const int motorPin = 32; // DC motor connected to GPIO 32
// Variables
bool isObjectDetected = false;
unsigned long motorStopTime = 0;
const unsigned long motorDelayTime = 500; // Delay time in milliseconds
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(irSensorPin, INPUT);
pinMode(motorPin, OUTPUT);
// Initialize motor state
digitalWrite(motorPin, HIGH); // Start the motor
}
void loop() {
// Check if object is detected
if (digitalRead(irSensorPin) == HIGH) {
if (!isObjectDetected) {
// Object detected for the first time
isObjectDetected = true;
Serial.println("Object detected. Stopping motor.");
digitalWrite(motorPin, LOW); // Stop the motor
motorStopTime = millis(); // Record the stop time
}
} else {
if (isObjectDetected) {
// Object is no longer detected
isObjectDetected = false;
unsigned long currentTime = millis();
if (currentTime - motorStopTime >= motorDelayTime) {
Serial.println("Resuming motor.");
digitalWrite(motorPin, HIGH); // Start the motor
}
}
}
}