I need help with my project

Hi all, I’m a newbie here. I am creating a motion sensor fan with following items:
Arduino Uno
L298N motor driver
Ultrasonic sensor
9V lithium battery
5v DC motor
Breadboard
Propeller
Jumper wires

My motor auto turns on when connected to the battery power without reading the sensor. Can anyone tell me what could be the reason and help me with this please? Thank you.

Hi, could you possibly post a wiring-diagram, a picture and the code of your project.

1 Like

Welcome to the Forum! Read the forum guidelines to see how to properly ask a question and some good information on making a good post. You will get faster and better help if you post all your code as requested by the forum guidelines.
Photos that clearly show your wiring can also be very helpful.

1 Like

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.

1 Like

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

Please post your full sketch, using code tags when you do

Posting your code using code tags prevents parts of it being interpreted as HTML coding and makes it easier to copy for examination

In my experience the easiest way to tidy up the code and add the code tags is as follows

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

It is also helpful to post full error messages in code tags as it makes it easier to scroll through them and copy them for examination

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);
}
}
1 Like

Thank you for trying to use code tags but some of the code is not in tags. Under some circumstances that can happen due to problems with the forum software

How exactly did you add the code tags and which version of the reply editor are you using ? Is it the Rich Text Editor or the Markdown editor ? You switch between them by clicking the leftmost icon above the reply composer window

What do you see on the serial monitor? You have lots of Serial.print() statements in your code so they should be telling you something.

On your wiring diagram, you have +12V going to VCC on your driver and from there going to 5V on your UNO - Yikes! Is that the Vin pin on the UNO or the actual 5V pin. Connecting 12V to the 5V pin can fry our board .

It's helpful if you describe what you expect or want this project to do.

A list of components followed by what goes wrong doesn't help anyone get a feel for the end result.

the serial monitor says "Distance: 0" all the readings

what I expect the project to do= I expect it to turn on when the distance is below the limit to turn on
example= Limit is 60 and the current distance is 80, so I don't expect it to turn on
Limit is 100 and distance is 80, so I expect it to switch on
but sometimes then fan just run because of the external power supply, when the distance reading is 0 and once I tested the distance reading it went crazy over 1000 and the fan was just running, even though there is no accurate reading or no reading at all.

In that case I would concentrate on getting the fan running over a range of values say 0 to 10 and do the distance stuff later.
Strip the code out of your sketch that deals with the distance and leave just the motor speed code.
Save the original code and save the new cut down version as a new sketch.
When developing a sketch, get into the habit of creating a new sketch when you make changes so you can go back to one that works if there's a problem. Call the different versions something like VER_01 etc.
You can copy code into a spreadsheet and compare line by line

@billboy You appear to have ignored the request to repost your code properly using code tags

As a public service I have edited it to remove the non ASCII characters, reformatted the code and here it is posted in code tags. Did you copy it from a website by any chance ?

Note how much easier it is to read, navigate and copy for examination. The code compiles but I have not examined it in detail

// 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);
    }
}

@UKHeliBob My bad and thanks for your patience. I generated the code trough AI. Let me go through and try your refined code. Thanks again.

https://forum.arduino.cc/u/

The code is not refined, just formatted differently. When you coped it from the AI output on screen a number of Unicode (multi byte) characters were included and the IDE does not understand those so there will have been problems for that reason if nothing else

There is no way this code:

produces

It is far better to copy and paste the exact output from the Serial Monitor. Programming is a precise endeavor.

Since your code will only turn on the fan if distance is greater than 0 or less than or equal to motionThreshold it is doing what it should - not turn on since distance is not greater than 0.

I would focus on getting your sensor working all by itself. When that is done, then proceed to incorporate turning on the fan.

Does the fan turn on properly if you just hardcode distance to an acceptable value (such as 10)?

No the fan doesn't work according to the ultrasonic sensor distance, it just works when the external power supply is connected to the dc motor. I used it because the Arduino board can't control the motor alone.

Hi, @billboy
Welcome to the forum.

Forget your code.
Write code that JUST gets the ultrasonic working, nothing else.
Then;
Write code that JUST gets your motor ON and OFF, nothing else.

Do you coding in stages, it makes it easier on ALL of us.

Now the IMPORTANT BIT;
Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.

Thanks.. Tom.... :smiley: :+1: :coffee: :australia:

Now ultra sonic sensor and the code is working fine. I have attached few images of my setup here.

Eventhough it says "Fan ON". Motor is not working. Can anyone help me with this?



I am glad to hear that the sensor is working but as is often the case, your pictures of the project provide little or no information as to how the components are connected and powered and posting a picture of part of your code is a waste of time

Draw out the circuit using pencil and paper showing the components of your project, the pins used, their labels if they have any, and how they are interconnected.

Please post your full sketch, using code tags when you do

Posting your code using code tags prevents parts of it being interpreted as HTML coding and makes it easier to copy for examination

In my experience the easiest way to tidy up the code and add the code tags is as follows

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

It is also helpful to post full error messages in code tags as it makes it easier to scroll through them and copy them for examination