O'Reilly logo

Mastering Arduino by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code

To use the HC-SR501 motion sensor all we need to do is read the digital output from the sensor. If the output is HIGH, then the sensor detected motion and if it is LOW, then it did not. The output from the sensor will stay HIGH for the length of time defined by the output time adjustment screw. I usually keep the output time low, usually a couple oof seconds.

For this project, we will output the status of the sensor to the serial console. The output will get a little fancier in the challenge section.

The following is the code to read the HC-SR501 motion sensor:

#define MOTION_SENSOR 3

void setup() {
 pinMode(MOTION_SENSOR, INPUT);
  Serial.begin(9600);
} void loop() { int sensorValue = digitalRead(MOTION_SENSOR); if (sensorValue == HIGH) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required