> For the complete documentation index, see [llms.txt](https://docs.idew.org/code-internet-of-things/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.idew.org/code-internet-of-things/tutorials/create-security-system/4.4-motion-sensor-code.md).

# D-4 Motion Sensor Code

Next, you'll add code in your Smart Security device app to control the motion sensor.

The basic steps to use a motion sensor in your app code are:

1. Declare a global variable to store the I/O pin number for the motion sensor.
2. Set the pin mode for the motion sensor pin in the `setup()` function.
3. Use a `digitalRead()` statement to check whether the sensor detects any motion, and add code statements that should be performed if motion is detected (or not detected).

## Global Variable for Sensor

Declare a global variable to store the I/O pin number for the motion sensor by adding this code statement **before** the `setup()` function:

```cpp
int motion = D3;
```

If you connected your motion sensor to a different I/O pin other than `D3`, then modify this code statement to list the correct pin number for your motion sensor.

## Set Pin Mode for Sensor

Set the pin mode for your motion sensor pin by adding this code statement **within** the `setup()` function (between the curly braces):

```cpp
pinMode(motion, INPUT_PULLUP);
```

## Add Function to Check Sensor

The `digitalRead()` method is used to check whether the sensor currently detects any motion.

The `digitalRead()` method will return a value of either `HIGH` or `LOW` (which are treated as if they were `int` values):

* `HIGH` indicates that motion is **NOT** currently detected.
* `LOW` indicates that motion is currently detected.

A variable named `motionState` will store the value returned by the `digitalRead()` method.&#x20;

An [if statement](http://www.wiring.org.co/reference/if_.html) will be used to perform a set of actions if motion is detected (if `motionState` has a value equivalent to `LOW`).

You'll add a custom function named `checkMotion()` that will contain all this code.

Add this `checkMotion()` custom function **after** the `loop()` function (you can add it before or after the `toggleMode()` function):

```cpp
void checkMotion() {
    int motionState = digitalRead(motion);
    
    if (motionState == LOW) {
        // add code to do something if motion detected
        
        delay(2000); // wait 2 seconds before checking sensor again
    }
}
```

Inside the `if` statement, you'll need to add code to do something if motion is detected. In the next step of this tutorial, you'll add code here to make an "alarm sound" using the speaker. Later, you'll also add code to send an event notification to the web app that you'll be creating.

You'll notice that a `delay()` of 2 seconds is performed when motion is detected. This delay is needed to allow the sensor to capture a new "snapshot" of the environment before checking the sensor again.

## Call Function in Loop If Armed

The `checkMotion()` function will only be performed if it is called within another function, such as the `loop()` function. However, the motion sensor should only be checked if the device's mode is currently set to `"armed"`.

Add this code **within** the `loop()` function (**after** the closing curly brace of the existing `if` statement that checks the value of `buttonState`):

```cpp
    if (deviceMode == "armed") {
        checkMotion();
    }
```

This code will only call the `checkMotion()` function if the value of `deviceMode` is equivalent to `"armed"`.

Save your `smart-security` app code by clicking the **Save** icon in the left navigation bar.

<div align="left"><img src="/files/-LJ0pSQvLOewPan-6Z_m" alt="Save Icon"></div>

<br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.idew.org/code-internet-of-things/tutorials/create-security-system/4.4-motion-sensor-code.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
