Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Arduino

You're reading from   Mastering Arduino A project-based approach to electronics, circuits, and programming

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781788830584
Length 372 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (23) Chapters Close

Preface The Arduino FREE CHAPTER Basic Electronics Circuit Diagrams Basic Prototyping Arduino IDE Programming the Arduino - The Basics Programming the Arduino - Beyond the Basics Motion Sensor Environment Sensors Obstacle Avoidance and Collision Detection Fun with Lights Fun with Sound Using LCD Displays Speech Recognition and Voice Synthesizing DC Motors and Motor Controllers Servo Motors Using a Relay Remotely Controlling the Arduino Creating a Robot Bluetooth LE Bluetooth Classic Another Book You May Enjoy

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) { Serial.println("Motion Detected"); } delay(500); }

This code starts off by using the #define directive to create...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image