Standard library · Hardware

hw.pir

Read a PIR motion sensor on a pin, active high or inverted, and wait for motion with a timeout.

import hw.pir

hw.pir reads a passive infrared motion sensor such as the HC-SR501. Most modules raise their output pin when they see motion; for the ones that lower it, use OpenInverted. Many modules hold the output high for seconds after a movement, so decide in your program how often to look.

Waiting for motion

Motion answers now. WaitMotion keeps asking for a number of milliseconds and gives up with false, which suits a light that turns on when someone walks in.

hw-pir-guide-wait.salam
Try it
import hw.board
import hw.pir

func main:
    sensor := pir.Open(7)
    println pir.WaitMotion(sensor, 5)
    board.SimSetPin(7, 1)
    println pir.WaitMotion(sensor, 5)
end
Output
false
true

Sensors that pull low

Some modules and door switches pull the pin low when something happens. Open them with OpenInverted: the pin gets the pull-up and Motion is true when the pin reads low.

hw-pir-guide-inverted.salam
Try it
import hw.board
import hw.pir

func main:
    sensor := pir.OpenInverted(8)
    println pir.Motion(sensor)
    board.SimSetPin(8, 0)
    println pir.Motion(sensor)
    board.SimSetPin(8, 1)
    println pir.Motion(sensor)
end
Output
false
true
false

Types

Sensor

#
struct Sensor

A PIR motion sensor on a pin, and whether it reports motion with a high or a low level.

NameTypeDescription
pinint = 0The pin the sensor output is wired to.
active_highbool = trueTrue when motion is a high level (most modules), false when it is a low level.
hw-pir-Sensor.salam
Try it
import hw.board
import hw.pir

func main:
    sensor := pir.Open(7)
    println pir.Motion(sensor)
    board.SimSetPin(7, 1)
    println pir.Motion(sensor), pir.WaitMotion(sensor, 10)
    board.SimSetPin(7, 0)
    println pir.WaitMotion(sensor, 3)
    door := pir.OpenInverted(8)
    println pir.Motion(door)
    board.SimSetPin(8, 0)
    println pir.Motion(door)
end
Output
false
true true
false
false
true

Functions

Open

#
func Open(pin: int): Sensor

Opens an active-high sensor: the pin becomes an input.

The example for this item is shown with the ones above: hw-pir-Sensor.salam

OpenInverted

#
func OpenInverted(pin: int): Sensor

Opens a sensor that pulls the pin low on motion. The pin gets the pull-up, so an idle sensor reads high.

The example for this item is shown with the ones above: hw-pir-Sensor.salam

Motion

#
func Motion(s: Sensor): bool

True when the sensor reports motion now.

The example for this item is shown with the ones above: hw-pir-Sensor.salam

WaitMotion

#
func WaitMotion(s: Sensor, timeout_ms: int): bool

Checks Motion once per millisecond for up to the given number of milliseconds and returns true as soon as motion appears, false if it never does. On a computer the waiting only advances the simulated clock.

The example for this item is shown with the ones above: hw-pir-Sensor.salam