Pinterest Stumbleupon Whatsapp
Ads by Google

Detect movement, then scare the heck out of an intruder with a high pitched alarm sounds and flashing lights. Does that sound fun? Of course it does. That’s the goal of today’s Arduino project, suitable for beginners. We’ll be writing completely from scratch and testing as we go along so you can hopefully get some idea of how it’s all being done rather than simply installing something I’ve already made.

Disclaimer: this isn’t going to actually protect your house. It might give your sister a nasty shock when she sneaks into your room though.

You’ll need:

As you’re wiring up this project, don’t remove everything each time — just keep building on the last block. By the time you get to “Coding The Alarm System” section, you should have all the bits and pieces wired up, looking something like this:


Flashing Lights

Use the wiring diagram from this project Build Your Own Dynamic Ambient Lighting For A Media Center Build Your Own Dynamic Ambient Lighting For A Media Center If you watch a lot of movies on your PC or media center, I'm sure you've faced the lighting dilemma; do you completely turn off all lights? Do you keep them on full blast? Or... Read More to hook up your LED strip; don’t change the pins, as we need PWM output. Use this code to quickly test your wiring. If all goes well, you should have this:

Ads by Google


Distance Sensor

On the SR04 module, you’ll find 4 pins. VCC and GND go to +5V rail and ground respectively; TRIG is the pin used to send a sonar signal, put this on pin 6; ECHO is used to read the signal back (and therefore calculate the distance) — put this on 7.


To make things incredibly simple, there’s a library we can use called NewPing. Download and place in your Arduino’s Library folder and restart the IDE before continuing. Test using this code; open up the serial monitor and make sure the speed is set to 115200 baud. With any luck, you should see some distance measurements being send back to you at a pretty high speed. You may find a variance of 1 or 2 centimeters, but this is fine. Try running your hand in front of the sensor, moving it up and down to observe the changing readings.


The code should be fairly simply to understand. There are a few declaration of relevant pins at the start, including a maximum distance – this may vary according to the exact sensor you have, but as long as you’re able to get less than 1 meter readings accurately, you should be fine.

In the loop of this test app, we use the ping() function to send out a sonar ping, getting back a value in milliseconds of how long it took for the value to return. To make sense of this, we use the NewPing libraries built in constant of US_ROUNDTRIP_CM, which defines how many microseconds it takes to go a single centimeter. There’s also a 50 ms delay between pings to avoid overloading the sensor.

Piezo Alarm

The Piezo crystal sensor is a simple and cheap buzzer, and we can use a PWM pin 3 to make different tones. Connect one wire to pin 3, one to ground rail – it doesn’t matter which.

Use this code to test.

The only way to kill the rather obnoxious and loud alarm is to pull the plugs. The code is a little complex to explain, but it involves using sine waves to generate a distinctive sound. Tweak the numbers to play with different tones.

Coding The Alarm System

Now that we have all the pieces of this puzzle, let’s combine them together.

Go ahead and make a new sketch, called Alarm. Start by combining all the variables and pin definitions we’ve in the test examples until now.

#include <NewPing.h>

// Select which PWM-capable pins are to be used.
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9

#define TRIGGER_PIN  6  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     7  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 100 // Maximum distance we want to ping for (in centimeters).

#define ALARM 3

float sinVal;
int toneVal;

Begin by writing a basic setup() function – we’ll only deal with the lights for now. I’ve added a 5 second delay before the main loop is started to give us some time to get out of the way if needed.

void setup(){

   //set pinModes for RGB strip

   //reset lights


Let’s use a helper function that allows us to quickly write a single RGB value out to the lights.

//helper function enabling us to send a colour in one command
void color (unsigned char red, unsigned char green, unsigned char blue)     // the color generating function
    analogWrite(RED_PIN, red);     
    analogWrite(BLUE_PIN, blue);
    analogWrite(GREEN_PIN, green);

Finally, our loop for now is going to consist of a simple color flash between red and yellow (or, whatever you want your alarm to be — just change the RGB values).

void loop(){
   color(255,0,0); //red
   color(255,255,0); //yellow

Upload and test that to ensure you’re on the right track.

Now, let’s integrate the distance sensor to trigger those lights only when something comes within, say, 50 cm (just less than the width of a door frame). We’ve already defined the right pins and imported the library, so before your setup() function add the following line to instantiate it:

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

Underneath that, add a variable to store the state of the alarm being triggered or not, defaulting to false, of course.

boolean triggered = false; 

Add a line to the setup() function so we can monitor the output on serial and debug.

Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.  

Next, let’s rename the current loop to alarm() – this is what’s will be called if the alarm has been tripped.

void alarm(){
   color(255,0,0); //red
   color(255,255,0); //yelow

Now create a new loop() function, one in which we fetch a new ping, read the results, and trigger the alarm if something is detected within the meter range.

void loop(){
    if(triggered == true){
      delay(50);// Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
      unsigned int uS =; // Send ping, get ping time in microseconds (uS).
      unsigned int distance = uS / US_ROUNDTRIP_CM;
      if(distance < 100){
         triggered = true;

Let me explain the code briefly:

  • Start by checking to see if the alarm has been triggered, and if so, fire off the alarm function (just flashing the lights at the moment).
  • If it’s not triggered yet, get the current reading from the sensor.
  • If the sensor is reading <100 cm, something has padded the beam (adjust this value if it’s triggering too early for you, obviously).

Give it a trial run now, before we add the annoying piezo buzzer.

Working? Great. Now let’s add that buzzer back. Add pinMode to the setup() routine.


Then add the piezo buzzer loop to the alarm() function:

for (int x=0; x<180; x++) {
    // convert degrees to radians then obtain sin value
    sinVal = (sin(x*(3.1412/180)));
    // generate a frequency from the sin value
    toneVal = 2000+(int(sinVal*1000));
    tone(ALARM, toneVal);

If you try to compile at this point, you’re going to run into an error — I’ve left this in deliberately so you can see some common issues. In this case, both the NewPing and standard tone library use the same interrupts — they are conflicting basically, and there’s not a lot you can do to fix it. Oh dear.

No worries though. It’s a common problem, and someone has a solution already — download and add this NewTone to your Arduino Libraries folder. Adjust the beginning of your program to include this:

#include <NewTone.h>

And adjust the line:

  tone(ALARM, toneVal); 


    NewTone(ALARM, toneVal);


That’s it. Set your alarm up in the doorway of your bedroom for the next hapless would-be burglar.

Or, a dopey dog, which seemed completely unfazed by the alarm.

Having trouble with the code? Here’s the complete app. If you’re getting random errors, try pasting them below and I’ll see if I can help.

Image credit: Fire Alarm via Flickr

  1. Jack
    October 9, 2016 at 12:11 pm

    What arduino model is use for this project?

    • James Bruce
      October 15, 2016 at 5:29 pm

      Just a basic Uno, but anything would do.

  2. hadi al agele
    June 22, 2016 at 7:38 pm

    Hi James
    i want to make code for constant distance like 20 cm , but i don't know how can i do? I am trying several time without any benefit when the distance less than 20 cm become led red . can you help me please?

    • James Bruce
      June 24, 2016 at 9:09 am

      Which bit exactly are you having trouble with? What have you tried so far?

      • hadi al agele
        June 24, 2016 at 6:10 pm

        Hi James
        thank you so much for your replay. can you send me the wire diagrams for alarm code ?please(picture).

  3. blfo
    May 26, 2016 at 7:02 am

    Hi, so i wired up my project completely and ran the code completely. What i noticed is that the LED strip when plugged into the 12V power supply stays on and lights up white. When the code is uploaded, the light just stays with a white colour rather than changing. What does this mean and how can i fix it?

    • James Bruce
      May 26, 2016 at 7:15 am

      It means you either have a different kind of MOSFET, or they're wired up wrong. White will occur when they're fully sinking all the voltage (ie, completely on).

      Try inverting the values output in the code first - so instead of sending 255 for full red, try sending 0 instead.

  4. given
    April 21, 2016 at 11:27 am

    how did wire all these up to aduino

  5. Landser
    April 5, 2016 at 1:16 pm

    How did you wire all of this into the Arduino? Been trying to figure this out, and maybe it is just me. Thanks

  6. Dora
    April 1, 2016 at 9:08 am

    Hi James,

    I wanted to use one LED rather than a LED strip just to test out the code and make sure I can get everything to work before going out and buying anything. When I look at the schematic for the LED strip, there are three transistors, which I assume I wouldn't need if I only used one LED. I was just wondering how I would go about changing the wiring if I only used one LED.

    • James Bruce
      April 1, 2016 at 9:47 am

      Easiest would be to use the built-in test LED on pin 13, then no wiring at all needed.. Check out the basic blink example for how to flash it.

  7. ibra
    March 27, 2016 at 8:22 pm

    I don't know why i had a errors of compilation ""exit statut 1 """

  8. Paul
    March 24, 2016 at 10:18 am

    hello sir. i badly need help because it seems to work for me but the thing is when i set it up the alarm triggers after 5 seconds that i've set it up even when nothing passes in front of it. I don't know ho to solve it.

    • James Bruce
      March 24, 2016 at 8:50 pm

      If you havent modified the code, then your sensor is probably not wired up right, so it's just triggering immediately.

      • Paul
        March 24, 2016 at 8:59 pm

        I don't think so.I did the wiring just as what you said with the instructions, the sensor receives ping with the first code and makes me see the change in distance.but with the last project or final sketch it only receives one and triggers the alarm.i don't know if i explained it well.

      • Paul
        March 24, 2016 at 9:10 pm

        oh sir. i kinda solved it but don't think was a solution.first i measured the distance of the the sensor to a wall and the max distance im getting was 96cm so what i did was lower the if statement (distance<50) and when i pass something i between it triggers the alarm.i'm just worried that when i present it and set it up it'll trigger right away

        • James
          March 24, 2016 at 9:30 pm

          Well, yes - if the distance is saying less than 100 cm, and your wall is 96cm away, then it will be triggered. You could add some debug output to be sure. Set up your project, check the values in the debug console, then make sure the if statement is a suitable number.

          Ideally, I guess, the code would first check for maximum distance, assuming at reset time that nothing is in the way, then would take a few centimeters off that number for the checking distance. The code I wrote 3 years ago isn't that clever though: that can be your homework ;)

        • Paul
          March 25, 2016 at 7:52 am

          yes thats exactly what i thought.i'm working on it right now.thank you for the project ?

        • Paul
          April 9, 2016 at 10:07 am

          i made some update with the code and it seems to work fine.i just have one question about the led, in the code rgb color should be between yellow and red but the output i'm having is green and red.i could not figure out what the problem is and need a help.

        • James Bruce
          April 11, 2016 at 7:43 am

          Yellow is made by mixing green and red. Possibly you don't have individual RGB LEDs, but a strip with individual red, green, and blue LEDs instead? Normally setting colour to yellow would work, but if you have individual colors instead of RGB, yellow will just show you green and red.

  9. Kevin
    February 24, 2016 at 1:45 pm

    sir the NewTone library doesnt work ? there is an error if i insert it . can you help me about this ?

  10. drew
    January 22, 2016 at 7:44 pm


  11. Gian
    January 13, 2016 at 6:49 pm

    Hello, I'm trying to do this for a uni project.I'd like to ask questions of how it works specifically how do you stop when it alarmed? Because I'm also trying to make a case for it.Thanks.

    • James Bruce
      January 15, 2016 at 12:53 pm

      Use the reset button on the arduino is the easiest. You can hook up your own momentary button to do the same.

  12. drew
    January 13, 2016 at 2:46 am

    Can you add a way to stop the alarm? Thanks.

  13. Andres Suarez Moscoso
    November 9, 2015 at 12:23 am

    Hello What happens is that the link to download the NewTone is down , can you tell me where I can download thanks.

  14. Alice Blue
    November 6, 2015 at 9:01 am

    Hi, we would like to use your code for a uni project, we tried the code but we are missing the NewPing.h, wWe would be very thankful if you could give us a bit of help, thankyou

  15. Sellers Crisp
    October 30, 2015 at 1:41 pm

    Hello, was wondering where the setup was for the board itself? I am currently using the Arduino Uno :)

    • James Bruce
      November 6, 2015 at 9:37 am

      Not sure what you mean – but board type is selected within the Arduino IDE, not in code.

      If you mean what to plug in where - it's all in the text. Just follow along with the guide, it will tell you exactly which pins to plug what in to.

  16. sean
    May 25, 2015 at 4:05 am

    HEY great project but I keep getting this error in the code

    core.a(Tone.cpp.o): In function `__vector_7':
    C:UsersAmyDesktopArduinohardwarearduinocoresarduino/Tone.cpp:535: multiple definition of `__vector_7'
    NewPingNewPing.cpp.o:C:UsersAmyDesktopArduinolibrariesNewPing/NewPing.cpp:214: first defined here

    and I can't figure it out any suggestions?

  17. bulletjoe
    May 17, 2015 at 11:02 am

    Can you please explain

    • James Bruce
      May 17, 2015 at 2:32 pm

      Explain what?

    • bullet joe
      May 22, 2015 at 10:44 am

      The code.I'm just in 8 grad3

  18. marc
    December 4, 2013 at 10:44 am

    Hi ! Nice project !

    You can have a look at my own arduino alarm project :

  19. Don Campbell
    August 26, 2013 at 4:43 pm

    Thanks James - I'm excited about doing this project with my kids. Can you tell me where I can find the parts I need to put this together? Do you have any links of where I can get them?

Leave a Reply

Your email address will not be published. Required fields are marked *