0% found this document useful (0 votes)
12 views

Untitled Document

Uploaded by

piyush sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Untitled Document

Uploaded by

piyush sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

AUTOSYSTEM

Items required

Arduino Nano
Ultrasonic sensor (HC-SR04 or similar)
LED
Buzzer
Motor driver module (L298N or similar) to control the train's motors

#include <NewPing.h>

// Define the Ultrasonic sensor pins


#define TRIGGER_PIN 10
#define ECHO_PIN 11
#define MAX_DISTANCE 200 // Maximum distance (in cm) to detect obstacles (2 meters)

// Define the motor driver pins (for demonstration purposes, adjust according to your motor
driver connections)
#define ENA 5 // Enable pin for Motor A
#define IN1 6 // Motor A input 1
#define IN2 7 // Motor A input 2

// Define LED and Buzzer pins


#define LED_PIN 9
#define BUZZER_PIN 8

// Create an Ultrasonic sensor object


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
// Initialize motor driver pins as outputs
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);

// Initialize LED and Buzzer pins as outputs


pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);

// Start with the motors off


stopMotors();

// Turn off the LED and Buzzer initially


digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}

void loop() {
// Read the distance from the Ultrasonic sensor
unsigned int distance = sonar.ping_cm();

// If an obstacle is detected within 1 meter (100 cm)


if (distance <= 100) {
// Stop the motors
stopMotors();

// Turn on the LED and Buzzer


digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);

// Add a delay to indicate the LED and Buzzer activation for a short duration
delay(1000); // Adjust the delay time as needed

// Turn off the LED and Buzzer


digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
} else {
// If the obstacle is out of the 2-meter range, turn off the LED and Buzzer
if (distance > 200) {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}

// Continue running the train (motors on)


startMotors();
}
}

// Function to stop the motors


void stopMotors() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
analogWrite(ENA, 0);
}

// Function to start the motors (you can adjust the speed by changing the speed value)
void startMotors() {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, 150); // Adjust motor speed as needed (0 to 255)
}

You might also like