> For the complete documentation index, see [llms.txt](https://docs.launchboard.app/cxd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.launchboard.app/cxd/code-internet-of-things-2.0/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="https://1128190565-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LEGLBX3AeXb13IcoB4Q%2F-LJ0pBBNm9hOWbswkZXP%2F-LJ0pSQvLOewPan-6Z_m%2Fpb-save-icon.png?alt=media&amp;token=fad2b9de-0395-4646-b367-019766d499f2" 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.launchboard.app/cxd/code-internet-of-things-2.0/tutorials/create-security-system/4.4-motion-sensor-code.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
