Untitled Document
Untitled Document
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 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
void setup() {
// Initialize motor driver pins as outputs
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
void loop() {
// Read the distance from the Ultrasonic sensor
unsigned int distance = sonar.ping_cm();
// Add a delay to indicate the LED and Buzzer activation for a short duration
delay(1000); // Adjust the delay time as needed
// 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)
}