Worksheet - 2 IOT Khu
Worksheet - 2 IOT Khu
: 2
Case 1: If the distance less than 20 cm, display “Too Close” on the LCD.
Case 2: If the distance is between 20 cm and 50 cm, display “Safe Distance” on the LCD.
Case 3: If the distance is greater than 50 cm, display “Far Away” on the LCD.
Ultrasonic Sensor:
• VCC → 5V on Arduino.
• GND → GND on Arduino.
• Trig → Digital Pin 9 on Arduino.
• Echo → Digital Pin 8 on Arduino.
LCD (I2C):
• VCC → 5V on Arduino.
• GND → GND on Arduino.
• SDA → A4 on Arduino.
• SCL → A5 on Arduino.
Case 1: If the distance less than 20 cm, display “Too Close” on the LCD.
Case 2: If the distance is between 20 cm and 50 cm, Case 3: If the distance is greater than 50 cm,
display “Safe Distance” on the LCD. display “Far Away” on the LCD.
4. Coding :
// C++ code
#include <LiquidCrystal_I2C.h>
// Initialize the I2C LCD (Address 0x27 and 16x2 display)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Ultrasonic Sensor Pins
const int trigPin = 9;
const int echoPin = 10;
void setup() {
// Initialize LCD and Serial Monitor
lcd.init();
lcd.backlight();
Serial.begin(9600);
// Set Ultrasonic Sensor Pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lcd.print("Distance Test");
delay(2000);
lcd.clear(); }
void loop() {
// Send Trigger Pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read Echo Pulse
long duration = pulseIn(echoPin, HIGH);
// CalcuLate Distance (cm) or handle timeout
float distance;
if (duration == 0) {
distance = -1; // Error value
} else {
distance = (duration * 0.0343) / 2; }
Serial.print("Distance: ");
if (distance == -1) {
Serial.println("Error: No signal");
} else {
Serial.print(distance);
Serial.println(" cm"); }
// Display on LCD
lcd.setCursor(0, 0); // First row
if (distance == -1) {
lcd.print("Error: No signal ");
} else {
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm "); }
lcd.setCursor(0, 1); // Second row
if (distance == -1) {
lcd.print("Check sensor ");
} else if (distance < 20.0) {
lcd.print("Too Close ");
} else if (distance >= 20.0 && distance <= 50.0) {
lcd.print("Safe Distance");
} else {
lcd.print("Far Away "); }
delay(500); // Delay for stability }
Evaluation Grid (To be created as per the SOP and Assessment guidelines by the faculty):
Teacher Signature