Hi all, this is the code I am using.
Arduino code:
// Motion Detected Fan using Arduino and HC-SR04 Ultrasonic Sensor
// Components: Arduino Uno, HC-SR04, DC Motor/Fan, Motor Driver
// Pin definitions
const int trigPin = 9; // Ultrasonic sensor trigger pin
const int echoPin = 10; // Ultrasonic sensor echo pin
const int motorPin = 6; // Motor control pin (PWM)
const int ledPin = 13; // LED indicator pin (optional)
// Variables
long duration;
int distance;
const int motionThreshold = 30; // Distance in cm to detect motion
const int fanSpeed = 255; // Fan speed (0-255)
const int fanRunTime = 5000; // Time to run fan after motion detected (ms)
unsigned long motionDetectedTime = 0;
bool fanRunning = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.println(“Motion Detected Fan System Ready”);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send ultrasonic pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Print distance for debugging
Serial.print(“Distance: “);
Serial.print(distance);
Serial.println(” cm”);
// Check for motion detection
if (distance > 0 && distance <= motionThreshold) {
// Motion detected
Serial.println(“Motion Detected! Starting Fan…”);
// Turn on fan and LED
analogWrite(motorPin, fanSpeed);
digitalWrite(ledPin, HIGH);
// Record the time when motion was detected
motionDetectedTime = millis();
fanRunning = true;
}
// Check if fan should stop running
if (fanRunning && (millis() - motionDetectedTime >= fanRunTime)) {
// Turn off fan and LED
analogWrite(motorPin, 0);
digitalWrite(ledPin, LOW);
fanRunning = false;
Serial.println(“Fan stopped.”);
}
// Small delay before next reading
delay(100);
}
// Optional: Function to adjust fan speed based on distance
void adjustFanSpeed() {
if (distance > 0 && distance <= motionThreshold) {
// Calculate fan speed based on proximity (closer = faster)
int speed = map(distance, 1, motionThreshold, 255, 100);
speed = constrain(speed, 100, 255);
analogWrite(motorPin, speed);
}
}
This is the diagram I tried.