⚠ यह कार्रवाई अनुमति नहीं है!
📗 NIELIT O Level · M4-R5 · Practical Chapter

Chapter 4: Building IoT Applications — Arduino IDE, Embedded C व 25+ Sensor Codes (Copy-Ready)

इस practical chapter में आप Arduino IDE से IoT applications बनाना सीखेंगे — Embedded C basics, loops, arrays, functions, और हर sensor की hardware deep-dive (अंदर क्या होता है, कितना voltage, कौन-से pins) के साथ 25+ copy-ready codes — हर code के साथ आसान हिंदी explanation।

📑 12 Sections 💻 25+ Codes 📋 Copy Button ❓ 50 MCQs + 15 Q 🗓 Updated 2026
👉 सभी chapters देखने के लिए swipe करें
📑 Table of Contents — किसी भी topic पर सीधे जाएँ
4.0

Arduino IDE — Introduction

Arduino IDE (Integrated Development Environment) एक free, open-source software है जिसमें Arduino boards (UNO, Mega, Nano, ESP32) को program किया जाता है। Simple words में — यह एक text editor + compiler + uploader tool है: code लिखो → compile करो → board पर upload करो।

🔄 Arduino Workflow (Diagram)

Code से LED Blink तक की Journey

✍️ Write Sketchsetup() + loop() ✅ VerifyCompile + Error check ➡️ UploadUSB से board पर 🖥️ Serial MonitorDebug + Data देखना

🧩 IDE Interface के 5 Main Parts

Partकाम
Sketch Areaजहाँ code लिखा जाता है
Verify Button (✅)Code compile करता है और errors दिखाता है
Upload Button (➡️)Compiled code को USB से board पर भेजता है
Serial MonitorBoard व computer के बीच real-time data दिखाता है (sensor values, debugging)
Message AreaErrors, warnings व uploading status दिखाता है

📝 Sketch की Structure — setup() और loop()

  • void setup(): Program की शुरुआत में सिर्फ एक बार चलता है — initialization जैसे pinMode(), Serial.begin()
  • void loop(): बार-बार लगातार चलता रहता है — main logic (LED blink, sensor reading) यहीं लिखा जाता है।
💻 पहला Program — LED Blink
// LED Blink Program in Arduino IDE
void setup() {
  pinMode(13, OUTPUT);    // Pin 13 ko output mode me set karna
}

void loop() {
  digitalWrite(13, HIGH); // LED ON
  delay(1000);            // 1 second wait
  digitalWrite(13, LOW);  // LED OFF
  delay(1000);            // 1 second wait
}
समझें: setup() में pin 13 को OUTPUT बनाया → loop() में HIGH (5V) से LED ON, 1 sec रुको, LOW (0V) से OFF, 1 sec रुको — यह cycle हमेशा दोहराती रहेगी। Board पर pin 13 वाली LED 1-1 second पर blink करेगी।

⬆️ Upload करने के 3 Steps

  • 1. Correct board select करें — Tools → Board → Arduino UNO।
  • 2. Correct port चुनें — Tools → Port → COM3 (आदि)।
  • 3. "Upload" दबाएँ और "Done Uploading" message का इंतज़ार करें।
Exam Point: Common compile error — digitalwrite (small 'w') लिखने पर IDE दिखाएगा: 'digitalwrite' was not declared in this scope — क्योंकि Embedded C case-sensitive है। सही: digitalWrite

🖥️ Serial Monitor का उपयोग

💻 Serial Monitor पर Sensor Value देखना
void setup() {
  Serial.begin(9600);   // Serial communication start (9600 baud rate)
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);  // Value serial monitor par print hogi
  delay(1000);
}
समझें: Serial.begin(9600) computer से 9600 bits/second की speed पर बात शुरू करता है → हर 1 second में A0 pin की value (0–1023) Serial Monitor पर print होती है।

✔️ Advantages of Arduino IDE

  • Free व open-source — beginners के लिए easy।
  • Multiple boards support (UNO, Mega, Nano, ESP32)।
  • Built-in libraries व ready examples।
  • Serial Monitor से real-time debugging।
  • Windows, Mac, Linux — सभी OS पर चलता है।
4.1

Embedded C — Language Basics

Embedded C — C जैसी language जो microcontrollers (Arduino, AVR, ARM, ESP32) पर hardware control के लिए उपयोग होती है। उद्देश्य: sensors से data लेना, actuators control करना, real-time tasks करना। Programs छोटे, fast व hardware-specific होते हैं।

1️⃣ Variables & Identifiers

Variable = memory में data store करने का नाम। Rules:

  • हमेशा alphabet या underscore (_) से शुरू हो — digit से नहीं।
  • Spaces व special characters (%, #, @) allowed नहीं।
  • Case-sensitive: Temp और temp अलग-अलग हैं।
  • Keywords (int, float, char) variable name नहीं बन सकते।
💻 Valid vs Invalid Variables
int ledPin = 13;       // ✅ Valid variable
int _counter = 0;      // ✅ Valid variable
int 2sensor = 10;      // ❌ Invalid (digit se start nahi kar sakte)
int float = 20;        // ❌ Invalid (float ek keyword hai)

2️⃣ Data Types

Data TypeSizeRangeExample
bool1 bytetrue / falsebool isON = true;
char1 byte-128 to 127char grade = 'A';
int2 bytes-32,768 to 32,767int temp = 25;
unsigned int2 bytes0 to 65,535unsigned int speed = 40000;
long4 bytes-2,147,483,648 to 2,147,483,647long counter = millis();
float4 bytes6 decimal digitsfloat voltage = 3.14;
Exam Point: int = 2 bytes (-32,768 to 32,767); float = 4 bytes — sizes व ranges exam में पूछे जाते हैं। Note: UNO व ESP32 में int की size अलग हो सकती है।

3️⃣ Constants

वह value जो program के दौरान change नहीं होती — दो तरीके:

💻 Constants के 2 तरीके
#define LED 13              // Preprocessor constant
const int baudRate = 9600;  // Typed constant (memory efficient — macros se behtar)

4️⃣ Operators

CategoryOperatorsउदाहरण
Arithmetic+  -  *  /  %10 % 3 = 1 (remainder)
Relational==  !=  >  <  >=  <=a > b
Logical&& (AND)  || (OR)  ! (NOT)a > 5 && b < 10
Assignment=  +=  -=  *=  /=  %=a += 5 (यानी a = a + 5)
💻 Operators in Action
int a = 10, b = 3;
int sum  = a + b;      // 13
int diff = a - b;      // 7
int mod  = a % b;      // 1 (remainder)
if (a > b && b != 0) {
  Serial.println("Condition True");
}

🧠 Practice Program — Sensor Voltage Calculate करना

💻 Variables + Constants + Operators साथ में
const int SENSOR_PIN = A0;
const float VREF = 5.0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int value = analogRead(SENSOR_PIN);        // Sensor data read (0-1023)
  float voltage = (value * VREF) / 1023.0;   // Voltage me convert
  Serial.print("Sensor Value: ");
  Serial.print(value);
  Serial.print("  Voltage: ");
  Serial.println(voltage);
  delay(500);
}
समझें: analogRead 0–1023 की digital value देता है → formula (value × 5.0) ÷ 1023 से इसे असली voltage (0–5V) में बदला जाता है। जैसे value = 512 → voltage ≈ 2.5V।
Important Points: हर statement के बाद semicolon (;) ज़रूरी। Integer division: 7/3 = 2 (decimal चाहिए तो 7.0/3 लिखें)। const variables macros से memory efficient होते हैं।
4.2

Conditional Statements और Loops

Conditional Statements program को decision लेने की शक्ति देते हैं (if, if-else, else-if, switch); Loops repetitive tasks के लिए (while, do-while, for)। IoT में sensor values check करने व automation के लिए यही सबसे ज़्यादा उपयोग होते हैं।

🔀 A. Conditional Statements

if Statement — condition true तो block चले

💻 if — Fan ON
int temp = 30;
if (temp > 25) {
  Serial.println("Fan ON");   // Output: Fan ON (kyunki 30 > 25)
}

if-else — दो possibilities (true/false)

💻 if-else — Light से LED Control
int light = analogRead(A0);
if (light < 500) {
  digitalWrite(13, HIGH);  // Andhera hai — LED ON
} else {
  digitalWrite(13, LOW);   // Roshni hai — LED OFF
}

else-if Ladder — कई conditions में से एक

💻 else-if — Temperature Levels
int temp = 28;
if (temp < 20)
  Serial.println("Low Temp");
else if (temp < 30)
  Serial.println("Normal Temp");   // Output: Normal Temp
else
  Serial.println("High Temp");

Nested if — condition के अंदर condition

💻 Nested if — Dehumidifier Logic
int temp = 35;
int humidity = 80;

if (temp > 30) {
  if (humidity > 70) {
    Serial.println("Turn ON Dehumidifier");
  }
}

switch — एक variable की multiple values

💻 switch — Mode Selection
int mode = 2;

switch (mode) {
  case 1: Serial.println("Manual Mode"); break;
  case 2: Serial.println("Auto Mode");   break;   // Output: Auto Mode
  case 3: Serial.println("Sleep Mode");  break;
  default: Serial.println("Invalid Mode");
}
Exam Point: switch में हर case के बाद break ज़रूरी है वरना अगले cases भी चल जाते हैं (fall-through); कोई case match न होने पर default चलता है।

🔁 B. Loops (Iteration)

while Loop — condition true तक चले

💻 while — 0 से 4 print
int i = 0;
while (i < 5) {
  Serial.println(i);   // Output: 0 1 2 3 4
  i++;
}

do-while — पहले चले, फिर condition check (कम से कम 1 बार ज़रूर)

💻 do-while Loop
int i = 0;
do {
  Serial.println(i);
  i++;
} while (i < 5);

for Loop — fixed बार दोहराना

💻 for — LED 10 बार Blink
for (int i = 0; i < 10; i++) {
  digitalWrite(13, HIGH);
  delay(200);
  digitalWrite(13, LOW);
  delay(200);
}

Nested Loops — loop के अंदर loop (pattern printing)

💻 Nested for — 3×3 Star Pattern
for (int row = 0; row < 3; row++) {
  for (int col = 0; col < 3; col++) {
    Serial.print("* ");
  }
  Serial.println();
}
// Output:
// * * *
// * * *
// * * *

Infinite Loop

💻 while(true) — हमेशा चलने वाला
while (true) {
  Serial.println("Running forever...");
  delay(1000);
}
Exam Point: Arduino का loop() function खुद एक infinite loop की तरह चलता है। do-while कम से कम एक बार ज़रूर चलता है — while से यही अंतर है।

🧠 Practice — Automatic Fan Control

💻 Conditions + Loop साथ में
const int TEMP_PIN = A0;
const int FAN_PIN = 9;

void setup() {
  Serial.begin(9600);
  pinMode(FAN_PIN, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(TEMP_PIN);
  float temp = (sensorValue * 5.0 / 1023.0) * 100;  // °C me convert
  Serial.print("Temp: ");
  Serial.println(temp);

  if (temp > 35)
    digitalWrite(FAN_PIN, HIGH);  // Fan ON
  else
    digitalWrite(FAN_PIN, LOW);   // Fan OFF

  delay(1000);
}
Beginner Tips: if के बाद गलती से semicolon न लगाएँ (if (x==1); ❌); हर condition parentheses ( ) में रखें; ज़्यादा delay() से real-time speed प्रभावित होती है — timers बेहतर हैं।
4.3

Arrays — एक नाम, कई Values

Array = एक ही नाम से कई similar values store करने वाला variable (collection of similar data elements)। IoT में sensor readings, multiple LEDs control व data buffer के लिए उपयोग होता है। Index हमेशा 0 से शुरू होता है।

1️⃣ Declaration व Initialization

💻 Array बनाने के तरीके
// Syntax: data_type array_name[size];
int sensor[4];                          // Empty array (4 elements)
int temp[5] = {25, 27, 29, 31, 30};     // Declaration + values
int ledPins[4] = {2, 3, 4, 5};
float readings[3] = {3.3, 4.1, 5.0};
int marks[] = {25, 28, 30, 32};         // Size optional jab values di ho

2️⃣ Elements को Access व Update करना

💻 Index से Access (0 से शुरू)
int temp[3] = {25, 27, 30};
Serial.println(temp[0]);  // Output: 25 (pehla element)
Serial.println(temp[2]);  // Output: 30 (teesra element)

int led[3] = {2, 3, 4};
led[1] = 8;               // 2nd element ab 8 ho gaya → {2, 8, 4}

3️⃣ Loops के साथ Arrays — सबसे powerful combination

💻 4 LEDs एक के बाद एक Blink
int ledPins[4] = {2, 3, 4, 5};

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 4; i++) {
    digitalWrite(ledPins[i], HIGH);
    delay(200);
    digitalWrite(ledPins[i], LOW);
  }
}
समझें: चारों pins array में हैं — for loop हर pin को बारी-बारी ON/OFF करता है। 4 अलग variables व 8 lines की जगह सिर्फ एक loop! यही array की power है।

🧠 Practical — 5 Readings का Average

💻 Sensor Readings Store + Average
const int TEMP_PIN = A0;
float readings[5];
int index = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  readings[index] = analogRead(TEMP_PIN) * (5.0 / 1023.0);
  index++;

  if (index == 5) {
    float sum = 0;
    for (int i = 0; i < 5; i++) {
      sum += readings[i];
    }
    float avg = sum / 5;
    Serial.print("Average Voltage: ");
    Serial.println(avg);
    index = 0;   // Reset
  }
  delay(1000);
}

4️⃣ 2D (Multi-Dimensional) Arrays

💻 Rows × Columns में Data
int matrix[2][3] = {
  {1, 2, 3},
  {4, 5, 6}
};
Serial.println(matrix[1][2]);  // Output: 6 (row 1, column 2)
Exam Points: Index 0 से शुरू; limit से बाहर access = undefined behavior; string (char array) के अंत में हमेशा '\0' (null character) होना चाहिए; matrix[1][2] = दूसरी row का तीसरा element।
4.4

Functions और Arduino Libraries

Function = code का block जो कोई specific task करता है — इससे program modular, readable व reusable बनता है। Structure: return_type function_name(parameters) { ... return value; }

1️⃣ User-defined Function

💻 blinkLED() — Custom Function
int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  blinkLED(3);   // Function call — LED 3 baar blink karegi
}

void blinkLED(int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(ledPin, HIGH);
    delay(300);
    digitalWrite(ledPin, LOW);
    delay(300);
  }
}
समझें: blinkLED(3) call करते ही parameter times = 3 बन जाता है → loop 3 बार चलकर LED blink कराता है। बार-बार वही code लिखने की ज़रूरत नहीं!

2️⃣ Function Prototype

💻 Prototype — Compiler को पहले बताना
void displayTemperature(float temp);   // Prototype (program ke top par)

void setup() {
  Serial.begin(9600);
  displayTemperature(25.6);
}

void displayTemperature(float temp) {
  Serial.print("Temperature: ");
  Serial.println(temp);
}

3️⃣ Return Type वाला Function

💻 addNumbers() — Value वापस भेजना
int addNumbers(int a, int b) {
  return a + b;
}

void setup() {
  Serial.begin(9600);
  int result = addNumbers(5, 10);
  Serial.print("Sum = ");
  Serial.println(result);   // Output: Sum = 15
}

4️⃣ Functions के 3 Types

TypeविवरणExamples
Built-in FunctionsArduino IDE के ready-madedigitalWrite(), analogRead(), pinMode()
User-definedDeveloper द्वारा बनाए गएblinkLED(), readSensorData()
Library FunctionsExternal libraries सेlcd.print(), dht.readTemperature()

5️⃣ Arduino Libraries — Ready-made Code

Libraries hardware को few lines में control करने देती हैं — include: #include <LibraryName.h>; Install: Sketch → Include Library → Manage Libraries; Examples: File → Examples।

LibraryPurposeExample Function
Wire.hI2C communication (LCD, sensors)Wire.beginTransmission()
LiquidCrystal.hLCD display controllcd.print("Hello");
DHT.hTemperature & Humidity sensorsdht.readTemperature();
Servo.hServo motor controlservo.write(90);
SoftwareSerial.hBluetooth/Serial communicationBTSerial.read();
Keypad.hKeypad inputkeypad.getKey();
Exam Point: Library include करते समय spelling case-sensitive होती है; missing library error आए तो Manage Libraries से install करें। Wire.h = I2C, Servo.h = servo, DHT.h = temperature/humidity — mapping याद रखें।
4.5

Sensor Interfacing Basics — Digital vs Analog Pins

Sensor Interfacing = microcontroller को बाहरी devices से जोड़ना ताकि physical world का data digital signals में बदले। Arduino में दो तरह के pins होते हैं — Digital pins (0–13) और Analog pins (A0–A5) — sensor के nature के अनुसार जोड़ते हैं।

⚖️ Digital vs Analog — Master Comparison

TypeSignal RangeExample SensorsRead Function
Digital0 या 1 (HIGH/LOW)IR, PIR Motion, Flame, TouchdigitalRead(pin)
Analog0 से 1023 (0–5V proportional)LDR, LM35, MQ135, PotentiometeranalogRead(pin)
Exam Point: analogRead की range 0–1023 है (10-bit ADC: 2¹⁰ = 1024 values); analogWrite (PWM) की range 0–255 (8-bit)। Voltage formula: V = value × 5.0 ÷ 1023।

🔘 पहली Interfacing — Button से LED Control

💻 Button (Input) + LED (Output)
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH)
    digitalWrite(ledPin, HIGH);   // Button dabaya → LED ON
  else
    digitalWrite(ledPin, LOW);    // Button chhoda → LED OFF
}
Beginner Tips: VCC (power) व GND (ground) हमेशा सही लगाएँ; analog sensors को A0, A1 जैसे pins से जोड़ें; data smooth करने के लिए average/filter algorithm उपयोग करें; sensor की datasheet से correct voltage ज़रूर check करें।
4.6

Sensors Hardware Deep-Dive — हर Sensor के अंदर क्या है + Code

इस section में हर sensor की internal structure (अंदर कौन-से components), operating voltage, pins, range और copy-ready Arduino code दिया गया है — exam व practical दोनों के लिए complete package।

🌞 1. LDR (Light Dependent Resistor) — Analog

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर का materialCadmium Sulphide (CdS) photoresistive cell — रोशनी पड़ने पर electrons free होते हैं
Resistanceअँधेरे में ~1 MΩ (बहुत high) → तेज़ रोशनी में ~few hundred Ω (बहुत low)
Operating Voltageकोई fixed नहीं — 3.3V/5V circuit में 10kΩ resistor के साथ voltage divider बनाकर लगाते हैं
Pins2 legs (no polarity) — एक 5V से, दूसरा A0 + 10kΩ से GND
PrincipleLight ↑ → Resistance ↓ → A0 पर voltage ↑
💻 LDR — Automatic Street Light
const int ldrPin = A0;
const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int lightValue = analogRead(ldrPin);   // 0-1023
  Serial.print("Light Value: ");
  Serial.println(lightValue);

  if (lightValue < 400) {                // Andhera detect
    digitalWrite(ledPin, HIGH);          // Street light ON
  } else {
    digitalWrite(ledPin, LOW);           // Light OFF
  }
  delay(500);
}
समझें: अँधेरे में LDR का resistance बढ़ता है → A0 की value कम आती है → 400 से नीचे जाते ही LED (street light) ON। Threshold (400) अपने कमरे की रोशनी के अनुसार Serial Monitor देखकर adjust करें।

🌡️ 2. LM35 Temperature Sensor — Analog

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर का materialPrecision semiconductor junction (IC) — temperature के proportional voltage generate करता है
Operating Voltage4V – 30V (आमतौर पर 5V)
Pins (3)VCC | Vout (middle) | GND — flat side सामने रखने पर left से right
Range / Accuracy-55°C से +150°C, accuracy ±0.5°C
Output Formula10 mV per °C — 25°C = 250 mV, 100°C = 1V
💻 LM35 — Temperature °C में पढ़ना
const int lm35Pin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int value = analogRead(lm35Pin);
  float voltage = value * (5.0 / 1023.0);   // Volt me convert
  float tempC = voltage * 100;              // 10mV/°C → V × 100 = °C

  Serial.print("Temperature: ");
  Serial.print(tempC);
  Serial.println(" °C");
  delay(1000);
}
समझें: value → voltage → ×100 = temperature। जैसे value = 61 → voltage ≈ 0.298V → temp ≈ 29.8°C। कोई library नहीं चाहिए — यही LM35 की खूबी है।

💧 3. DHT11 (Temperature + Humidity) — Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 3 चीज़ें1) NTC Thermistor (temperature के लिए) 2) Capacitive Humidity Sensor (2 electrodes के बीच moisture-holding substrate) 3) 8-bit chip जो दोनों readings को digital signal में भेजती है
Operating Voltage3.3V – 5.5V
Pins (module: 3)VCC | DATA | GND (bare sensor में 4 pins — तीसरा NC)
Temperature Range0–50°C, accuracy ±2°C
Humidity Range20–90% RH, accuracy ±5%
Sampling Rate1 reading per second (1 Hz)
💻 DHT11 — Temperature + Humidity (DHT.h library)
#include <DHT.h>

#define DHTPIN 2          // DATA pin → Digital pin 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  float temp = dht.readTemperature();   // °C
  float hum  = dht.readHumidity();      // %

  if (isnan(temp) || isnan(hum)) {
    Serial.println("Sensor Error!");
    return;
  }

  Serial.print("Temp: ");
  Serial.print(temp);
  Serial.print(" C  Humidity: ");
  Serial.print(hum);
  Serial.println(" %");
  delay(2000);   // DHT11 slow sensor hai — 2 sec gap rakhein
}
समझें: DHT.h library install करें (Manage Libraries → "DHT sensor library" by Adafruit)। isnan() check ज़रूरी — wiring गलत होने पर "Sensor Error" दिखेगा। DHT22 उपयोग करना हो तो सिर्फ DHT22 लिख दें (range -40 से 80°C, ±0.5°C — ज़्यादा accurate)।

📏 4. Ultrasonic Sensor HC-SR04 (Distance) — Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 2 चीज़ें1) Transmitter transducer (T) — 40 kHz की ultrasonic sound waves भेजता है 2) Receiver transducer (R) — टकराकर लौटी echo receive करता है
Operating Voltage / Current5V, ~15mA
Pins (4)VCC | TRIG (trigger — pulse भेजने के लिए) | ECHO (लौटने का time) | GND
Range / Accuracy2 cm – 400 cm, accuracy ±3 mm, angle ~15°
Distance FormulaDistance (cm) = Time (µs) × 0.034 ÷ 2 (sound speed 340 m/s; ÷2 क्योंकि आना-जाना दोनों)
💻 HC-SR04 — Distance Measurement
const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // 10 microsecond ka trigger pulse bhejo
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Echo aane ka time napo (microseconds me)
  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.034 / 2;   // cm me

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(500);
}
समझें: TRIG को 10µs HIGH करते ही sensor 8 sound pulses भेजता है → object से टकराकर echo लौटती है → pulseIn() उस time को microseconds में मापता है → formula से distance। Car parking sensor यही technique है!

🔦 5. IR Sensor Module (Obstacle Detection) — Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 4 चीज़ें1) IR LED (transmitter — infrared light भेजती है) 2) Photodiode (receiver — reflected IR receive करता है) 3) LM393 Comparator IC (signal को clean 0/1 बनाता है) 4) Potentiometer (sensitivity/range adjust करने के लिए)
Operating Voltage3.3V – 5V
Pins (3)VCC | GND | OUT (digital)
Range2 – 30 cm (potentiometer से adjustable)
Output LogicObject detect होने पर OUT = LOW (0) — ज़्यादातर modules में उल्टा logic!
💻 IR Sensor — Obstacle Alarm
const int irPin = 7;
const int buzzerPin = 8;

void setup() {
  pinMode(irPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int obstacle = digitalRead(irPin);

  if (obstacle == LOW) {              // LOW = object detected
    Serial.println("Obstacle Detected!");
    digitalWrite(buzzerPin, HIGH);    // Buzzer ON
  } else {
    digitalWrite(buzzerPin, LOW);
  }
  delay(200);
}
समझें: IR LED की invisible light object से reflect होकर photodiode पर पड़ती है → comparator OUT को LOW कर देता है → हम LOW पर buzzer ON करते हैं। Line follower robots व automatic taps में यही sensor है।

🚶 6. PIR Motion Sensor HC-SR501 — Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 3 चीज़ें1) Pyroelectric Sensor (इंसान/जानवर की body से निकलने वाली infrared heat detect करता है) 2) Fresnel Lens (सफेद dome — IR को sensor पर focus करती है, coverage बढ़ाती है) 3) BISS0001 IC (signal processing)
Operating Voltage4.5V – 12V (board पर internal 3.3V regulator)
Pins (3)VCC | OUT | GND
Range / Angle7 meter तक, ~110°–120° detection angle
2 PotentiometersSensitivity (range) व Time Delay (output कितनी देर HIGH रहे: 0.3s–5min)
💻 PIR — Motion Detection Security Light
const int pirPin = 2;
const int ledPin = 13;

void setup() {
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  delay(30000);   // PIR ko stable hone ke liye 30-60 sec warm-up time
}

void loop() {
  int motion = digitalRead(pirPin);

  if (motion == HIGH) {
    Serial.println("Motion Detected!");
    digitalWrite(ledPin, HIGH);   // Light ON
  } else {
    digitalWrite(ledPin, LOW);
  }
  delay(200);
}
समझें: इंसान के आने पर उसकी body-heat (infrared) का pattern बदलता है → pyroelectric sensor voltage generate करता है → OUT HIGH हो जाता है। ⚠️ PIR को शुरू में 30–60 second warm-up ज़रूर दें वरना false triggers आएँगे।

💨 7. Gas Sensors — MQ2 (Smoke/LPG) व MQ135 (Air Quality) — Analog

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 2 चीज़ें1) SnO₂ (Tin Dioxide) sensing layer — gas के contact में आने पर conductivity बदलती है 2) Heater Coil — sensing layer को गर्म रखती है (इसीलिए sensor चलने पर हल्का गर्म होता है)
Operating Voltage5V (heater को ज़्यादा current चाहिए — 150mA तक)
Pins (4)VCC | GND | A0 (analog value) | D0 (digital — threshold potentiometer से)
MQ2 detect करता हैLPG, Smoke, Methane, Butane, Hydrogen (300–10,000 ppm)
MQ135 detect करता हैNH₃ (Ammonia), CO₂, Benzene, Alcohol, Smoke — Air Quality
Preheat TimeAccurate readings के लिए 24–48 hrs burn-in ideal; कम से कम 20 sec warm-up
💻 MQ2 — Gas Leakage Alarm
const int mq2Pin = A0;
const int buzzerPin = 8;
const int threshold = 400;    // Apne environment ke hisab se adjust karein

void setup() {
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int gasValue = analogRead(mq2Pin);
  Serial.print("Gas Level: ");
  Serial.println(gasValue);

  if (gasValue > threshold) {
    Serial.println("!! GAS LEAK DETECTED !!");
    digitalWrite(buzzerPin, HIGH);   // Alarm ON
  } else {
    digitalWrite(buzzerPin, LOW);
  }
  delay(500);
}
समझें: Gas आते ही SnO₂ layer की conductivity बढ़ती है → A0 value बढ़ती है → threshold पार होते ही buzzer बजता है। MQ135 के लिए same code — बस pin पर MQ135 लगाएँ (air quality monitor बन जाएगा)।

🌱 8. Soil Moisture Sensor — Analog + Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 2 चीज़ें1) 2 Probes (fork जैसी plates) — मिट्टी में current pass करके resistance मापती हैं (गीली मिट्टी = कम resistance) 2) LM393 Comparator board — analog व digital दोनों outputs देता है
Operating Voltage3.3V – 5V
Pins (4)VCC | GND | A0 (moisture level) | D0 (threshold पर 0/1)
Reading Logicसूखी मिट्टी = high value (~800–1023); गीली मिट्टी = low value (~300–500)
💻 Soil Moisture — Smart Irrigation
const int soilPin = A0;
const int relayPin = 7;       // Relay se water pump

void setup() {
  pinMode(relayPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int moisture = analogRead(soilPin);
  Serial.print("Soil Moisture: ");
  Serial.println(moisture);

  if (moisture > 700) {               // Mitti sookhi hai
    digitalWrite(relayPin, HIGH);     // Pump ON
    Serial.println("Pump ON - Watering...");
  } else {
    digitalWrite(relayPin, LOW);      // Pump OFF
  }
  delay(1000);
}
समझें: सूखी मिट्टी current कम pass करती है → value ज़्यादा (700+) → relay से pump ON। पानी मिलते ही value गिरती है → pump OFF। यही Chapter 2 वाला Smart Agriculture system है — अब code के साथ!

🌧️ 9. Rain Sensor — Analog + Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरNickel-coated sensing pad (parallel tracks) — बारिश की बूँदें tracks को short करके resistance घटाती हैं + LM393 comparator board
Operating Voltage3.3V – 5V
Pins (4)VCC | GND | A0 | D0
Logicसूखा pad = high value; बारिश = low value
💻 Rain Sensor — Rain Alert
const int rainPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int rainValue = analogRead(rainPin);

  if (rainValue < 500) {
    Serial.println("Rain Detected! Close the windows.");
  } else {
    Serial.println("No Rain.");
  }
  delay(1000);
}

🎤 10. Sound Sensor KY-037 — Analog + Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरElectret Condenser Microphone (आवाज़ की vibrations को electrical signal में बदलता है) + LM393 comparator + sensitivity potentiometer
Operating Voltage3.3V – 5V
Pins (4)VCC | GND | A0 | D0
💻 Sound Sensor — Clap Switch
const int soundPin = 7;    // D0 pin
const int ledPin = 13;
bool ledState = false;

void setup() {
  pinMode(soundPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(soundPin) == HIGH) {   // Clap detect
    ledState = !ledState;                // State toggle
    digitalWrite(ledPin, ledState);
    delay(500);                          // Double trigger se bachne ke liye
  }
}
समझें: ताली की आवाज़ microphone पर पड़ते ही D0 HIGH होता है → ledState = !ledState से LED का state उल्टा (toggle) हो जाता है — एक ताली ON, दूसरी OFF। यही "clap switch" है!

👆 11. Touch Sensor TTP223 — Digital

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरTTP223 Capacitive touch IC — उँगली छूने पर pad की capacitance बदलती है, IC इसे detect करके OUT HIGH कर देता है
Operating Voltage2V – 5.5V
Pins (3)VCC | GND | SIG (OUT)
💻 Touch Sensor — Touch Light
const int touchPin = 2;
const int ledPin = 13;

void setup() {
  pinMode(touchPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(touchPin) == HIGH) {
    digitalWrite(ledPin, HIGH);   // Touch hua → LED ON
  } else {
    digitalWrite(ledPin, LOW);
  }
}

🔥 12. Flame Sensor — Digital + Analog

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरIR Receiver LED (760–1100 nm wavelength की flame-infrared detect करती है) + LM393 comparator + potentiometer
Operating Voltage3.3V – 5V
Range / Angle~80 cm तक, 60° detection angle
PinsVCC | GND | D0 (कुछ modules में A0 भी)
💻 Flame Sensor — Fire Alarm
const int flamePin = 2;
const int buzzerPin = 8;

void setup() {
  pinMode(flamePin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(flamePin) == LOW) {     // Flame detected (module par LOW)
    Serial.println("!! FIRE DETECTED !!");
    digitalWrite(buzzerPin, HIGH);
  } else {
    digitalWrite(buzzerPin, LOW);
  }
  delay(200);
}

🎛️ 13. Potentiometer व Tilt Sensor

🔩 Hardware के अंदर क्या है?

DeviceअंदरVoltage / Pins
Potentiometer (10kΩ)Resistive track + घूमने वाला wiper — घुमाने पर resistance बँटता है (voltage divider)3 pins: VCC | Wiper (A0) | GND
Tilt Sensor (SW-520D)Metal ball वाली छोटी tube — झुकाने पर ball दो contacts को जोड़ती/तोड़ती है2 pins (digital switch की तरह)
💻 Potentiometer — LED Brightness Control (PWM)
const int potPin = A0;
const int ledPin = 9;     // PWM pin (~ wale pins: 3,5,6,9,10,11)

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int potValue = analogRead(potPin);                // 0-1023
  int brightness = map(potValue, 0, 1023, 0, 255);  // 0-255 me convert
  analogWrite(ledPin, brightness);                  // PWM se brightness
}
समझें: map() function 0–1023 की range को 0–255 (PWM) में बदलता है → knob घुमाते ही LED की brightness smooth बदलती है। PWM pins पर ~ का निशान होता है (3, 5, 6, 9, 10, 11)।
Exam Point: Sensor modules में बार-बार दिखने वाली LM393 Comparator IC — analog signal को clean digital (0/1) में बदलती है; Potentiometer — sensitivity/threshold adjust करता है। ये दोनों IR, Soil, Rain, Sound, Flame, MQ सबमें मिलते हैं।
4.7

Output Devices — LED, Buzzer, Servo, Motor, 7-Segment + Codes

Sensors input देते हैं, तो output devices action करते हैं — रोशनी, आवाज़, movement। यहाँ हर output device की hardware detail व copy-ready code है।

🔔 1. Buzzer — Active vs Passive

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरPiezoelectric disc — voltage मिलने पर vibrate होकर आवाज़ बनाती है
Active Buzzerअंदर oscillator circuit है — सिर्फ HIGH देने से fixed tone बजता है
Passive BuzzerOscillator नहीं — tone() से frequency देनी पड़ती है (गाने बजा सकते हैं!)
Operating Voltage3.3V – 5V | Pins: + (long leg) व –
💻 Buzzer — Beep Sound (tone/noTone)
const int buzzerPin = 9;

void setup() {
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  tone(buzzerPin, 1000);   // 1000 Hz frequency par sound
  delay(500);
  noTone(buzzerPin);       // Sound band
  delay(500);
}

⚙️ 2. Servo Motor SG90 — Precise Angle Control

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर 4 चीज़ें1) छोटी DC Motor 2) Gear Box (speed घटाकर torque बढ़ाता है) 3) Potentiometer (current position feedback) 4) Control Circuit (PWM signal से target angle compare)
Operating Voltage4.8V – 6V | Torque: ~1.8 kg-cm
Pins (3 wires)Brown = GND | Red = VCC | Orange = Signal (PWM)
Rotation0° से 180° (precise position) — PWM 50Hz control
💻 Servo — 0° → 90° → 180° Sweep
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);    // Signal wire → Pin 9
}

void loop() {
  myServo.write(0);     // 0 degree
  delay(1000);
  myServo.write(90);    // 90 degree
  delay(1000);
  myServo.write(180);   // 180 degree
  delay(1000);
}
समझें: servo.write(angle) से exact angle सेट होता है — अंदर का potentiometer position feedback देता रहता है। Robot arms, smart dustbin के ढक्कन व CCTV pan-tilt में यही servo है।

🌀 3. DC Motor — Speed Control (PWM)

🔩 Hardware Note

DC motor को Arduino pin से सीधे न जोड़ें — motor ज़्यादा current (100mA+) खींचती है जबकि Arduino pin सिर्फ ~40mA दे सकता है। बीच में transistor (जैसे BC547/TIP120) या Motor Driver (L293D/L298N) लगाएँ + back-EMF से बचने के लिए diode।

💻 DC Motor — Speed धीरे-धीरे बढ़ाना/घटाना
const int motorPin = 9;   // Transistor/driver ke through

void setup() {
  pinMode(motorPin, OUTPUT);
}

void loop() {
  // Speed 0 se 255 tak badhao
  for (int s = 0; s <= 255; s++) {
    analogWrite(motorPin, s);
    delay(10);
  }
  // Speed 255 se 0 tak ghatao
  for (int s = 255; s >= 0; s--) {
    analogWrite(motorPin, s);
    delay(10);
  }
}

🔢 4. 7-Segment Display — 0 से 9 Counter

🔩 Hardware के अंदर क्या है?

DetailValue
अंदर8 LEDs (7 segments a–g + 1 decimal point) एक digit के आकार में arranged
2 TypesCommon Cathode (सभी LEDs का – common; segment HIGH = ON) व Common Anode (सभी का + common; segment LOW = ON)
Voltageहर segment एक LED है — 2V, current limit के लिए 220Ω resistors ज़रूरी
💻 7-Segment — 0-9 Counter (Common Cathode)
int seg[] = {2, 3, 4, 5, 6, 7, 8};   // a,b,c,d,e,f,g pins

byte nums[10][7] = {
  {1,1,1,1,1,1,0},  // 0
  {0,1,1,0,0,0,0},  // 1
  {1,1,0,1,1,0,1},  // 2
  {1,1,1,1,0,0,1},  // 3
  {0,1,1,0,0,1,1},  // 4
  {1,0,1,1,0,1,1},  // 5
  {1,0,1,1,1,1,1},  // 6
  {1,1,1,0,0,0,0},  // 7
  {1,1,1,1,1,1,1},  // 8
  {1,1,1,1,0,1,1}   // 9
};

void setup() {
  for (int i = 0; i < 7; i++) pinMode(seg[i], OUTPUT);
}

void loop() {
  for (int n = 0; n < 10; n++) {
    for (int i = 0; i < 7; i++) {
      digitalWrite(seg[i], nums[n][i]);
    }
    delay(1000);
  }
}
समझें: 2D array nums में हर digit का pattern है (कौन-से segments ON) → nested loop हर second अगला digit दिखाता है। यह section 4.3 के 2D arrays का perfect practical use है!

🌈 5. RGB LED — तीन रंगों वाली LED

💻 RGB LED — Red, Green, Blue Colors
const int redPin = 9, greenPin = 10, bluePin = 11;   // PWM pins

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void setColor(int r, int g, int b) {
  analogWrite(redPin, r);
  analogWrite(greenPin, g);
  analogWrite(bluePin, b);
}

void loop() {
  setColor(255, 0, 0);   delay(1000);   // Red
  setColor(0, 255, 0);   delay(1000);   // Green
  setColor(0, 0, 255);   delay(1000);   // Blue
  setColor(255, 255, 0); delay(1000);   // Yellow (R+G)
}
समझें: RGB LED के अंदर 3 LEDs (Red, Green, Blue) होती हैं — तीनों की brightness (0–255) mix करके 1.6 करोड़ रंग बन सकते हैं। यहाँ custom function setColor() का उपयोग भी देखिए (section 4.4)।
4.8

LCD Display व Keypad Interfacing

IoT projects में 16×2 LCD (16 columns × 2 rows) sensor data दिखाने के लिए और Keypad user input (password, commands) लेने के लिए उपयोग होता है।

🖥️ A. 16×2 LCD Display

🔩 Hardware के अंदर क्या है?

DetailValue
अंदरHD44780 controller chip + 32 character cells (हर cell 5×8 pixels की dot matrix)
Operating Voltage5V, backlight के साथ ~25mA
Total Pins16 pins

⚙️ Pin Configuration (16×2 LCD)

Pin No.NameFunction
1VSSGround
2VDD+5V Supply
3V0Contrast Adjustment (10kΩ potentiometer से)
4RSRegister Select (Command/Data चुनना)
5RWRead/Write (आमतौर पर GND = Write)
6ENEnable Signal
11–14D4–D7Data Pins (4-bit mode)
15–16A, KBacklight LED (+ व –)
💻 LCD — "Hello IoT World!" Display
#include <LiquidCrystal.h>

// LCD pins → Arduino (RS, EN, D4, D5, D6, D7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);               // 16 column, 2 row LCD initialize
  lcd.print("Hello IoT World!");
}

void loop() {
}
💻 LCD — Live Temperature Display (LM35)
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int tempPin = A0;

void setup() {
  lcd.begin(16, 2);
  lcd.print("Temp: ");
}

void loop() {
  int sensorValue = analogRead(tempPin);
  float voltage = sensorValue * (5.0 / 1023.0);
  float temperature = voltage * 100;    // LM35: 10mV/°C

  lcd.setCursor(0, 1);    // Column 0, Row 1 (doosri line)
  lcd.print(temperature);
  lcd.print(" C   ");
  delay(1000);
}
LCD Tips: lcd.clear() = display साफ; lcd.setCursor(col, row) = position सेट; V0 pin पर potentiometer न लगाने से display खाली दिखता है (सबसे common गलती!)।

⌨️ B. 4×3 Keypad Interfacing

🔩 Hardware के अंदर क्या है?

Keypad के अंदर rows व columns की matrix होती है — हर button एक row wire को एक column wire से जोड़ता है। Library scanning करके पता लगाती है कि कौन-सा button दबा। 4×3 keypad = 4 row pins + 3 column pins = 7 wires।

💻 Keypad — Pressed Key पढ़ना
#include <Keypad.h>

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
  Serial.begin(9600);
  Serial.println("Press a Key:");
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    Serial.print("You pressed: ");
    Serial.println(key);
  }
}

🔐 C. Mini Project — Password Access System (Keypad + LCD)

💻 Password System — Access Granted/Denied
#include <LiquidCrystal.h>
#include <Keypad.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {A3, A2, A1};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

String password = "1234";
String input = "";

void setup() {
  lcd.begin(16, 2);
  lcd.print("Enter Password:");
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    if (key == '#') {                  // # = submit
      lcd.clear();
      if (input == password) {
        lcd.print("Access Granted");
      } else {
        lcd.print("Access Denied");
      }
      input = "";
      delay(2000);
      lcd.clear();
      lcd.print("Enter Password:");
    } else {
      input += key;                    // Key ko input me jodo
      lcd.setCursor(0, 1);
      lcd.print(input);
    }
  }
}
समझें: हर key दबाने पर input string में जुड़ती है व LCD की दूसरी line पर दिखती है → '#' दबाते ही input की तुलना password ("1234") से होती है → match = "Access Granted"। Smart locks व attendance machines का यही base concept है। Buzzer/relay जोड़कर इसे और advanced बना सकते हैं।
4.9

Serial Communication — Bluetooth HC-05

Serial Communication = दो devices के बीच data का bit-by-bit transfer। Arduino में दो प्रकार: Hardware Serial (fixed pins RX=0, TX=1) व Software Serial (किसी भी pins पर — SoftwareSerial.h library से)। HC-05 popular Bluetooth module है जो Arduino को smartphone से wireless जोड़ता है।

🔩 HC-05 Hardware Deep-Dive

Specifications

DetailValue
अंदरBluetooth 2.0 radio chip (2.4 GHz) + antenna + 3.3V regulator
Operating VoltageVCC: 3.6V – 6V | RX pin सिर्फ 3.3V tolerant!
Range~10 meters | Speed: up to 2.1 Mbps
Default SettingsBaud rate: 9600 | Pairing code: 1234 या 0000

⚙️ HC-05 Pin Configuration

PinNameFunction
1EN / KEYAT Command Mode enable करने के लिए
2VCCPower Supply (3.6–6V)
3GNDGround
4TXDData transmit करता है → Arduino के RX से जुड़ता है
5RXDData receive करता है ← Arduino के TX से (voltage divider के साथ)
6STATEConnection status दिखाता है (LED indicator)

🔌 Wiring (Arduino UNO ↔ HC-05)

  • VCC → 5V  |  GND → GND
  • HC-05 TX → Arduino Pin 10 (हमारा software RX)
  • HC-05 RX → Arduino Pin 11 (हमारा software TX) — voltage divider के through
Exam Point (बहुत important): HC-05 का RX pin सिर्फ 3.3V tolerant है जबकि Arduino का TX 5V भेजता है — इसलिए बीच में voltage divider (2 resistors — जैसे 1kΩ + 2kΩ) लगाकर 5V को ~3.3V किया जाता है, वरना module खराब हो सकता है।
💻 HC-05 — Phone ↔ Arduino Chat (Echo)
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11);   // RX, TX

void setup() {
  Serial.begin(9600);       // Serial Monitor
  BTSerial.begin(9600);     // Bluetooth HC-05
  Serial.println("Bluetooth Ready!");
}

void loop() {
  if (BTSerial.available()) {        // Phone se data aaya
    char data = BTSerial.read();
    Serial.print("From Phone: ");
    Serial.println(data);
  }
  if (Serial.available()) {          // Serial Monitor se bheja
    char data = Serial.read();
    BTSerial.write(data);            // Phone par jayega
  }
}
समझें: Mobile में "Serial Bluetooth Terminal" app से HC-05 pair करें (code 1234) → app से text भेजने पर Serial Monitor में दिखेगा, और Serial Monitor से लिखा phone पर जाएगा — two-way (full duplex) communication!
💻 HC-05 — Mobile से LED Control
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11);   // RX, TX
const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  BTSerial.begin(9600);
  Serial.begin(9600);
  Serial.println("Send '1' = ON, '0' = OFF");
}

void loop() {
  if (BTSerial.available()) {
    char c = BTSerial.read();
    if (c == '1') {
      digitalWrite(ledPin, HIGH);
      BTSerial.println("LED is ON");
    } else if (c == '0') {
      digitalWrite(ledPin, LOW);
      BTSerial.println("LED is OFF");
    }
  }
}

🛠️ AT Commands — HC-05 Configure करना

EN/KEY pin HIGH करके module "AT Command Mode" में जाता है — नाम, password, baud rate बदल सकते हैं:

CommandFunctionResponse
ATConnection checkOK
AT+NAMEModule का नाम देखनाHC-05
AT+NAME=MyBTनाम बदलनाMyBT
AT+PSWD=4321Password बदलना4321
4.10

Relay Module — 5V Signal से 220V AC Devices Control

Relay Module एक electronic switch है जो Arduino जैसे low-voltage circuit (5V DC) को high-voltage devices (220V AC — bulb, fan) से जोड़ता है। Simple words में — relay एक "bridge" है जो low-power control और high-power load के बीच काम करता है।

🔩 Relay Hardware Deep-Dive — अंदर क्या होता है?

Internal Components

Componentकाम
Electromagnet Coil5V मिलते ही magnetic field बनाती है जो mechanical switch खींचती है — इसीलिए ON/OFF पर "click" की आवाज़ आती है
Spring + Armature (Switch)Magnetic field से attract होकर contacts जोड़ता है; signal हटते ही spring वापस खींचती है
Optocoupler (PC817)Arduino को 220V spikes से electrically isolate रखता है (opto-isolated modules में)
Transistor + Flyback DiodeTransistor coil को current देता है; diode coil के back-EMF से circuit बचाती है
Contact Ratingआमतौर पर 10A 250V AC / 10A 30V DC तक

🔀 NO, NC, COM — तीन Terminals

  • COM (Common): मुख्य terminal — load का common connection।
  • NO (Normally Open): Relay OFF रहने पर circuit खुला (current नहीं) — signal आने पर बंद होकर device ON। (सबसे ज़्यादा यही उपयोग होता है)
  • NC (Normally Closed): Relay OFF रहने पर circuit बंद (current बहता है) — signal आने पर खुल जाता है।

⚙️ Relay Module Pin Configuration

PinFunction
VCC5V DC (Arduino से)
GNDGround
INControl Signal (Arduino के digital pin से)
COM220V Live line का common connection
NONormally Open → appliance (bulb/fan) line
NCNormally Closed terminal

🔌 Wiring: Arduino → Relay → 220V Bulb

  • VCC → 5V | GND → GND | IN → Digital Pin 7
  • COM → 220V Live line | NO → Bulb की line (Neutral सीधे bulb पर)
💻 Relay — Serial से 220V Bulb ON/OFF
const int relayPin = 7;

void setup() {
  pinMode(relayPin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Send 1 = ON, 0 = OFF");
}

void loop() {
  if (Serial.available()) {
    char input = Serial.read();
    if (input == '1') {
      digitalWrite(relayPin, HIGH);
      Serial.println("Device ON");
    }
    else if (input == '0') {
      digitalWrite(relayPin, LOW);
      Serial.println("Device OFF");
    }
  }
}

🏠 Smart Home Project — Bluetooth + Relay

💻 Mobile से 220V Appliance Control (HC-05 + Relay)
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11);   // RX, TX
const int relayPin = 7;

void setup() {
  pinMode(relayPin, OUTPUT);
  BTSerial.begin(9600);
  Serial.begin(9600);
  Serial.println("Bluetooth Relay Ready!");
}

void loop() {
  if (BTSerial.available()) {
    char data = BTSerial.read();
    if (data == '1') {
      digitalWrite(relayPin, HIGH);
      BTSerial.println("Appliance ON");
    }
    else if (data == '0') {
      digitalWrite(relayPin, LOW);
      BTSerial.println("Appliance OFF");
    }
  }
}
समझें: Mobile app से '1' भेजते ही relay की coil energize होकर COM–NO contact जुड़ता है → 220V circuit complete → bulb ON। यही concept बढ़ाकर (4/8-channel relay से) पूरा smart home बनता है — "ON1", "OFF2" जैसी commands से हर appliance अलग control।

📦 Relay Types

  • 1-Channel: एक appliance | 2-Channel: fan + light
  • 4/8-Channel: पूरे home automation के लिए
  • Solid-State Relay (SSR): बिना mechanical part — silent, ज़्यादा durable, fast switching
⚠️ Safety Guidelines (220V से काम करते समय): Wiring से पहले main power ज़रूर disconnect करें; insulated wires व tape उपयोग करें; relay को plastic enclosure में रखें; opto-isolated modules prefer करें (Arduino को AC spikes से बचाते हैं); Arduino powered ON हो तो live wires कभी न छुएँ।
Exam Point: कुछ relay modules Active LOW होते हैं — IN pin को LOW देने पर relay ON होता है (उल्टा logic)। Code में HIGH/LOW स्वैप करके check करें। Relay के "click" sound से ON/OFF status पता चलता है।
4.11

Summary — Quick Revision

  • Arduino IDE: Sketch (setup एक बार + loop बार-बार) → Verify (compile) → Upload (USB से board) → Serial Monitor (debugging, 9600 baud)।
  • Embedded C: int = 2 bytes, float = 4 bytes; case-sensitive; const > #define; हर statement पर semicolon।
  • Conditions/Loops: if-else, else-if ladder, switch (break ज़रूरी); while, do-while (min 1 बार), for; loop() खुद infinite loop है।
  • Arrays: Index 0 से; loops के साथ powerful; 2D array = rows × columns (7-segment patterns)।
  • Functions: Built-in (digitalWrite), User-defined (blinkLED), Library (lcd.print); prototype top पर।
  • Pins: digitalRead = 0/1; analogRead = 0–1023 (10-bit ADC); analogWrite (PWM) = 0–255, pins 3,5,6,9,10,11।
  • Sensors (voltage/range): LDR (CdS, divider) · LM35 (10mV/°C, -55–150°C) · DHT11 (3.3–5.5V, 0–50°C ±2, NTC+capacitive) · HC-SR04 (5V, 2–400cm, Time×0.034÷2) · IR (2–30cm, LOW on detect) · PIR (7m, 110°, warm-up) · MQ2/135 (SnO₂+heater, 5V) · Soil/Rain/Sound (LM393 comparator)।
  • Output: Buzzer (active/passive, tone()) · Servo SG90 (0–180°, 4.8–6V) · DC motor (driver ज़रूरी, PWM speed) · 7-segment (8 LEDs, CC/CA) · LCD 16×2 (HD44780, V0 contrast)।
  • HC-05: 3.6–6V; RX सिर्फ 3.3V tolerant → voltage divider; default 9600 baud, code 1234; AT commands से configure।
  • Relay: Electromagnet coil + NO/NC/COM; 5V signal से 220V control; opto-isolation; safety first!
4.12

Model Questions — 50 Important MCQs + 15 Theory Questions

✅ 50 Important MCQs (Answers के साथ)

#प्रश्नउत्तर
1Arduino IDE का पूरा नाम क्या है?Integrated Development Environment
2Arduino IDE में लिखा गया program क्या कहलाता है?Sketch
3कौन-सा function program में सिर्फ एक बार चलता है?void setup()
4कौन-सा function बार-बार लगातार चलता रहता है?void loop()
5Verify button का काम क्या है?Code को compile करना और errors दिखाना
6Serial Monitor का उपयोग किसलिए होता है?Board व computer के बीच real-time data देखने / debugging के लिए
7Serial.begin(9600) में 9600 क्या है?Baud rate (bits per second)
8pinMode(13, OUTPUT) का क्या काम है?Pin 13 को output mode में सेट करना
9'digitalwrite' लिखने पर error क्यों आती है?Embedded C case-sensitive है — सही: digitalWrite
10int data type की size कितनी होती है?2 bytes (-32,768 से 32,767)
11float data type की size कितनी है?4 bytes
1210 % 3 का result क्या होगा?1 (% remainder देता है)
137 / 3 (integer division) का result?2 (decimal part हट जाता है)
14#define और const में से memory efficient कौन?const
15&& operator कौन-सा logical operation है?AND (दोनों conditions true हों)
16switch statement में हर case के बाद क्या ज़रूरी है?break (वरना fall-through होता है)
17कौन-सा loop कम से कम एक बार ज़रूर चलता है?do-while loop
18Array का index किससे शुरू होता है?0 से
19int temp[3] = {25, 27, 30}; में temp[2] क्या है?30
20String (char array) के अंत में कौन-सा character होता है?'\0' (null character)
21matrix[1][2] किस element को refer करता है?दूसरी row का तीसरा element
22digitalWrite(), analogRead() किस type के functions हैं?Built-in functions
23Function prototype कहाँ लिखा जाता है?Program के top पर
24I2C communication के लिए कौन-सी library है?Wire.h
25Servo motor के लिए कौन-सी library है?Servo.h
26digitalRead() क्या return करता है?HIGH (1) या LOW (0)
27analogRead() की value range क्या है?0 से 1023 (10-bit ADC)
28analogWrite() (PWM) की range क्या है?0 से 255 (8-bit)
29Arduino UNO के PWM pins कौन-से हैं?3, 5, 6, 9, 10, 11 (~ निशान वाले)
30LDR के अंदर कौन-सा material होता है?Cadmium Sulphide (CdS)
31अँधेरे में LDR का resistance कितना होता है?बहुत high (~1 MΩ)
32LM35 का output कितना होता है?10 mV per °C
33LM35 की temperature range क्या है?-55°C से +150°C (±0.5°C)
34DHT11 के अंदर कौन-से 2 sensors होते हैं?NTC Thermistor + Capacitive Humidity Sensor
35DHT11 की temperature व humidity range?0–50°C (±2°C); 20–90% RH (±5%)
36HC-SR04 कौन-सी frequency की waves भेजता है?40 kHz ultrasonic waves
37HC-SR04 का distance formula क्या है?Distance = Time × 0.034 ÷ 2 (cm)
38HC-SR04 की range कितनी है?2 cm से 400 cm (±3mm)
39IR sensor object detect करने पर क्या output देता है?LOW (0)
40PIR sensor में सफेद dome क्या है?Fresnel Lens (IR को focus करती है)
41PIR की detection range व angle?~7 meter, 110°–120°
42MQ sensors की sensing layer किसकी बनी होती है?SnO₂ (Tin Dioxide) + heater coil
43MQ135 मुख्यतः क्या detect करता है?Air quality — NH₃, CO₂, benzene, smoke
44Sensor modules में LM393 IC का काम?Comparator — analog को clean digital (0/1) बनाना
45Servo SG90 का rotation range?0° से 180°
4616×2 LCD में कौन-सा controller होता है?HD44780
47LCD का V0 pin किसलिए है?Contrast adjustment (potentiometer से)
48HC-05 का RX pin कितने volt tolerant है?सिर्फ 3.3V — इसलिए voltage divider लगाते हैं
49HC-05 का default pairing code व baud rate?1234 (या 0000); 9600 baud
50Relay में NO का मतलब क्या है?Normally Open — relay OFF पर circuit खुला रहता है

📝 15 Theory Questions (Short Answers)

  1. Arduino IDE क्या है? इसके main parts बताइए।Free, open-source software जिसमें Arduino boards program होते हैं। Parts: Sketch Area, Verify, Upload, Serial Monitor, Message Area।
  2. setup() और loop() में अंतर बताइए।setup() शुरुआत में एक बार चलता है (initialization); loop() बार-बार लगातार चलता है (main logic)।
  3. Embedded C के variable naming rules लिखिए।Alphabet/underscore से शुरू हो, digit से नहीं; special characters नहीं; case-sensitive; keywords नहीं।
  4. while और do-while में अंतर बताइए।while पहले condition check करता है; do-while पहले block चलाता है — इसलिए कम से कम एक बार ज़रूर चलता है।
  5. Array क्या है? Example दीजिए।एक ही नाम से similar values का collection — int temp[5] = {25,27,29,31,30}; index 0 से शुरू।
  6. Function के तीन types बताइए।Built-in (digitalWrite), User-defined (blinkLED), Library functions (lcd.print, dht.readTemperature)।
  7. digitalRead() और analogRead() में अंतर बताइए।digitalRead सिर्फ HIGH/LOW (0/1) पढ़ता है; analogRead 0–1023 values देता है (10-bit ADC, 0–5V proportional)।
  8. DHT11 sensor की internal structure व specifications लिखिए।NTC thermistor + capacitive humidity sensor + 8-bit chip; 3.3–5.5V; 0–50°C ±2°C; 20–90% RH ±5%; 1Hz sampling।
  9. HC-SR04 से distance कैसे मापी जाती है?TRIG पर 10µs pulse → 40kHz waves object से टकराकर लौटती हैं → pulseIn() से echo time → Distance = Time × 0.034 ÷ 2 cm।
  10. PIR sensor की working व components बताइए।Pyroelectric sensor body की infrared heat detect करता है; Fresnel lens focus करती है; BISS0001 IC signal process करती है; range 7m, 110–120°।
  11. MQ2 और MQ135 में अंतर बताइए।दोनों में SnO₂ layer + heater; MQ2 = LPG, smoke, methane (leak alarm); MQ135 = NH₃, CO₂, benzene (air quality)।
  12. 16×2 LCD के मुख्य pins के नाम व काम लिखिए।VSS (GND), VDD (+5V), V0 (contrast — potentiometer), RS (register select), RW (read/write), EN (enable), D4–D7 (data)।
  13. HC-05 की wiring में voltage divider क्यों ज़रूरी है?HC-05 का RX सिर्फ 3.3V tolerant है, Arduino TX 5V भेजता है — 2 resistors का divider 5V को ~3.3V करके module बचाता है।
  14. Relay की internal working समझाइए।5V signal से electromagnet coil energize होती है → magnetic field armature खींचकर COM–NO contact जोड़ता है → 220V circuit complete → device ON; opto-coupler Arduino को isolate रखता है।
  15. NO, NC व COM terminals समझाइए।COM = common terminal; NO (Normally Open) = relay OFF पर खुला, ON पर जुड़ता है; NC (Normally Closed) = OFF पर जुड़ा, ON पर खुलता है।
Revision Tip: ये 65 questions इस chapter का पूरा exam-oriented निचोड़ हैं — sensor voltages, ranges व internal components (Q30–50) से exam में सीधे प्रश्न आते हैं। Mock tests के लिए O Level Mock Test ज़रूर लगाएँ।
FAQ

अक्सर पूछे जाने वाले प्रश्न

Arduino IDE क्या है?

Arduino IDE (Integrated Development Environment) एक free, open-source software platform है जिसमें Arduino boards के लिए code (Sketch) लिखा, compile (Verify) और board पर upload किया जाता है। इसमें Serial Monitor debugging के लिए होता है।

Arduino Sketch में setup() और loop() का क्या काम है?

void setup() program की शुरुआत में सिर्फ एक बार चलता है — इसमें pinMode(), Serial.begin() जैसे initialization होते हैं। void loop() बार-बार लगातार चलता रहता है — इसमें main logic (जैसे LED blink, sensor reading) लिखा जाता है।

digitalRead() और analogRead() में क्या अंतर है?

digitalRead(pin) सिर्फ HIGH (1) या LOW (0) पढ़ता है — digital sensors (IR, PIR) के लिए। analogRead(pin) 0 से 1023 तक की value देता है जो 0–5V के proportional होती है — analog sensors (LDR, LM35, MQ135) के लिए।

DHT11 sensor के अंदर क्या होता है और यह कितने voltage पर चलता है?

DHT11 के अंदर एक NTC Thermistor (temperature के लिए), Capacitive Humidity Sensor (नमी के लिए) और एक 8-bit chip होती है। यह 3.3V–5.5V पर चलता है, temperature range 0–50°C (±2°C) और humidity 20–90% (±5%) मापता है।

Relay module से 220V AC device कैसे control होती है?

Relay के अंदर electromagnet coil होती है — Arduino का 5V signal coil को energize करता है जिससे magnetic field बनकर mechanical switch activate होता है। COM को 220V live line से, NO को appliance से जोड़ते हैं — signal HIGH होने पर circuit complete होकर device ON हो जाती है।

HC-05 Bluetooth module की wiring में voltage divider क्यों लगाते हैं?

HC-05 का RX pin सिर्फ 3.3V tolerant है जबकि Arduino का TX pin 5V signal भेजता है — इसलिए 2 resistors का voltage divider लगाकर 5V को ~3.3V में घटाया जाता है ताकि module safe रहे।

🎉 Chapter 4 पूरा हुआ! अब अगला पढ़ें

Chapter 5 में IoT की Security और Future of IoT Ecosystem को detail में समझेंगे।

Chapter 5: Security & Future of IoT ➜