Laser Attack Weapon Code

 #include <Servo.h>


#define TRIG_PIN 9
#define ECHO_PIN 9
#define LASER_PIN 9


Servo servoMotor;
int pos = 0;
long duration, distance;

void setup() {
servoMotor.attach(9);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LASER_PIN, OUTPUT);
}

void loop() {
// Rotate servo motor
for (pos = 0; pos <= 180; pos += 1) {
servoMotor.write(pos);
delay(15);
distance = calculateDistance();
if (distance < 100) { // If an object is detected within 100 cm
blinkLaser();
delay(1000); // Wait for a second
}
}
for (pos = 180; pos >= 0; pos -= 1) {
servoMotor.write(pos);
delay(15);
distance = calculateDistance();
if (distance < 100) { // If an object is detected within 100 cm
blinkLaser();
delay(1000); // Wait for a second
}
}
}

long calculateDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
return distance;
}

void blinkLaser() {
for (int i = 0; i < 3; i++) {
digitalWrite(LASER_PIN, HIGH);
delay(300);
digitalWrite(LASER_PIN, LOW);
delay(300);
}
}

Comments

Popular posts from this blog

ESP32 Wi-Fi Extender Code