TRIBUTE TO INDIAN ARMY- Shoot the Enemy with LASER

TRIBUTE TO INDIAN ARMY- Shoot the Enemy with LASER 



Code With Connection:

//TRIGGER_PIN  4  // D4
//ECHO_PIN     5  // D5
//LASER_PIN    15 // D15
//OLED
//SCK D22
//SDA D21


#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <NewPing.h>

#define OLED_RESET    -1
Adafruit_SSD1306 display(OLED_RESET);

#define TRIGGER_PIN  4  // D4
#define ECHO_PIN     5  // D5
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define LASER_PIN    15  // Pin connected to the LASER module

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200);
 
  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  // Set LASER pin as output
  pinMode(LASER_PIN, OUTPUT);
  digitalWrite(LASER_PIN, LOW); // Ensure LASER is off initially

  // Clear the buffer
  display.clearDisplay();

  // Display initial message
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("SR04 Distance");
  display.display();
  delay(2000);
  display.clearDisplay();
}

void shootLaser(bool activate) {
  if (activate) {
    digitalWrite(LASER_PIN, HIGH); // Turn on LASER
  } else {
    digitalWrite(LASER_PIN, LOW);  // Turn off LASER
  }
}

void loop() {
  delay(100); // Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
 
  unsigned int distance = sonar.ping_cm(); // Send ping, get distance in cm (0 = outside set distance range)

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 10);

  // Display distance
  if (distance == 0) {
    display.println("Out of range");
    shootLaser(false); // Turn off LASER if out of range
    display.setCursor(0, 20);
    display.println("LASER: OFF");
  } else {
    display.print("Distance: ");
    display.print(distance);
    display.println(" cm");
   
    // Determine and display LASER status
    if (distance <= 10) {
      shootLaser(true); // Turn on LASER
      display.setCursor(0, 20);
      display.println("LASER: SHOOT ENEMY");
    } else {
      shootLaser(false); // Turn off LASER
      display.setCursor(0, 20);
      display.println("LASER: OFF");
    }
  }

  display.display();
}

Comments

Popular Posts