Using the SONAR sensor as the main detector

. But the default range of the sensor is too small (15 degrees only),

so adding a SERVO which controls by a JOYSTICK can allow the system to have more coverage area.

If something (enemy) is approaching a certain distance,

the SONAR sensor will turn on a LED light to activate RELAY (weapon).

Wiring diagram
1. Detect sensors: Automatic detect objects (enemy)
2. Control system: Manually control the detection range
3. Weapon system: Automantly triggered according to a specific situation

COMPONENTS

CODE

#include <Servo.h> //Include the servo library

Servo servo1;

Servo servo2;

int joyX =0;

int joyY =1;  //none

int joyVal;   //joystick value

#include <NewPing.h>

int ledPin1=10;     //led

int ledPin2=12;     //relay

int lightPin = A3;  //light sensor

int lightValue;     //light sensor

int dist;

#define TRIGGER_PIN  7    // Arduino pin tied to trigger pin on the ultrasonic sensor.

#define ECHO_PIN     8    // Arduino pin tied to echo pin on the ultrasonic sensor.

#define MAX_DISTANCE 400  // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

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

void setup()

{ //attaches our servos on pins PWM 3-5

  servo1.attach(3);

  servo2.attach(5);     //none

  //Serial.begin(115200);  //sonar sensor

  Serial.begin(9600);      //light sensor

  pinMode(ledPin2, OUTPUT);

}

void loop()

{

  //read the value of joystick (between 0-1023)

  joyVal = analogRead(joyX);

  joyVal = map (joyVal, 0, 1023, 0, 180); //servo value between 0-180

  servo1.write(joyVal); //set the servo position according to the joystick value

  joyVal = analogRead(joyY);

  joyVal = map (joyVal, 0, 1023, 0, 180);

  servo2.write(joyVal);

  delay(15);

Serial.print(sonar.ping_cm());

  // Send ping, get distance in cm and print result (0 = outside set distance range)

  Serial.println(“cm”);

  dist = sonar.ping_cm();

  if(dist >= 20){

  digitalWrite(ledPin1, LOW);

}

  if(dist < 20){

  digitalWrite(ledPin1, HIGH);

  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.

}

int lightValue = analogRead(lightPin);

int mapValue = map(lightValue, 600, 20, 0, 10); //200=min light, 20=max light

//mapValue = constrain(mapValue, 0 ,10);

Serial.print(mapValue);

Serial.print(“–“);

Serial.println(lightValue);

if(mapValue > 5){

  digitalWrite(ledPin2, HIGH);

  delay(20);

  digitalWrite(ledPin2, LOW);

  delay(20);

  }

  else{

  digitalWrite(ledPin2, HIGH);

}

}

WIRING