ARDUINO SESSION 5
Topics:
Hands-on with
a. PIR Motion Sensor
b. Ultrasonic Sensor
Dr. Swarna Priya RM,
Associate Professor, SCORE
7/29/2024 Dr. Swarna Priya RM
PIR MOTION SENSOR
int led = 9; // Led positive terminal to the digital pin 9.
int sensor = 5; // signal pin of sensor to digital pin 5.
int val = 0;
void setup() {
pinMode(led, OUTPUT); // Led is determined as an output here.
pinMode(sensor, INPUT); // PIR motion sensor is determined as an
input here.
[Link](9600);
}
7/29/2024 Dr. Swarna Priya RM
void loop(){
val = digitalRead(sensor);
if (val == HIGH) {
digitalWrite(led, HIGH);
[Link](" Motion detected ");
}
else {
digitalWrite(led, LOW);
[Link]("The action/ motion has stopped");
}
}
7/29/2024 Dr. Swarna Priya RM
Ultrasonic Sensor
long duration; // Variable to store time taken to the pulse to reach
receiver
int distance; // Variable to store distance calculated using formula
int trigPin = 11;
int echoPin = 12;
void setup()
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
[Link](9600);
[Link]("Distance measurement using Arduino Uno.");
delay(500);
}
7/29/2024 Dr. Swarna Priya RM
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // wait for 2 ms to avoid collision in serial monitor
digitalWrite(trigPin, HIGH); // turn on the Trigger to generate pulse
delayMicroseconds(10); // keep the trigger "ON" for 10 ms to generate pulse for 10
ms.
digitalWrite(trigPin, LOW); // Turn off the pulse trigger to stop pulse generation
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.0344 / 2; // Expression to calculate distance using time
[Link]("Distance: ");
[Link](distance); // Print the output in serial monitor
[Link](" cm");
delay(100);
}
7/29/2024 Dr. Swarna Priya RM