07. Motion sensor

This digital input example uses a motion sensor to turn on a LED every time it detects a movement.

The motion sensor detects the movement of people in a certain area and is realized with a PIR (Passive InfraRed). Two separate sensors independently measure the amount of infrared radiation emitted by your body. If the two measurements are different the movement of your body is deduced (Figure 1).

Figure 1 - motion detection

Control functions

  • Output timing

Sets how long the output remains high after detecting motion (from 5 seconds to 5 minutes)

  • Sensitivity Adjust

Sets the detection range (from 3 meters to 7 meters)

  • Trigger Selection (with welding or jumper)

Set for single (No reset) or repeatable triggers (Auto-reset).

Figure 2 - PIR pinout


The sensor has 3 PINs (Figure 2):

  • Vcc 5-20V
  • OUT output signal (3.3V TTL); high when motion is detected
  • GND Ground.

Area of detection

The sensor will detect motion inside a 110 degree cone with a range of 3 to 7 meters (Figure 3).

Figure 3 - detection area

Device Initialization

The sensor requires nearly a minute to initialize. During this period, it can and often will output false detection signals. Circuit or controller logic needs to take this initialization period into consideration.

1. Circuit

Connect the Pir and the led as shown in Figure 4:

  • led positive PIN to d7
  • led negative PIN to d8
  • Pir GND PIN to GND
  • Pir data PIN to D3
  • Pir Vcc PIN to 5V.

Note: the longer LED PIN is the positive.

Figure 4 - motion sensor circuit

2. Sketch

Write a sketch K to define:

  • the output connections: led :: d7, gnd :: d8
  • the input connections: Pir :: D3
  • the command to start and stop the system: start, stop
  • the rules to implement the automaton (Figure 5).

When the automa has 2 states use led as a status variable.

Pir :: D3   
gnd :: d8
led :: d7 
EndMotion = !Pir   
Motion = Pir   
stop = [led=0]   
!led & Motion -> led=1 ##
 led & EndMotion -> led=0 ##

or simply load the sketch in the workspace with the command

] load e07_motion_sensor

Figure 5 - motion sensor automaton

3. Try and learn

Initialize the system with the command

  • ] start

the LED is off.

Move in front of the PIR!

  • < Motion

the LED turns on and the Motion event is sent to the Internet

Do not move in front of the PIR!

  • < EndMotion

the LED turns off and the EndMotion event is sent to the Internet

Try the following commands now:

  • ] stop

turns off the LED and the PIR is insensitive to movement!

  • ] start

reestablish motion detection

  • ] pause

suspends motion detection.

Do you notice a difference with the stop command?

What is the command to resume motion detection?

4. Summarizing

In this lesson you learned or repeated:

  • how to use a PIR and a LED
  • the commands: start, stop, pause (and play), ##
  • use led as a status variable.