#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows
const int potPin = A0;
const int trigPin = 9;
const int echoPin = 10;
const int stepperStepPin = 2;
const int stepperDirPin = 3;
const int stepperEnablePin = 4;
const int buzzerPin = 5;
const int distanceThreshold = 30; // Distance threshold in centimeters
int speed;
float distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(stepperStepPin, OUTPUT);
pinMode(stepperDirPin, OUTPUT);
pinMode(stepperEnablePin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
lcd.begin(16, 2); // initialize the LCD
lcd.print("Speed: ");
}
void loop() {
// Read the potentiometer value to control speed
speed = analogRead(potPin) / 4; // map the pot value (0-1023) to speed (0-255)
// Control the stepper motor speed
digitalWrite(stepperDirPin, HIGH); // Set the direction
for (int i = 0; i < speed; i++) {
digitalWrite(stepperStepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepperStepPin, LOW);
delayMicroseconds(500);
}
// Ultrasonic sensor to detect distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
distance = pulseIn(echoPin, HIGH) * 0.034 / 2;
// Display speed on LCD
lcd.setCursor(7, 0);
lcd.print(" "); // Clear previous speed value
lcd.setCursor(7, 0);
lcd.print(speed);
// Check for over-speed and trigger warning
if (speed > 120) {
lcd.setCursor(0, 1);
lcd.print("Over Speed!");
digitalWrite(buzzerPin, HIGH);
} else if (distance <= distanceThreshold) {
lcd.setCursor(0, 1);
lcd.print("Collision Detected!");
digitalWrite(buzzerPin, HIGH);
} else {
lcd.setCursor(0, 1);
lcd.print("In Safe Distance"); // Clear warning message
digitalWrite(buzzerPin, LOW);
}
delay(100); // Adjust delay based on the system response time
}