Programming IoT with Arduino
Complete IoT Textbook โ 10 Chapters
From blinking LEDs to cloud-connected smart systems โ master Arduino, sensors, actuators, wireless communication, and IoT cloud platforms in one book.
โฑ๏ธ 50+ hrs total | ๐ฏ Arduino + ESP8266 + Cloud | ๐ฐ โน6โ20 LPA Embedded/IoT | ๐ฅ๏ธ Smart India Hackathon Ready
๐ผ Jobs this unlocks: Embedded Developer (โน6โ10 LPA) | IoT Engineer (โน8โ15 LPA) | Firmware Developer (โน10โ20 LPA)
LCD Interfacing with Arduino Uno
๐ฅ๏ธ Every Display Around You Started with an LCD
ATM machines, railway ticket counters, petrol pump meters, weighing scales at kirana shops โ they all use LCD displays. The 16ร2 LCD is like the "sabse pehla output device" for Arduino. Think of it as a TV remote's display โ small, simple, but powerful enough to show you what matters.
LCD = Jugaad Display! With just โน80 and 6 wires, you can make Arduino talk to you. By the end of this chapter, you'll display custom messages, scrolling text, and even create your own characters like โค๏ธ on a tiny screen.
1.1 LCD Pin Details โ All 16 Pins Explained
A standard 16ร2 LCD module (based on the HD44780 controller) has 16 pins. Understanding each pin is crucial before wiring.
| Pin # | Name | Function |
|---|---|---|
| 1 | VSS | Ground (0V) |
| 2 | VDD | Power Supply (+5V) |
| 3 | V0 | Contrast Adjustment (connect to potentiometer) |
| 4 | RS | Register Select: 0=Command, 1=Data |
| 5 | RW | Read/Write: 0=Write, 1=Read (usually GND) |
| 6 | EN | Enable: Latches data on falling edge |
| 7 | D0 | Data Bit 0 (not used in 4-bit mode) |
| 8 | D1 | Data Bit 1 (not used in 4-bit mode) |
| 9 | D2 | Data Bit 2 (not used in 4-bit mode) |
| 10 | D3 | Data Bit 3 (not used in 4-bit mode) |
| 11 | D4 | Data Bit 4 |
| 12 | D5 | Data Bit 5 |
| 13 | D6 | Data Bit 6 |
| 14 | D7 | Data Bit 7 |
| 15 | A (LED+) | Backlight Anode (+5V through 220ฮฉ resistor) |
| 16 | K (LED-) | Backlight Cathode (GND) |
1.2 Interfacing 16ร2 LCD with Arduino (4-bit Mode)
In 4-bit mode, we only use pins D4โD7, saving 4 Arduino pins. This is the most common wiring method.
Connection Table
| LCD Pin | Arduino Pin | Purpose |
|---|---|---|
| VSS (1) | GND | Ground |
| VDD (2) | 5V | Power |
| V0 (3) | Potentiometer Wiper | Contrast control |
| RS (4) | D12 | Register Select |
| RW (5) | GND | Write mode (always) |
| EN (6) | D11 | Enable pulse |
| D4 (11) | D5 | Data bit 4 |
| D5 (12) | D4 | Data bit 5 |
| D6 (13) | D3 | Data bit 6 |
| D7 (14) | D2 | Data bit 7 |
| A (15) | 5V via 220ฮฉ | Backlight ON |
| K (16) | GND | Backlight GND |
1.3 LiquidCrystal Library Functions
| Function | Description | Example |
|---|---|---|
LiquidCrystal(rs,en,d4,d5,d6,d7) | Constructor โ define pins | LiquidCrystal lcd(12,11,5,4,3,2) |
lcd.begin(cols, rows) | Initialize LCD size | lcd.begin(16, 2) |
lcd.print(data) | Print text/number at cursor | lcd.print("Hello") |
lcd.setCursor(col, row) | Move cursor (0-indexed) | lcd.setCursor(0, 1) |
lcd.clear() | Clear screen, cursor to 0,0 | lcd.clear() |
lcd.scrollDisplayLeft() | Scroll entire display left | Use in loop for marquee |
lcd.scrollDisplayRight() | Scroll entire display right | Reverse marquee |
lcd.blink() | Blinking block cursor | Shows cursor position |
lcd.noBlink() | Stop blinking cursor | Hide cursor |
lcd.createChar(num, data) | Create custom 5ร8 char | Max 8 custom chars (0โ7) |
1.4 Arduino Code โ Hello World on LCD
Arduino // Program: Display "Hello World!" on 16x2 LCD // Board: Arduino Uno // Connection: 4-bit mode (RS=12, EN=11, D4=5, D5=4, D6=3, D7=2) #include <LiquidCrystal.h> // Initialize LCD: LiquidCrystal(RS, EN, D4, D5, D6, D7) LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); // Set LCD to 16 columns, 2 rows lcd.setCursor(0, 0); // Move cursor to column 0, row 0 lcd.print("Hello World!"); // Print on first line lcd.setCursor(0, 1); // Move cursor to second line lcd.print("Arduino IoT"); // Print on second line } void loop() { // Nothing to repeat โ static display }
1.5 Custom Character Display โ createChar()
The LCD can store up to 8 custom characters (numbered 0โ7). Each character is a 5ร8 pixel grid defined by a byte array.
Arduino // Program: Display custom heart character on LCD #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Define heart character as byte array byte heart[8] = { 0b01010, // Row 0: .#.#. 0b11111, // Row 1: ##### 0b11111, // Row 2: ##### 0b11111, // Row 3: ##### 0b01110, // Row 4: .###. 0b00100, // Row 5: ..#.. 0b00000, // Row 6: .....(blank) 0b00000 // Row 7: .....(blank) }; void setup() { lcd.begin(16, 2); lcd.createChar(0, heart); // Store heart at position 0 lcd.setCursor(0, 0); lcd.print("I "); lcd.write(byte(0)); // Display custom character 0 (heart) lcd.print(" Arduino!"); } void loop() {}
1.6 Worked Examples
Example 1: Display Your Name
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.print("Name: Rahul"); lcd.setCursor(0, 1); lcd.print("Roll: 101"); } void loop() {}
Example 2: Counter 0โ99
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); } void loop() { for (int i = 0; i < 100; i++) { lcd.clear(); lcd.print("Count: "); lcd.print(i); delay(500); } }
Example 3: Scrolling Marquee
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.print(" Welcome to EduArtha IoT Lab! "); } void loop() { lcd.scrollDisplayLeft(); // Shift text left by 1 position delay(300); // Speed of scrolling }
Example 4: Temperature Display Format
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); byte degreeSymbol[8] = {0x06,0x09,0x09,0x06,0x00,0x00,0x00,0x00}; void setup() { lcd.begin(16, 2); lcd.createChar(0, degreeSymbol); lcd.print("Temp: 32"); lcd.write(byte(0)); lcd.print("C"); lcd.setCursor(0, 1); lcd.print("Humidity: 65%"); } void loop() {}
Example 5: Custom Heart + Smiley
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); byte heart[8] = {0x00,0x0A,0x1F,0x1F,0x0E,0x04,0x00,0x00}; byte smiley[8] = {0x00,0x0A,0x0A,0x00,0x11,0x0E,0x00,0x00}; void setup() { lcd.begin(16, 2); lcd.createChar(0, heart); lcd.createChar(1, smiley); lcd.write(byte(0)); lcd.print(" I love IoT "); lcd.write(byte(1)); } void loop() {}
Example 6: Blinking Cursor
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.print("Enter PIN:"); lcd.setCursor(0, 1); lcd.blink(); // Show blinking block cursor } void loop() {}
Example 7: Two-Line Message
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.setCursor(2, 0); lcd.print("Jai Hind!"); lcd.setCursor(0, 1); lcd.print("Bharat Mata Ki"); } void loop() {}
Example 8: Right-to-Left Scroll
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print("Scrolling Right"); } void loop() { lcd.scrollDisplayRight(); delay(400); }
Example 9: Display Analog Reading
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); } void loop() { int val = analogRead(A0); // Read pot/sensor on A0 lcd.clear(); lcd.print("Analog: "); lcd.print(val); // 0-1023 lcd.setCursor(0, 1); lcd.print("Volts: "); lcd.print(val * 5.0 / 1023, 2); // Convert to voltage delay(500); }
Example 10: Simple LCD Menu
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); int btnPin = 7; int menu = 0; void setup() { lcd.begin(16, 2); pinMode(btnPin, INPUT_PULLUP); showMenu(); } void loop() { if (digitalRead(btnPin) == LOW) { menu = (menu + 1) % 3; showMenu(); delay(300); // Debounce } } void showMenu() { lcd.clear(); lcd.print("> Menu Option:"); lcd.setCursor(0, 1); if (menu == 0) lcd.print("1. Read Temp"); else if (menu == 1) lcd.print("2. Read Light"); else lcd.print("3. Motor ON"); }
lcd.begin(16,2) in setup. (4) Backlight not connected โ check A and K pins.
1.7 MCQs โ Chapter 1 (20 Questions)
How many pins does a standard 16ร2 LCD module have?
- 8
- 14
- 16
- 20
What is the function of pin V0 on the LCD?
- Power supply
- Contrast adjustment
- Data transmission
- Backlight control
In 4-bit mode, which data pins of the LCD are used?
- D0โD3
- D4โD7
- D0โD7
- D2โD5
What does the RS pin on the LCD control?
- Reset the display
- Select between command and data mode
- Control the refresh speed
- Enable the backlight
Which function initializes the LCD dimensions?
- lcd.init(16,2)
- lcd.start(16,2)
- lcd.begin(16,2)
- lcd.setup(16,2)
What is the maximum number of custom characters you can create on a 16ร2 LCD?
- 4
- 8
- 16
- 32
What is the pixel grid size for each custom character on a 16ร2 LCD?
- 8ร8
- 5ร7
- 5ร8
- 7ร5
Why is the RW pin usually connected to GND?
- To save power
- Because we only write to the LCD, never read from it
- It doesn't work otherwise
- To increase speed
Which function moves the cursor to column 5, row 1?
- lcd.setCursor(1, 5)
- lcd.setCursor(5, 1)
- lcd.moveTo(5, 1)
- lcd.goto(5, 1)
What happens when you call lcd.clear()?
- Only the first line is cleared
- The backlight turns off
- All text is erased and cursor moves to position (0,0)
- The LCD resets completely
How many Arduino digital pins are needed for LCD in 4-bit mode (excluding power)?
- 4
- 6
- 8
- 10
What is the purpose of the EN (Enable) pin?
- Enables the backlight
- Latches data on the falling edge of a pulse
- Enables write mode
- Enables the power supply
Which resistor value is typically used with the LCD backlight (pin A)?
- 10ฮฉ
- 100ฮฉ
- 220ฮฉ
- 10kฮฉ
Which library is used for basic LCD control in Arduino?
- LCD.h
- LiquidCrystal.h
- Display.h
- HD44780.h
What controller chip does the standard 16ร2 LCD use?
- ATmega328P
- HD44780
- ESP8266
- MAX7219
To display the byte stored at custom character position 0, which function is used?
- lcd.print(0)
- lcd.display(0)
- lcd.write(byte(0))
- lcd.show(0)
What does lcd.scrollDisplayLeft() do?
- Moves the cursor left
- Shifts the entire display content one position to the left
- Erases the leftmost character
- Rotates the display 90 degrees
How many total characters can a 16ร2 LCD display at once?
- 16
- 24
- 32
- 64
If you want to display text starting from the 3rd column of the 2nd row, which call do you use?
- lcd.setCursor(3, 2)
- lcd.setCursor(2, 1)
- lcd.setCursor(3, 1)
- lcd.setCursor(2, 2)
What advantage does 4-bit mode have over 8-bit mode?
- Faster data transfer
- Uses fewer Arduino pins (6 instead of 10)
- Better contrast
- Supports more characters
LDR, Ultrasonic & IR Sensor Interfacing
๐๏ธ Sensors = Arduino Ki Aankhein Aur Kaan
Without sensors, Arduino is blind and deaf โ it can't sense the world. An LDR detects light (street lights that auto-ON at night), an ultrasonic sensor measures distance (parking sensors in cars), and an IR sensor detects objects (automatic doors at malls). These three sensors are the foundation of every IoT project.
Analogy: Think of sensors as your body's senses โ LDR is your eyes (light), ultrasonic is your ears (echo/sonar), IR is your touch (proximity detection).
2.1 LDR (Light Dependent Resistor)
An LDR's resistance changes with light: bright light โ low resistance (~1kฮฉ), dark โ high resistance (~10Mฮฉ). We use a voltage divider circuit to convert this resistance change into a voltage that Arduino can read via analogRead().
Street Light Automation โ Full Code
Arduino // Program: Automatic Street Light using LDR // When dark (LDR value < threshold) โ LED ON // When bright (LDR value >= threshold) โ LED OFF int ldrPin = A0; // LDR connected to analog pin A0 int ledPin = 13; // LED connected to digital pin 13 int threshold = 500; // Adjust based on your environment void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { int ldrValue = analogRead(ldrPin); // Read LDR (0-1023) Serial.print("LDR Value: "); Serial.println(ldrValue); if (ldrValue < threshold) { // Dark condition digitalWrite(ledPin, HIGH); // Turn ON street light Serial.println("STATUS: Dark โ LED ON"); } else { // Bright condition digitalWrite(ledPin, LOW); // Turn OFF street light Serial.println("STATUS: Bright โ LED OFF"); } delay(500); }
2.2 Ultrasonic Sensor (HC-SR04)
The HC-SR04 sends an ultrasonic pulse (40kHz) and measures the time it takes for the echo to return. Distance is calculated using: distance = (time ร 0.034) / 2 (speed of sound โ 340 m/s).
| Pin | Function | Arduino Connection |
|---|---|---|
| VCC | Power (+5V) | 5V |
| Trig | Trigger pulse input | D9 |
| Echo | Echo pulse output | D10 |
| GND | Ground | GND |
Distance Measurement โ Full Code
Arduino // Program: Measure distance using HC-SR04 Ultrasonic Sensor // Formula: distance = (duration * 0.034) / 2 const int trigPin = 9; // Trigger pin const int echoPin = 10; // Echo pin long duration; float distance; void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); Serial.println("HC-SR04 Distance Sensor Ready"); } void loop() { // Step 1: Send 10ยตs trigger pulse digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Step 2: Measure echo pulse duration duration = pulseIn(echoPin, HIGH); // Step 3: Calculate distance distance = (duration * 0.034) / 2; // Step 4: Display result Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(500); }
Parking Sensor with Buzzer
Arduino // Parking sensor: buzzer beeps faster as object gets closer const int trigPin = 9; const int echoPin = 10; const int buzzerPin = 8; long duration; float distance; void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(buzzerPin, OUTPUT); Serial.begin(9600); } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration * 0.034) / 2; if (distance < 10) { tone(buzzerPin, 1000); // Continuous beep โ very close! } else if (distance < 30) { tone(buzzerPin, 1000, 100); // Short beep delay(distance * 10); // Beep faster when closer } else { noTone(buzzerPin); // No beep โ safe distance } delay(100); }
2.3 IR Sensor โ Object Detection
An IR sensor module has an IR LED (emitter) and a photodiode (receiver). When an object is close, IR light reflects back and the output goes LOW. It gives a digital output โ HIGH (no object) or LOW (object detected).
Arduino // Program: Object detection using IR Sensor int irPin = 7; int ledPin = 13; void setup() { pinMode(irPin, INPUT); pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { int irValue = digitalRead(irPin); if (irValue == LOW) { // Object detected digitalWrite(ledPin, HIGH); Serial.println("Object Detected!"); } else { digitalWrite(ledPin, LOW); Serial.println("No Object"); } delay(200); }
2.4 Worked Examples
Example 1: LDR with LED brightness (PWM)
Arduino int ldrPin = A0; int ledPin = 9; // PWM pin void setup() { pinMode(ledPin, OUTPUT); } void loop() { int val = analogRead(ldrPin); int brightness = map(val, 0, 1023, 255, 0); // Dark=bright LED analogWrite(ledPin, brightness); delay(100); }
Example 2: Ultrasonic + LCD display
Arduino #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); const int trig = 9, echo = 10; void setup() { lcd.begin(16,2); pinMode(trig,OUTPUT); pinMode(echo,INPUT); } void loop() { digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); float d = (pulseIn(echo,HIGH) * 0.034) / 2; lcd.clear(); lcd.print("Distance:"); lcd.setCursor(0,1); lcd.print(d); lcd.print(" cm"); delay(300); }
Example 3: IR counter (count objects passing)
Arduino int irPin = 7; int count = 0; bool lastState = HIGH; void setup() { pinMode(irPin,INPUT); Serial.begin(9600); } void loop() { bool curr = digitalRead(irPin); if (lastState == HIGH && curr == LOW) { count++; Serial.print("Count: "); Serial.println(count); } lastState = curr; delay(50); }
Example 4: Multi-zone parking (3 ultrasonic sensors)
Arduino int trig[] = {2, 4, 6}; int echo[] = {3, 5, 7}; void setup() { Serial.begin(9600); for(int i=0;i<3;i++) { pinMode(trig[i],OUTPUT); pinMode(echo[i],INPUT); } } float getDistance(int t, int e) { digitalWrite(t,LOW); delayMicroseconds(2); digitalWrite(t,HIGH); delayMicroseconds(10); digitalWrite(t,LOW); return (pulseIn(e,HIGH) * 0.034) / 2; } void loop() { for(int i=0;i<3;i++) { float d = getDistance(trig[i],echo[i]); Serial.print("Zone "); Serial.print(i+1); Serial.print(": "); Serial.print(d); Serial.println(d<20 ? " OCCUPIED" : " EMPTY"); } Serial.println("---"); delay(1000); }
Example 5: LDR night lamp with Serial plotter
Arduino void setup() { Serial.begin(9600); } void loop() { Serial.println(analogRead(A0)); // Open Serial Plotter to see graph delay(100); }
Example 6: Ultrasonic + RGB LED (distance โ color)
Arduino const int trig=9, echo=10, redPin=3, greenPin=5, bluePin=6; void setup() { pinMode(trig,OUTPUT); pinMode(echo,INPUT); pinMode(redPin,OUTPUT); pinMode(greenPin,OUTPUT); pinMode(bluePin,OUTPUT); } void loop() { digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); float d = (pulseIn(echo,HIGH)*0.034)/2; if(d<10){analogWrite(redPin,255);analogWrite(greenPin,0);analogWrite(bluePin,0);} else if(d<30){analogWrite(redPin,255);analogWrite(greenPin,255);analogWrite(bluePin,0);} else{analogWrite(redPin,0);analogWrite(greenPin,255);analogWrite(bluePin,0);} delay(200); }
Example 7: IR-based line follower (2 sensors)
Arduino int leftIR = 6, rightIR = 7; int motorL = 9, motorR = 10; void setup() { pinMode(leftIR,INPUT); pinMode(rightIR,INPUT); pinMode(motorL,OUTPUT); pinMode(motorR,OUTPUT); } void loop() { int L = digitalRead(leftIR), R = digitalRead(rightIR); if(L==LOW && R==LOW) { analogWrite(motorL,200); analogWrite(motorR,200); } // Forward else if(L==LOW) { analogWrite(motorL,0); analogWrite(motorR,200); } // Turn left else if(R==LOW) { analogWrite(motorL,200); analogWrite(motorR,0); } // Turn right else { analogWrite(motorL,0); analogWrite(motorR,0); } // Stop }
Example 8: LDR alarm (buzzer when too dark)
Arduino void setup() { pinMode(8,OUTPUT); } void loop() { if(analogRead(A0) < 200) tone(8,1000); else noTone(8); delay(100); }
Example 9: Ultrasonic water level monitor
Arduino const int trig=9,echo=10; const float tankHeight = 30.0; // cm void setup() { pinMode(trig,OUTPUT); pinMode(echo,INPUT); Serial.begin(9600); } void loop() { digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); float d = (pulseIn(echo,HIGH)*0.034)/2; float level = tankHeight - d; float pct = (level/tankHeight)*100; Serial.print("Water Level: "); Serial.print(pct); Serial.println("%"); delay(1000); }
Example 10: Combined sensor dashboard (LDR+Ultrasonic+IR on Serial)
Arduino const int trig=9,echo=10,irPin=7; void setup() { pinMode(trig,OUTPUT);pinMode(echo,INPUT);pinMode(irPin,INPUT); Serial.begin(9600); Serial.println("=== IoT Sensor Dashboard ==="); } void loop() { int ldr = analogRead(A0); digitalWrite(trig,LOW);delayMicroseconds(2); digitalWrite(trig,HIGH);delayMicroseconds(10); digitalWrite(trig,LOW); float dist = (pulseIn(echo,HIGH)*0.034)/2; int ir = digitalRead(irPin); Serial.print("Light:"); Serial.print(ldr); Serial.print(" | Dist:"); Serial.print(dist); Serial.print("cm | Object:"); Serial.println(ir==LOW?"YES":"NO"); delay(500); }
2.5 MCQs โ Chapter 2 (20 Questions)
What happens to LDR resistance in darkness?
- Decreases
- Increases
- Stays same
- Becomes zero
Which Arduino function reads analog voltage?
- digitalRead()
- analogRead()
- voltageRead()
- sensorRead()
The HC-SR04 ultrasonic sensor operates at what frequency?
- 20 kHz
- 40 kHz
- 100 kHz
- 1 MHz
What is the formula for distance using HC-SR04?
- distance = time ร 340
- distance = (time ร 0.034) / 2
- distance = time / 340
- distance = time ร 0.034
What does pulseIn(echoPin, HIGH) return?
- Voltage in volts
- Time in microseconds the pin was HIGH
- Distance in cm
- Frequency in Hz
What is the range of HC-SR04 sensor?
- 0โ10 cm
- 2โ400 cm
- 1โ1000 cm
- 10โ200 cm
An IR sensor output is LOW when:
- No object is present
- An object is detected
- Power is off
- Sensor is broken
In an LDR voltage divider, the fixed resistor is typically:
- 100ฮฉ
- 1kฮฉ
- 10kฮฉ
- 1Mฮฉ
analogRead() returns a value in the range:
- 0โ255
- 0โ1023
- 0โ4095
- 0โ65535
Which trigger pulse duration is needed for HC-SR04?
- 2 ยตs
- 10 ยตs
- 100 ยตs
- 1 ms
What type of output does an IR obstacle sensor give?
- Analog
- Digital
- PWM
- Serial
map(val, 0, 1023, 0, 255) converts analog reading to:
- Voltage
- PWM duty cycle range
- Temperature
- Distance
Speed of sound used in ultrasonic calculation is approximately:
- 340 m/s
- 3400 m/s
- 34 m/s
- 34000 m/s
Which application uses LDR sensors in India?
- Automatic street lights
- Motor speed control
- Temperature measurement
- RFID reading
How many pins does the HC-SR04 module have?
- 2
- 3
- 4
- 6
For a line follower robot, which sensor is used?
- LDR
- Ultrasonic
- IR sensor
- Temperature sensor
What is the ADC resolution of Arduino Uno?
- 8-bit
- 10-bit
- 12-bit
- 16-bit
Which function generates a square wave on a pin for a buzzer?
- analogWrite()
- tone()
- buzz()
- sound()
Why do we divide the ultrasonic time by 2?
- To convert units
- Sound travels to object and back (round trip)
- Sensor has 2 pins
- Arduino clock is 2x faster
What component is paired with LDR in a voltage divider?
- Capacitor
- LED
- Fixed resistor
- Transistor
Temperature & Humidity Sensor (DHT22)
๐ก๏ธ Weather Station Banaao โ Apne Room Ka Mausam Jaano!
India's weather is extreme โ from Rajasthan's 50ยฐC summers to Kashmir's -10ยฐC winters. A single โน250 sensor can tell you the exact temperature and humidity of any room. Build your own weather station, greenhouse monitor, or server room alert system!
Analogy: DHT22 = Your room ka personal mausam vibhaag (weather department)!
3.1 DHT22 Module Specifications
| Parameter | DHT22 (AM2302) | DHT11 (for comparison) |
|---|---|---|
| Temperature Range | -40ยฐC to +80ยฐC | 0ยฐC to +50ยฐC |
| Temperature Accuracy | ยฑ0.5ยฐC | ยฑ2ยฐC |
| Humidity Range | 0โ100% RH | 20โ80% RH |
| Humidity Accuracy | ยฑ2% RH | ยฑ5% RH |
| Sampling Rate | Every 2 seconds | Every 1 second |
| Operating Voltage | 3.3V โ 5V | 3.3V โ 5V |
| Pins | 3 (VCC, DATA, GND) | 3 (VCC, DATA, GND) |
| Price (India) | โน200โ300 | โน80โ120 |
3.2 DHT Library Installation
- Open Arduino IDE โ Sketch โ Include Library โ Manage Libraries
- Search for "DHT sensor library" by Adafruit
- Click Install (also install "Adafruit Unified Sensor" if prompted)
3.3 Basic DHT22 Code โ Read Temperature & Humidity
Arduino // Program: Read Temperature and Humidity from DHT22 // Board: Arduino Uno | Sensor: DHT22 on pin D2 #include <DHT.h> #define DHTPIN 2 // DHT22 data pin connected to D2 #define DHTTYPE DHT22 // Sensor type: DHT22 DHT dht(DHTPIN, DHTTYPE); // Create DHT object void setup() { Serial.begin(9600); dht.begin(); // Initialize DHT sensor Serial.println("DHT22 Weather Station Ready!"); Serial.println("=========================="); } void loop() { delay(2000); // DHT22 needs 2 sec between readings float humidity = dht.readHumidity(); float tempC = dht.readTemperature(); // Celsius float tempF = dht.readTemperature(true); // Fahrenheit // Check if reading failed if (isnan(humidity) || isnan(tempC)) { Serial.println("ERROR: Failed to read DHT22!"); return; } // Calculate heat index float heatIndex = dht.computeHeatIndex(tempC, humidity, false); Serial.print("Temperature: "); Serial.print(tempC); Serial.print("ยฐC ("); Serial.print(tempF); Serial.println("ยฐF)"); Serial.print("Humidity: "); Serial.print(humidity); Serial.println("%"); Serial.print("Heat Index: "); Serial.print(heatIndex); Serial.println("ยฐC"); Serial.println("---"); }
3.4 Weather Station Project โ DHT22 + LCD
Arduino // Weather Station: DHT22 + 16x2 LCD Display #include <DHT.h> #include <LiquidCrystal.h> #define DHTPIN 2 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); LiquidCrystal lcd(12, 11, 5, 4, 3, 8); // Changed D2โD8 (D2 used by DHT) byte degreeChar[8] = {0x06,0x09,0x09,0x06,0x00,0x00,0x00,0x00}; void setup() { lcd.begin(16, 2); lcd.createChar(0, degreeChar); dht.begin(); lcd.print("Weather Station"); lcd.setCursor(0, 1); lcd.print("Initializing..."); delay(2000); } void loop() { float t = dht.readTemperature(); float h = dht.readHumidity(); if (isnan(t) || isnan(h)) { lcd.clear(); lcd.print("Sensor Error!"); delay(2000); return; } lcd.clear(); lcd.print("Temp: "); lcd.print(t, 1); lcd.write(byte(0)); lcd.print("C"); lcd.setCursor(0, 1); lcd.print("Humid: "); lcd.print(h, 1); lcd.print("%"); delay(2000); }
3.5 Worked Examples
Example 1: Temperature alert (buzzer when >35ยฐC)
Arduino #include <DHT.h> DHT dht(2, DHT22); void setup() { dht.begin(); pinMode(8,OUTPUT); Serial.begin(9600); } void loop() { delay(2000); float t = dht.readTemperature(); if(t > 35.0) { tone(8,1000); Serial.println("HOT ALERT!"); } else { noTone(8); Serial.print("Temp: "); Serial.println(t); } }
Example 2: Humidity-based fan control
Arduino #include <DHT.h> DHT dht(2, DHT22); int fanPin = 9; void setup() { dht.begin(); pinMode(fanPin,OUTPUT); } void loop() { delay(2000); float h = dht.readHumidity(); if(h > 70) digitalWrite(fanPin,HIGH); else digitalWrite(fanPin,LOW); }
Example 3: Min/Max temperature logger
Arduino #include <DHT.h> DHT dht(2, DHT22); float minT=100, maxT=-100; void setup() { dht.begin(); Serial.begin(9600); } void loop() { delay(2000); float t = dht.readTemperature(); if(t<minT) minT=t; if(t>maxT) maxT=t; Serial.print("Now:"); Serial.print(t); Serial.print(" Min:"); Serial.print(minT); Serial.print(" Max:"); Serial.println(maxT); }
Example 4: Comfort index indicator (LED colors)
Arduino #include <DHT.h> DHT dht(2, DHT22); int red=3,green=5,blue=6; void setup() { dht.begin(); pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT); } void loop() { delay(2000); float t = dht.readTemperature(); if(t<20) { digitalWrite(blue,HIGH); digitalWrite(green,LOW); digitalWrite(red,LOW); } // Cold else if(t<30) { digitalWrite(blue,LOW); digitalWrite(green,HIGH); digitalWrite(red,LOW); } // Comfortable else { digitalWrite(blue,LOW); digitalWrite(green,LOW); digitalWrite(red,HIGH); } // Hot }
Example 5: Data logger to Serial (CSV format)
Arduino #include <DHT.h> DHT dht(2, DHT22); unsigned long reading = 0; void setup() { dht.begin(); Serial.begin(9600); Serial.println("Reading,Temp_C,Humidity_%"); } void loop() { delay(5000); reading++; Serial.print(reading); Serial.print(","); Serial.print(dht.readTemperature()); Serial.print(","); Serial.println(dht.readHumidity()); }
Example 6: Dew point calculation
Arduino #include <DHT.h> DHT dht(2, DHT22); void setup() { dht.begin(); Serial.begin(9600); } void loop() { delay(2000); float t=dht.readTemperature(), h=dht.readHumidity(); float dp = t - ((100-h)/5.0); // Simplified dew point Serial.print("Dew Point: "); Serial.print(dp); Serial.println("ยฐC"); }
Example 7: Greenhouse monitor (temp + humidity thresholds)
Arduino #include <DHT.h> DHT dht(2, DHT22); int pumpPin=7, ventPin=8; void setup() { dht.begin(); pinMode(pumpPin,OUTPUT); pinMode(ventPin,OUTPUT); Serial.begin(9600); } void loop() { delay(2000); float t=dht.readTemperature(), h=dht.readHumidity(); Serial.print("T:"); Serial.print(t); Serial.print(" H:"); Serial.println(h); if(h<40) digitalWrite(pumpPin,HIGH); else digitalWrite(pumpPin,LOW); // Irrigate if(t>35) digitalWrite(ventPin,HIGH); else digitalWrite(ventPin,LOW); // Ventilate }
Example 8: Moving average temperature (smoothing)
Arduino #include <DHT.h> DHT dht(2, DHT22); float readings[5]; int idx=0; void setup() { dht.begin(); Serial.begin(9600); } void loop() { delay(2000); readings[idx] = dht.readTemperature(); idx = (idx+1) % 5; float avg = 0; for(int i=0;i<5;i++) avg += readings[i]; avg /= 5; Serial.print("Avg Temp: "); Serial.println(avg); }
Example 9: Heat index warning system
Arduino #include <DHT.h> DHT dht(2, DHT22); void setup() { dht.begin(); Serial.begin(9600); } void loop() { delay(2000); float t=dht.readTemperature(), h=dht.readHumidity(); float hi = dht.computeHeatIndex(t, h, false); Serial.print("Heat Index: "); Serial.print(hi); if(hi>40) Serial.println(" DANGER!"); else if(hi>32) Serial.println(" Caution"); else Serial.println(" Normal"); }
Example 10: Temp + humidity on Serial Plotter
Arduino #include <DHT.h> DHT dht(2, DHT22); void setup() { dht.begin(); Serial.begin(9600); } void loop() { delay(2000); Serial.print(dht.readTemperature()); Serial.print("\t"); // Tab separator for Serial Plotter Serial.println(dht.readHumidity()); }
3.6 MCQs โ Chapter 3 (20 Questions)
What is the temperature accuracy of DHT22?
- ยฑ1ยฐC
- ยฑ0.5ยฐC
- ยฑ2ยฐC
- ยฑ0.1ยฐC
What is the minimum delay between DHT22 readings?
- 100 ms
- 500 ms
- 1 second
- 2 seconds
Which pull-up resistor is used with DHT22 data line?
- 220ฮฉ
- 1kฮฉ
- 10kฮฉ
- 100kฮฉ
What does isnan() check in the DHT code?
- If the value is zero
- If the value is negative
- If the reading failed (Not a Number)
- If the sensor is disconnected
DHT22 uses which communication protocol?
- I2C
- SPI
- UART
- Single-wire (proprietary)
What is the humidity range of DHT22?
- 20โ80%
- 0โ100%
- 10โ90%
- 30โ70%
Which library is used for DHT sensors in Arduino?
- Wire.h
- DHT.h
- Sensor.h
- Temperature.h
dht.readTemperature(true) returns temperature in:
- Celsius
- Fahrenheit
- Kelvin
- Raw ADC value
How many pins does the DHT22 module have?
- 2
- 3
- 4
- 6
What does heat index represent?
- Actual temperature
- Wind chill factor
- How hot it feels considering humidity
- Maximum temperature
What voltage does DHT22 operate on?
- 1.8V only
- 3.3V only
- 5V only
- 3.3V to 5V
Which is more accurate: DHT11 or DHT22?
- DHT11
- DHT22
- Both same
- Depends on temperature
What does dht.begin() do?
- Reads temperature
- Initializes the sensor
- Calibrates the sensor
- Resets the sensor
Temperature range of DHT22 is:
- 0ยฐC to 50ยฐC
- -40ยฐC to 80ยฐC
- -20ยฐC to 60ยฐC
- -10ยฐC to 100ยฐC
Which function computes heat index in the DHT library?
- dht.heatIndex()
- dht.computeHeatIndex()
- dht.getHI()
- dht.feelTemp()
What type of sensor element does DHT22 use?
- Thermistor + capacitive humidity sensor
- Thermocouple + resistive humidity sensor
- RTD + piezoelectric sensor
- Infrared sensor
If DHT22 reads NaN, the most likely cause is:
- Wrong voltage
- Missing pull-up resistor or wiring error
- Too much humidity
- Arduino is too fast
In the weather station project, why do we use D8 instead of D2 for LCD?
- D2 is faster
- D2 is used by DHT22 sensor
- D8 has better resolution
- No reason
What does RH stand for in humidity measurement?
- Relative Humidity
- Real Humidity
- Ratio Humidity
- Recorded Humidity
For a greenhouse, ideal humidity is maintained by:
- Increasing temperature
- Using fans and irrigation based on DHT readings
- Closing all windows
- Adding more sensors
DC Motors with L298N Motor Driver
๐๏ธ Robot Car Banana Hai? L298N Se Shuru Karo!
Every robot, drone, and automated factory machine uses motors. The L298N is the most popular motor driver for Arduino โ it can control 2 DC motors simultaneously with speed and direction control. From line-following robots to automated curtain openers, this is your gateway to motion!
Analogy: Arduino is the brain, L298N is the muscle. Brain decides direction, muscle provides power!
4.1 L298N Specifications
| Parameter | Value |
|---|---|
| Driver Type | Dual H-Bridge |
| Motor Supply Voltage | 5V โ 35V |
| Logic Voltage | 5V |
| Max Current per Channel | 2A |
| Control Pins | ENA, IN1, IN2, IN3, IN4, ENB |
| Output Pins | OUT1, OUT2, OUT3, OUT4 |
4.2 H-Bridge Working Principle
Direction Control Truth Table
| IN1 | IN2 | Motor Action |
|---|---|---|
| HIGH | LOW | Forward (clockwise) |
| LOW | HIGH | Reverse (counter-clockwise) |
| LOW | LOW | Coast (free spin) |
| HIGH | HIGH | Brake (hard stop) |
Connection Table
| L298N Pin | Arduino Pin | Purpose |
|---|---|---|
| ENA | D9 (PWM) | Motor A speed control |
| IN1 | D8 | Motor A direction |
| IN2 | D7 | Motor A direction |
| IN3 | D6 | Motor B direction |
| IN4 | D5 | Motor B direction |
| ENB | D3 (PWM) | Motor B speed control |
| +12V | External 9-12V battery | Motor power |
| GND | Common GND (Arduino + Battery) | Ground |
4.3 Single Motor Control Code
Arduino // Program: Control single DC motor with L298N int ENA = 9; // PWM pin for speed int IN1 = 8; // Direction pin 1 int IN2 = 7; // Direction pin 2 void setup() { pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); } void loop() { // Forward at full speed digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENA, 255); // Full speed delay(2000); // Stop digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); delay(1000); // Reverse at half speed digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENA, 128); // Half speed delay(2000); // Stop digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); delay(1000); }
4.4 Robot Car Code (2 Motors)
Arduino // Robot Car: Forward, Backward, Left, Right int ENA=9,IN1=8,IN2=7,IN3=6,IN4=5,ENB=3; int speed = 200; void setup() { int pins[] = {ENA,IN1,IN2,IN3,IN4,ENB}; for(int i=0;i<6;i++) pinMode(pins[i],OUTPUT); } void forward() { digitalWrite(IN1,HIGH); digitalWrite(IN2,LOW); digitalWrite(IN3,HIGH); digitalWrite(IN4,LOW); analogWrite(ENA,speed); analogWrite(ENB,speed); } void backward() { digitalWrite(IN1,LOW); digitalWrite(IN2,HIGH); digitalWrite(IN3,LOW); digitalWrite(IN4,HIGH); analogWrite(ENA,speed); analogWrite(ENB,speed); } void turnLeft() { digitalWrite(IN1,LOW); digitalWrite(IN2,LOW); digitalWrite(IN3,HIGH); digitalWrite(IN4,LOW); analogWrite(ENB,speed); } void turnRight() { digitalWrite(IN1,HIGH); digitalWrite(IN2,LOW); analogWrite(ENA,speed); digitalWrite(IN3,LOW); digitalWrite(IN4,LOW); } void stopMotors() { digitalWrite(IN1,LOW); digitalWrite(IN2,LOW); digitalWrite(IN3,LOW); digitalWrite(IN4,LOW); } void loop() { forward(); delay(2000); stopMotors(); delay(500); turnRight(); delay(1000); stopMotors(); delay(500); backward(); delay(2000); stopMotors(); delay(500); turnLeft(); delay(1000); stopMotors(); delay(500); }
4.5 Worked Examples
Ex 1: Speed ramp up
Arduino int ENA=9,IN1=8,IN2=7; void setup(){pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);} void loop(){ digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW); for(int s=0;s<=255;s+=5){analogWrite(ENA,s);delay(50);} for(int s=255;s>=0;s-=5){analogWrite(ENA,s);delay(50);} }
Ex 2: Pot-controlled speed
Arduino int ENA=9,IN1=8,IN2=7; void setup(){pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);} void loop(){analogWrite(ENA,map(analogRead(A0),0,1023,0,255));delay(50);}
Ex 3: Button direction toggle
Arduino int ENA=9,IN1=8,IN2=7,btn=2; bool dir=true; void setup(){pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);pinMode(btn,INPUT_PULLUP);} void loop(){ if(digitalRead(btn)==LOW){dir=!dir;delay(300);} digitalWrite(IN1,dir?HIGH:LOW);digitalWrite(IN2,dir?LOW:HIGH); analogWrite(ENA,200); }
Ex 4: Serial-controlled motor
Arduino int ENA=9,IN1=8,IN2=7; void setup(){Serial.begin(9600);pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);} void loop(){ if(Serial.available()){ char c=Serial.read(); if(c=='F'){digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);analogWrite(ENA,200);} else if(c=='R'){digitalWrite(IN1,LOW);digitalWrite(IN2,HIGH);analogWrite(ENA,200);} else if(c=='S'){digitalWrite(IN1,LOW);digitalWrite(IN2,LOW);} } }
Ex 5โ10: Additional motor examples
Arduino // Ex 5: Obstacle-avoiding robot (ultrasonic + motors) int trig=10,echo=11,ENA=9,IN1=8,IN2=7,IN3=6,IN4=5,ENB=3; void setup(){ pinMode(trig,OUTPUT);pinMode(echo,INPUT); int p[]={ENA,IN1,IN2,IN3,IN4,ENB}; for(int i=0;i<6;i++)pinMode(p[i],OUTPUT); } float getDist(){ digitalWrite(trig,LOW);delayMicroseconds(2); digitalWrite(trig,HIGH);delayMicroseconds(10); digitalWrite(trig,LOW); return(pulseIn(echo,HIGH)*0.034)/2; } void loop(){ float d=getDist(); if(d>20){ digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW); digitalWrite(IN3,HIGH);digitalWrite(IN4,LOW); analogWrite(ENA,180);analogWrite(ENB,180); }else{ digitalWrite(IN1,LOW);digitalWrite(IN2,HIGH); digitalWrite(IN3,LOW);digitalWrite(IN4,LOW); analogWrite(ENA,150); delay(600); } delay(100); }
Arduino // Ex 6: PWM motor speed display on LCD #include <LiquidCrystal.h> LiquidCrystal lcd(12,11,5,4,3,2); int ENA=9,IN1=8,IN2=7; void setup(){lcd.begin(16,2);pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);} void loop(){ int pot=analogRead(A0); int spd=map(pot,0,1023,0,255); analogWrite(ENA,spd); lcd.clear();lcd.print("Speed: ");lcd.print(spd); lcd.setCursor(0,1);lcd.print(map(spd,0,255,0,100));lcd.print("%"); delay(200); }
Arduino // Ex 7: Timed motor sequence int ENA=9,IN1=8,IN2=7; void setup(){pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);} void loop(){ int speeds[]={50,100,150,200,255}; digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW); for(int i=0;i<5;i++){analogWrite(ENA,speeds[i]);delay(1000);} digitalWrite(IN1,LOW);digitalWrite(IN2,LOW);delay(2000); }
Arduino // Ex 8: Motor with emergency stop button int ENA=9,IN1=8,IN2=7,stopBtn=2; bool running=true; void setup(){pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);pinMode(stopBtn,INPUT_PULLUP);} void loop(){ if(digitalRead(stopBtn)==LOW) running=!running; if(running){digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);analogWrite(ENA,200);} else{digitalWrite(IN1,LOW);digitalWrite(IN2,LOW);} delay(200); }
Arduino // Ex 9: Temperature-controlled fan motor #include <DHT.h> DHT dht(2,DHT22); int ENA=9,IN1=8,IN2=7; void setup(){dht.begin();pinMode(ENA,OUTPUT);pinMode(IN1,OUTPUT);pinMode(IN2,OUTPUT);digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);} void loop(){ delay(2000); float t=dht.readTemperature(); int spd=constrain(map(t,25,45,0,255),0,255); analogWrite(ENA,spd); }
Arduino // Ex 10: Dual motor independent control via Serial int ENA=9,IN1=8,IN2=7,IN3=6,IN4=5,ENB=3; void setup(){Serial.begin(9600);int p[]={ENA,IN1,IN2,IN3,IN4,ENB};for(int i=0;i<6;i++)pinMode(p[i],OUTPUT);} void loop(){ if(Serial.available()){ char c=Serial.read(); switch(c){ case 'W':digitalWrite(IN1,HIGH);digitalWrite(IN2,LOW);digitalWrite(IN3,HIGH);digitalWrite(IN4,LOW);analogWrite(ENA,200);analogWrite(ENB,200);break; case 'X':digitalWrite(IN1,LOW);digitalWrite(IN2,LOW);digitalWrite(IN3,LOW);digitalWrite(IN4,LOW);break; } } }
4.6 MCQs โ Chapter 4 (20 Questions)
L298N is a:
- Single H-bridge driver
- Dual H-bridge driver
- Motor encoder
- Servo controller
To control motor speed with L298N, which function is used?
- digitalWrite()
- analogWrite()
- motorSpeed()
- pwmSet()
When IN1=HIGH and IN2=LOW, the motor:
- Stops
- Rotates forward
- Rotates reverse
- Brakes
What happens when both IN1 and IN2 are HIGH?
- Forward
- Reverse
- Brake (hard stop)
- Coast (free spin)
Maximum current per channel of L298N is:
- 500 mA
- 1A
- 2A
- 5A
Why must Arduino GND and motor battery GND be connected?
- To charge battery
- For common voltage reference
- To power Arduino
- Not needed
PWM value 128 represents what percentage of full speed?
- 25%
- 50%
- 75%
- 100%
The ENA pin on L298N controls:
- Direction of Motor A
- Speed of Motor A
- Direction of Motor B
- Motor encoder
Motor supply voltage range for L298N is:
- 1Vโ3V
- 5Vโ35V
- 12Vโ48V
- 3.3Vโ5V
To make a robot car turn left, you should:
- Stop left motor, run right motor
- Stop right motor, run left motor
- Run both motors forward
- Stop both motors
What is an H-bridge?
- A type of resistor
- A circuit that allows voltage to be applied across a load in either direction
- A bridge rectifier
- A type of capacitor circuit
Which Arduino pins can be used for ENA/ENB?
- Any digital pin
- Only analog pins
- Only PWM-capable pins (marked ~)
- Only pins 0 and 1
The L298N has a built-in 5V regulator. It outputs 5V when motor supply is:
- Less than 5V
- 5Vโ12V with jumper on
- Only 12V exactly
- Never
analogWrite(ENA, 0) will:
- Run motor at full speed
- Run motor at half speed
- Stop the motor (0% duty)
- Brake the motor
Coast vs Brake in L298N โ what's the difference?
- No difference
- Coast = motor freely decelerates; Brake = motor stops instantly
- Brake is slower
- Coast needs more power
How many motors can L298N control simultaneously?
- 1
- 2
- 4
- 8
Why does L298N get hot during operation?
- Defective unit
- Voltage drop across transistors (~2V) dissipates as heat
- Motor is broken
- Wrong wiring
map(analogRead(A0), 0, 1023, 0, 255) converts pot reading to:
- Voltage
- Motor speed (PWM range)
- Temperature
- Distance
For an obstacle-avoiding robot, which sensor is combined with motors?
- LDR
- DHT22
- Ultrasonic (HC-SR04)
- RFID
constrain(value, min, max) function does what?
- Generates random value
- Limits value within min-max range
- Converts units
- Rounds the value
LED Displays with MAX7219
๐ก From Railway Stations to Stock Tickers โ LED Displays Run India!
Walk into any Indian railway station and you'll see scrolling LED displays showing train timings. Visit Dalal Street and BSE/NSE stock tickers flash prices in real-time. Shop signboards across India glow with LED matrix displays showing offers and greetings.
MAX7219 = LED Display Ka Boss! This single chip can drive 64 LEDs (8ร8 matrix) or 8 seven-segment digits using just 3 wires (SPI). Chain multiple modules together and you've got a full scrolling display โ just like the ones at railway stations. Cost? Under โน150!
5.1 MAX7219 LED Dot Matrix 4-in-1 Display
The MAX7219 4-in-1 dot matrix module combines four 8ร8 LED matrices into a single PCB, giving you a 32ร8 pixel display. The MAX7219 IC handles all the multiplexing โ you just send data over SPI and the chip takes care of driving 64 LEDs per module.
| Parameter | Value |
|---|---|
| Display Type | 8ร8 LED Dot Matrix (ร4 = 32ร8) |
| Driver IC | MAX7219 |
| Operating Voltage | 5V |
| Communication | SPI (CLK, DIN, CS) |
| Max Cascade | 8 modules (theoretically unlimited) |
| LED Color | Red (common), Green/Blue available |
| Brightness Levels | 16 (0โ15) |
| Current per Segment | ~40 mA (set via resistor) |
| Module Cost (India) | โน120โ180 |
SPI Communication
MAX7219 uses a 3-wire SPI interface:
| SPI Pin | Function |
|---|---|
CLK (Clock) | Synchronizes data transfer |
DIN (Data In) | Serial data input (MOSI) |
CS (Chip Select) | Active LOW โ latches data when pulled LOWโHIGH |
Cascading Multiple Modules
To chain multiple MAX7219 modules: connect DOUT of the first module to DIN of the next. All modules share the same CLK and CS lines. Data shifts through like a chain โ the first data sent ends up on the last module.
Connection Table (Arduino โ MAX7219 4-in-1)
| MAX7219 Pin | Arduino Pin | Purpose |
|---|---|---|
| VCC | 5V | Power supply |
| GND | GND | Ground |
| DIN | D11 (MOSI) | Serial data input |
| CS | D10 | Chip select (latch) |
| CLK | D13 (SCK) | Clock signal |
5.2 MD_Parola & MD_MAX72XX Libraries
The MD_MAX72XX library provides low-level control of MAX7219 modules. MD_Parola adds high-level text scrolling, animations, and effects on top of it.
| Function | Description | Example |
|---|---|---|
MD_Parola(type, cs, max) | Constructor โ hardware type, CS pin, number of devices | MD_Parola P = MD_Parola(MD_MAX72XX::FC16_HW, 10, 4) |
P.begin() | Initialize the display | P.begin() |
P.displayText(text, align, speed, pause, effect_in, effect_out) | Set text with scrolling parameters | See code below |
P.displayAnimate() | Animate one frame โ call in loop() | if (P.displayAnimate()) P.displayReset() |
P.displayReset() | Reset animation to start | Called after animation completes |
P.setIntensity(val) | Set brightness (0โ15) | P.setIntensity(5) |
P.setTextAlignment(align) | PA_LEFT, PA_CENTER, PA_RIGHT | P.setTextAlignment(PA_CENTER) |
P.print(text) | Print static text | P.print("HELLO") |
5.3 Full Code โ Scrolling Text on Dot Matrix
Arduino // Program: Scrolling text on MAX7219 4-in-1 Dot Matrix // Board: Arduino Uno // Libraries: MD_Parola, MD_MAX72XX #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> // Hardware configuration #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 // 4 modules in the 4-in-1 #define CS_PIN 10 // Create Parola object MD_Parola myDisplay = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); void setup() { myDisplay.begin(); myDisplay.setIntensity(5); // Brightness 0-15 myDisplay.displayClear(); myDisplay.displayScroll( "WELCOME TO EDUARTHA IOT LAB", PA_CENTER, PA_SCROLL_LEFT, 100 // Speed in ms ); } void loop() { if (myDisplay.displayAnimate()) { myDisplay.displayReset(); // Restart scroll } }
5.4 MAX7219 Digital Tube Display (8-Digit 7-Segment)
The MAX7219 also drives 8-digit 7-segment displays. Each digit has 7 segments (aโg) + decimal point. The MAX7219 multiplexes all 8 digits, and the LedControl library provides easy functions.
| Parameter | Value |
|---|---|
| Display Type | 8-digit 7-segment (common cathode) |
| Driver IC | MAX7219 |
| Interface | SPI (DIN, CS, CLK) |
| Wiring | Same as dot matrix |
LedControl Library Functions
| Function | Description |
|---|---|
LedControl(DIN, CLK, CS, numDevices) | Constructor |
lc.shutdown(addr, false) | Wake up the display |
lc.setIntensity(addr, brightness) | Set brightness (0โ15) |
lc.clearDisplay(addr) | Clear all digits |
lc.setDigit(addr, digit, value, dp) | Set a digit (0โ7) to value (0โ9) |
lc.setChar(addr, digit, char, dp) | Set a digit to character |
Countdown Timer Code (99 โ 00)
Arduino // Program: Countdown timer on MAX7219 8-digit 7-segment display #include <LedControl.h> // LedControl(DIN, CLK, CS, numDevices) LedControl lc = LedControl(11, 13, 10, 1); void setup() { lc.shutdown(0, false); // Wake up display lc.setIntensity(0, 8); // Medium brightness lc.clearDisplay(0); // Clear all digits } void loop() { for (int i = 99; i >= 0; i--) { int tens = i / 10; int ones = i % 10; lc.setDigit(0, 1, tens, false); // Tens digit lc.setDigit(0, 0, ones, false); // Ones digit delay(1000); // 1 second interval } }
5.5 Worked Examples
Example 1: Display Static Text "HELLO"
Arduino #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 #define CS_PIN 10 MD_Parola myDisplay = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); void setup() { myDisplay.begin(); myDisplay.setIntensity(5); myDisplay.setTextAlignment(PA_CENTER); myDisplay.print("HELLO"); } void loop() {}
Example 2: Scrolling Text with Custom Speed
Arduino #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> #define HARDWARE_TYPE MD_MAX72XX::FC16_HW MD_Parola myDisplay = MD_Parola(HARDWARE_TYPE, 10, 4); void setup() { myDisplay.begin(); myDisplay.setIntensity(8); myDisplay.displayScroll("FAST SCROLL!", PA_CENTER, PA_SCROLL_LEFT, 50); // 50ms = fast } void loop() { if (myDisplay.displayAnimate()) myDisplay.displayReset(); }
Example 3: Temperature Reading on 7-Segment
Arduino #include <LedControl.h> #include <DHT.h> LedControl lc = LedControl(11, 13, 10, 1); DHT dht(2, DHT22); void setup() { lc.shutdown(0, false); lc.setIntensity(0, 8); lc.clearDisplay(0); dht.begin(); } void loop() { delay(2000); int temp = (int)dht.readTemperature(); lc.setDigit(0, 3, temp / 10, false); // Tens lc.setDigit(0, 2, temp % 10, true); // Ones + decimal point lc.setChar(0, 1, 'C', false); // ยฐC symbol }
Example 4: Dot Matrix Smiley Animation
Arduino #include <LedControl.h> LedControl lc = LedControl(11, 13, 10, 1); byte smiley[8] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10100101, 0b10011001, 0b01000010, 0b00111100 }; byte sad[8] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10011001, 0b10100101, 0b01000010, 0b00111100 }; void setup() { lc.shutdown(0,false); lc.setIntensity(0,5); } void loop() { for(int i=0;i<8;i++) lc.setRow(0,i,smiley[i]); delay(1000); for(int i=0;i<8;i++) lc.setRow(0,i,sad[i]); delay(1000); }
Example 5: Clock Display on 7-Segment (using millis)
Arduino #include <LedControl.h> LedControl lc = LedControl(11, 13, 10, 1); unsigned long prev = 0; int sec=0, mins=0; void setup() { lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); } void loop() { if (millis() - prev >= 1000) { prev = millis(); sec++; if(sec>=60){sec=0;mins++;} if(mins>=60) mins=0; lc.setDigit(0,3,mins/10,false); lc.setDigit(0,2,mins%10,true); // Decimal = colon lc.setDigit(0,1,sec/10,false); lc.setDigit(0,0,sec%10,false); } }
Example 6: Brightness Control via Potentiometer
Arduino #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> MD_Parola myDisplay = MD_Parola(MD_MAX72XX::FC16_HW, 10, 4); void setup() { myDisplay.begin(); myDisplay.setTextAlignment(PA_CENTER); myDisplay.print("BRIGHT"); } void loop() { int pot = analogRead(A0); int brightness = map(pot, 0, 1023, 0, 15); myDisplay.setIntensity(brightness); delay(100); }
Example 7: Cycling Multiple Messages
Arduino #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> MD_Parola P = MD_Parola(MD_MAX72XX::FC16_HW, 10, 4); const char* msgs[] = {"HELLO", "IoT LAB", "ARDUINO", "MAX7219"}; int idx = 0; void setup() { P.begin(); P.setIntensity(5); } void loop() { P.setTextAlignment(PA_CENTER); P.print(msgs[idx]); idx = (idx + 1) % 4; delay(2000); }
Example 8: Visitor Counter on 7-Segment
Arduino #include <LedControl.h> LedControl lc = LedControl(11, 13, 10, 1); int btnPin = 2, count = 0; void setup() { lc.shutdown(0,false); lc.setIntensity(0,8); lc.clearDisplay(0); pinMode(btnPin, INPUT_PULLUP); showCount(); } void loop() { if (digitalRead(btnPin) == LOW) { count++; if(count>9999) count=0; showCount(); delay(300); // Debounce } } void showCount() { lc.setDigit(0,3,count/1000,false); lc.setDigit(0,2,(count/100)%10,false); lc.setDigit(0,1,(count/10)%10,false); lc.setDigit(0,0,count%10,false); }
Example 9: Scrolling Sensor Data on Dot Matrix
Arduino #include <MD_Parola.h> #include <MD_MAX72XX.h> #include <SPI.h> MD_Parola P = MD_Parola(MD_MAX72XX::FC16_HW, 10, 4); char msg[30]; void setup() { P.begin(); P.setIntensity(5); } void loop() { int sensorVal = analogRead(A0); sprintf(msg, "Sensor: %d", sensorVal); P.displayScroll(msg, PA_LEFT, PA_SCROLL_LEFT, 80); while (!P.displayAnimate()) {} delay(500); }
Example 10: Binary Counter on Dot Matrix (Single 8ร8)
Arduino #include <LedControl.h> LedControl lc = LedControl(11, 13, 10, 1); void setup() { lc.shutdown(0,false); lc.setIntensity(0,5); lc.clearDisplay(0); } void loop() { for(int i=0; i<256; i++) { for(int row=0; row<8; row++) lc.setRow(0, row, (i>>row) & 1 ? 0xFF : 0x00); delay(200); } }
MD_MAX72XX::FC16_HW hardware type. (4) If text appears reversed/mirrored, change hardware type to PAROLA_HW or GENERIC_HW. (5) Ensure SPI pins (D11=MOSI, D13=SCK) are correct โ they're hardware SPI.
5.6 MCQs โ Chapter 5 (20 Questions)
MAX7219 communicates with Arduino using which protocol?
- I2C
- UART
- SPI
- One-Wire
How many LEDs can a single MAX7219 IC drive?
- 16
- 32
- 64
- 128
What is the resolution of a MAX7219 4-in-1 dot matrix display?
- 8ร8 pixels
- 16ร8 pixels
- 32ร8 pixels
- 64ร8 pixels
To cascade multiple MAX7219 modules, which pin connects to the next module's DIN?
- CLK
- CS
- DOUT
- VCC
How many brightness levels does MAX7219 support?
- 8
- 10
- 16
- 256
Which Arduino pin is typically used for DIN (MOSI) with MAX7219?
- D10
- D11
- D12
- D13
Which library provides high-level text scrolling on MAX7219 dot matrix?
- LedControl
- MD_Parola
- Adafruit_GFX
- FastLED
What does the CS (Chip Select) pin do in SPI?
- Sends clock signal
- Carries data
- Latches data when toggled LOWโHIGH
- Powers the chip
The LedControl library function setDigit(0, 3, 5, true) displays:
- Digit 5 on position 3 with decimal point
- Digit 3 on position 5
- Digit 0 on position 3
- Nothing โ invalid call
What is the operating voltage of MAX7219?
- 3.3V
- 5V
- 9V
- 12V
In MD_Parola, which function must be called repeatedly in loop() for animations?
- displayText()
- displayAnimate()
- displayScroll()
- displayReset()
How many 7-segment digits can one MAX7219 drive?
- 4
- 6
- 8
- 16
What happens when you call lc.shutdown(0, false)?
- Turns off the display
- Wakes up the display (exits shutdown mode)
- Resets brightness
- Clears all digits
SPI stands for:
- Serial Peripheral Interface
- Simple Protocol Interface
- Synchronous Parallel Interface
- Serial Pin Integration
For the hardware type FC16_HW in MD_Parola, what does FC16 refer to?
- A type of Arduino board
- A specific PCB layout for MAX7219 modules
- A font style
- A communication speed
The maximum number of MAX7219 modules that can be cascaded is:
- 4
- 8
- 16
- Theoretically unlimited (practically ~8)
To display the number "42" on positions 1 and 0 of a 7-segment display:
- lc.setDigit(0,1,4,false); lc.setDigit(0,0,2,false);
- lc.setDigit(0,0,4,false); lc.setDigit(0,1,2,false);
- lc.setChar(0,1,'4',false); lc.setChar(0,0,'2',false);
- Both A and C are correct
Which pin on Arduino Uno is the hardware SPI clock (SCK)?
- D10
- D11
- D12
- D13
If the dot matrix display shows text in reverse, you should:
- Reverse the DIN and CLK wires
- Change the hardware type in code (e.g., FC16_HW to PAROLA_HW)
- Use a different library
- Replace the module
setIntensity(0, 15) sets the display to:
- Minimum brightness
- Half brightness
- Maximum brightness
- Display off
RFID Module with Arduino (RC522)
๐ท๏ธ Tap & Go โ RFID Powers Your Daily Life!
Every time you tap your Delhi Metro card, swipe your office ID, or cruise through a FASTag toll booth โ you're using RFID technology. Amazon and Flipkart warehouses use RFID to track millions of packages. Libraries use it for book checkout. It's the invisible technology that keeps India moving!
RFID = Contactless Magic! The RC522 module costs just โน120 and can read RFID cards/tags from up to 5cm away. By the end of this chapter, you'll build your own access control system โ just like the ones at office doors!
6.1 RFID Concept
RFID stands for Radio Frequency Identification. It's a wireless system with two components:
| Component | Description |
|---|---|
| RFID Reader (RC522) | Emits radio waves and reads data from tags |
| RFID Tag/Card | Contains a microchip + antenna; stores a unique ID (UID) |
Active vs Passive Tags
| Feature | Passive Tag | Active Tag |
|---|---|---|
| Battery | No battery โ powered by reader's RF field | Has its own battery |
| Range | Short (1โ10 cm) | Long (up to 100m) |
| Cost | โน5โ20 per tag | โน500+ per tag |
| Example | Metro card, ID card | Vehicle tracking, logistics |
RC522 Specifications
| Parameter | Value |
|---|---|
| Operating Voltage | 3.3V (NOT 5V!) |
| Operating Frequency | 13.56 MHz |
| Communication Interface | SPI |
| Read Range | ~5 cm (depending on tag) |
| Supported Cards | MIFARE 1K, MIFARE 4K, MIFARE Ultralight |
| Data Transfer Rate | 10 Mbit/s |
| Current (idle) | 13โ26 mA |
| Module Cost (India) | โน100โ150 (includes 1 card + 1 keychain tag) |
6.2 Pin Connections
RC522 Pin Description
| RC522 Pin | Function |
|---|---|
| SDA (SS) | SPI Slave Select / Chip Select |
| SCK | SPI Clock |
| MOSI | SPI Master Out Slave In (Data to RC522) |
| MISO | SPI Master In Slave Out (Data from RC522) |
| IRQ | Interrupt (usually not connected) |
| GND | Ground |
| RST | Reset |
| 3.3V | Power supply (3.3V only!) |
Connection Table (Arduino โ RC522)
| RC522 Pin | Arduino Pin | Purpose |
|---|---|---|
| 3.3V | 3.3V | Power (NOT 5V!) |
| GND | GND | Ground |
| RST | D9 | Reset |
| SDA (SS) | D10 | SPI Chip Select |
| MOSI | D11 | SPI Data to RC522 |
| MISO | D12 | SPI Data from RC522 |
| SCK | D13 | SPI Clock |
| IRQ | Not connected | Interrupt (optional) |
6.3 MFRC522 Library
Install the MFRC522 library by GithubCommunity from Arduino Library Manager.
| Function | Description |
|---|---|
MFRC522 mfrc522(SS_PIN, RST_PIN) | Constructor โ chip select and reset pins |
mfrc522.PCD_Init() | Initialize the reader |
mfrc522.PICC_IsNewCardPresent() | Returns true if a new card is in range |
mfrc522.PICC_ReadCardSerial() | Reads the card's serial/UID data |
mfrc522.uid.uidByte[i] | Access individual UID bytes (0โ3) |
mfrc522.uid.size | Number of bytes in the UID |
mfrc522.PICC_HaltA() | Halt communication with the card |
mfrc522.PCD_StopCrypto1() | Stop encryption on PCD side |
6.4 Read Card UID โ Basic Code
Arduino // Program: Read RFID card UID using RC522 // Board: Arduino Uno // Connections: SDA=D10, SCK=D13, MOSI=D11, MISO=D12, RST=D9 #include <SPI.h> #include <MFRC522.h> #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522(SS_PIN, RST_PIN); void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); Serial.println("Scan your RFID card..."); } void loop() { // Check for new card if (!mfrc522.PICC_IsNewCardPresent()) return; if (!mfrc522.PICC_ReadCardSerial()) return; // Print UID Serial.print("Card UID: "); for (byte i = 0; i < mfrc522.uid.size; i++) { Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); Serial.print(mfrc522.uid.uidByte[i], HEX); } Serial.println(); mfrc522.PICC_HaltA(); }
6.5 Access Control Project
Arduino // Project: RFID Access Control System // Authorized card โ Green LED + Servo opens door // Unauthorized โ Red LED + Buzzer alarm #include <SPI.h> #include <MFRC522.h> #include <Servo.h> #define SS_PIN 10 #define RST_PIN 9 #define GREEN_LED 6 #define RED_LED 7 #define BUZZER 8 #define SERVO_PIN 3 MFRC522 mfrc522(SS_PIN, RST_PIN); Servo doorServo; // Authorized card UID (replace with your card's UID) byte authorizedUID[4] = {0xA3, 0xB7, 0x2E, 0x1F}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); doorServo.attach(SERVO_PIN); doorServo.write(0); // Door locked pinMode(GREEN_LED, OUTPUT); pinMode(RED_LED, OUTPUT); pinMode(BUZZER, OUTPUT); Serial.println("Access Control Ready. Scan card..."); } void loop() { if (!mfrc522.PICC_IsNewCardPresent()) return; if (!mfrc522.PICC_ReadCardSerial()) return; bool authorized = true; for (byte i = 0; i < 4; i++) { if (mfrc522.uid.uidByte[i] != authorizedUID[i]) { authorized = false; break; } } if (authorized) { Serial.println("ACCESS GRANTED!"); digitalWrite(GREEN_LED, HIGH); doorServo.write(90); // Unlock door delay(3000); doorServo.write(0); // Lock door digitalWrite(GREEN_LED, LOW); } else { Serial.println("ACCESS DENIED!"); digitalWrite(RED_LED, HIGH); tone(BUZZER, 1000, 1000); // 1kHz beep for 1 second delay(2000); digitalWrite(RED_LED, LOW); } mfrc522.PICC_HaltA(); }
6.6 Worked Examples
Example 1: Simple Card Detection
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); } void loop() { if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { Serial.println("Card Detected!"); mfrc522.PICC_HaltA(); delay(1000); } }
Example 2: Display UID on LCD
Arduino #include <SPI.h> #include <MFRC522.h> #include <LiquidCrystal.h> MFRC522 mfrc522(10, 9); LiquidCrystal lcd(7, 6, 5, 4, 3, 2); void setup() { lcd.begin(16,2); SPI.begin(); mfrc522.PCD_Init(); lcd.print("Scan Card..."); } void loop() { if (!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; lcd.clear(); lcd.print("UID:"); lcd.setCursor(0,1); for(byte i=0;i<mfrc522.uid.size;i++) { if(mfrc522.uid.uidByte[i]<0x10) lcd.print("0"); lcd.print(mfrc522.uid.uidByte[i], HEX); lcd.print(" "); } mfrc522.PICC_HaltA(); delay(2000); }
Example 3: Multiple Authorized Cards
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); byte cards[3][4] = { {0xA3,0xB7,0x2E,0x1F}, // Card 1 (Rahul) {0xD4,0x12,0x8A,0x5C}, // Card 2 (Priya) {0x7B,0xE5,0x44,0x91} // Card 3 (Admin) }; const char* names[] = {"Rahul", "Priya", "Admin"}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; for(int c=0;c<3;c++) { bool match=true; for(byte i=0;i<4;i++) if(mfrc522.uid.uidByte[i]!=cards[c][i]) match=false; if(match) { Serial.print("Welcome, "); Serial.println(names[c]); break; } if(c==2) Serial.println("Unknown card!"); } mfrc522.PICC_HaltA(); delay(1000); }
Example 4: Attendance System (Serial Log)
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); int attendCount = 0; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); Serial.println("Sr.No, UID, Time(ms)"); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; attendCount++; Serial.print(attendCount); Serial.print(", "); for(byte i=0;i<mfrc522.uid.size;i++) { Serial.print(mfrc522.uid.uidByte[i], HEX); Serial.print(" "); } Serial.print(", "); Serial.println(millis()); mfrc522.PICC_HaltA(); delay(2000); }
Example 5: RFID LED Toggle
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); int ledPin = 6; bool ledState = false; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); pinMode(ledPin,OUTPUT); } void loop() { if(mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { ledState = !ledState; digitalWrite(ledPin, ledState ? HIGH : LOW); Serial.println(ledState ? "LED ON" : "LED OFF"); mfrc522.PICC_HaltA(); delay(1000); } }
Example 6: RFID Door Lock with Servo
Arduino #include <SPI.h> #include <MFRC522.h> #include <Servo.h> MFRC522 mfrc522(10, 9); Servo lockServo; byte key[4] = {0xA3,0xB7,0x2E,0x1F}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); lockServo.attach(3); lockServo.write(0); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; bool ok=true; for(byte i=0;i<4;i++) if(mfrc522.uid.uidByte[i]!=key[i]) ok=false; if(ok) { Serial.println("Door Unlocked!"); lockServo.write(90); delay(5000); lockServo.write(0); } else Serial.println("Wrong Card!"); mfrc522.PICC_HaltA(); delay(1000); }
Example 7: Student Record Lookup
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); byte students[2][4] = {{0xA3,0xB7,0x2E,0x1F},{0xD4,0x12,0x8A,0x5C}}; const char* info[] = {"Rahul|CS|Roll:101", "Priya|ECE|Roll:205"}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; for(int s=0;s<2;s++) { bool m=true; for(byte i=0;i<4;i++) if(mfrc522.uid.uidByte[i]!=students[s][i]) m=false; if(m) { Serial.print("Student: "); Serial.println(info[s]); break; } if(s==1) Serial.println("Student not found!"); } mfrc522.PICC_HaltA(); delay(1000); }
Example 8: Card Tap Counter
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); int tapCount = 0; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); } void loop() { if(mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { tapCount++; Serial.print("Total Taps: "); Serial.println(tapCount); mfrc522.PICC_HaltA(); delay(1000); } }
Example 9: Buzzer Alarm for Unauthorized Cards
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); int buzzer = 8; byte allowed[4] = {0xA3,0xB7,0x2E,0x1F}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); pinMode(buzzer,OUTPUT); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; bool ok=true; for(byte i=0;i<4;i++) if(mfrc522.uid.uidByte[i]!=allowed[i]) ok=false; if(!ok) { Serial.println("INTRUDER ALERT!"); for(int i=0;i<5;i++) { tone(buzzer,2000,200); delay(300); } } else Serial.println("Welcome!"); mfrc522.PICC_HaltA(); delay(1000); }
Example 10: RFID with Relay Control
Arduino #include <SPI.h> #include <MFRC522.h> MFRC522 mfrc522(10, 9); int relayPin = 6; bool relayState = false; byte masterCard[4] = {0xA3,0xB7,0x2E,0x1F}; void setup() { Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init(); pinMode(relayPin,OUTPUT); digitalWrite(relayPin,LOW); } void loop() { if(!mfrc522.PICC_IsNewCardPresent() || !mfrc522.PICC_ReadCardSerial()) return; bool ok=true; for(byte i=0;i<4;i++) if(mfrc522.uid.uidByte[i]!=masterCard[i]) ok=false; if(ok) { relayState = !relayState; digitalWrite(relayPin, relayState ? HIGH : LOW); Serial.println(relayState ? "Relay ON" : "Relay OFF"); } mfrc522.PICC_HaltA(); delay(1000); }
6.7 MCQs โ Chapter 6 (20 Questions)
RFID stands for:
- Radio Frequency Identification
- Rapid File Input Device
- Radio Frequency Integrated Design
- Remote Frequency Identity
What operating voltage does the RC522 module require?
- 5V
- 3.3V
- 9V
- 12V
RC522 communicates with Arduino using which protocol?
- I2C
- UART
- SPI
- One-Wire
What is the operating frequency of RC522?
- 125 kHz
- 13.56 MHz
- 2.4 GHz
- 900 MHz
A passive RFID tag:
- Has its own battery
- Gets power from the reader's RF field
- Needs USB power
- Only works with WiFi
What does UID stand for in RFID?
- Universal Input Data
- Unique Identification
- Unique Identifier
- User Interface Design
Which function checks if a new RFID card is present?
- mfrc522.readCard()
- mfrc522.PICC_IsNewCardPresent()
- mfrc522.cardAvailable()
- mfrc522.scanCard()
The approximate read range of RC522 is:
- ~5 cm
- ~50 cm
- ~5 meters
- ~50 meters
What happens if you connect RC522 VCC to 5V instead of 3.3V?
- It works faster
- It reads from longer range
- The module may be permanently damaged
- No difference
mfrc522.uid.uidByte[0] returns:
- The card type
- The first byte of the card's UID
- The reader's firmware version
- The signal strength
MIFARE 1K card has how much storage?
- 64 bytes
- 512 bytes
- 1 KB (1024 bytes)
- 4 KB
Which pin on RC522 is NOT typically connected for basic UID reading?
- SDA
- SCK
- IRQ
- RST
In the access control project, to compare UID bytes, we use:
- String comparison
- Byte-by-byte array comparison
- Hash function
- Analog comparison
SPI requires how many wires (excluding power)?
- 1
- 2
- 3
- 4
FASTag in India uses which RFID frequency band?
- 125 kHz (LF)
- 13.56 MHz (HF)
- 860โ960 MHz (UHF)
- 2.4 GHz (Microwave)
What does mfrc522.PCD_Init() do?
- Reads the card
- Initializes the RFID reader module
- Sends data to the card
- Resets the UID
Which Arduino pin connects to RC522's RST pin?
- D10
- D9
- D11
- D13
PICC_HaltA() is used to:
- Initialize the reader
- Stop communication with the current card
- Read the next card
- Change the card's UID
For an RFID attendance system, each card tap should be:
- Ignored
- Logged with UID, timestamp, and serial number
- Counted only once ever
- Displayed on LED
Delhi Metro card uses which RFID technology?
- Active UHF RFID
- Passive HF RFID (MIFARE)
- Bluetooth Low Energy
- NFC only
Pulse Oximeter with MAX30100
โค๏ธ From ICU Monitors to Your Fingertip โ Pulse Oximetry Saves Lives!
During COVID-19, pulse oximeters became as common as thermometers in Indian households. Doctors at AIIMS Delhi and Apollo Hospitals used them to detect "happy hypoxia" โ when patients felt fine but their oxygen was dangerously low. The Aarogya Setu app even recommended home monitoring.
MAX30100 = Hospital-Grade Sensor at โน200! This tiny sensor uses Red + Infrared LEDs and a photodetector to measure both SpO2 (blood oxygen) and Heart Rate (BPM) โ the same principle used in โน50,000 hospital monitors. Build your own health monitor today!
7.1 MAX30100 Sensor
The MAX30100 is an integrated pulse oximetry and heart-rate sensor. It combines two LEDs (Red + IR), a photodetector, and signal processing โ all in a tiny package.
How It Works
Oxygenated hemoglobin (HbOโ) absorbs more infrared light (880nm) and lets red light pass. Deoxygenated hemoglobin (Hb) absorbs more red light (660nm) and lets infrared pass. By comparing the absorption ratio of Red vs IR light through your fingertip, the sensor calculates SpOโ percentage.
MAX30100 Specifications
| Parameter | Value |
|---|---|
| Sensor Type | Integrated Pulse Oximeter + Heart Rate |
| IC Operating Voltage | 1.8V โ 3.3V |
| Module Operating Voltage | 5V (onboard regulator) |
| Communication Interface | I2C |
| I2C Address | 0x57 |
| SpO2 Accuracy | ยฑ2% |
| Heart Rate Range | 30 โ 240 BPM |
| Red LED Wavelength | 660 nm |
| IR LED Wavelength | 880 nm |
| Current (LEDs active) | ~20 mA |
| Module Cost (India) | โน150โ250 |
7.2 Pin Connections
Connection Table (Arduino โ MAX30100)
| MAX30100 Pin | Arduino Pin | Purpose |
|---|---|---|
| VIN | 5V | Power (module has onboard regulator) |
| GND | GND | Ground |
| SCL | A5 (SCL) | I2C Clock |
| SDA | A4 (SDA) | I2C Data |
| INT | D2 (optional) | Interrupt (beat detection) |
7.3 MAX30100_PulseOximeter Library
Install MAX30100lib by OXullo Intersecans from Arduino Library Manager.
| Function | Description |
|---|---|
PulseOximeter pox | Create PulseOximeter object |
pox.begin() | Initialize the sensor (returns true on success) |
pox.update() | Must be called frequently in loop() โ processes sensor data |
pox.getHeartRate() | Returns heart rate in BPM (float) |
pox.getSpO2() | Returns blood oxygen saturation in % (uint8_t) |
pox.setOnBeatDetectedCallback(fn) | Set callback function for each heartbeat detected |
pox.setIRLedCurrent(val) | Set IR LED current (MAX30100_LED_CURR_*) |
7.4 Full Code โ Heart Rate & SpO2 Monitor
Arduino // Program: Heart Rate & SpO2 Monitor using MAX30100 // Board: Arduino Uno // Connections: SDA=A4, SCL=A5, VIN=5V, GND=GND #include <Wire.h> #include <MAX30100_PulseOximeter.h> #define REPORTING_PERIOD_MS 1000 PulseOximeter pox; uint32_t lastReport = 0; // Callback for beat detection void onBeatDetected() { Serial.println("โฅ Beat!"); } void setup() { Serial.begin(9600); Serial.println("Initializing Pulse Oximeter..."); if (!pox.begin()) { Serial.println("MAX30100 FAILED! Check wiring."); while(1); } pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); pox.setOnBeatDetectedCallback(onBeatDetected); Serial.println("Place your finger on the sensor..."); } void loop() { pox.update(); // MUST call frequently! if (millis() - lastReport > REPORTING_PERIOD_MS) { Serial.print("Heart Rate: "); Serial.print(pox.getHeartRate()); Serial.print(" BPM | SpO2: "); Serial.print(pox.getSpO2()); Serial.println("%"); lastReport = millis(); } }
7.5 Health Monitoring Project
Arduino // Project: Health Monitor with LCD + Buzzer + LED indicators // Normal SpO2: 95-100%, Low: 90-94%, Critical: <90% #include <Wire.h> #include <MAX30100_PulseOximeter.h> #include <LiquidCrystal.h> #define REPORTING_PERIOD_MS 1000 #define GREEN_LED 6 #define RED_LED 7 #define BUZZER 8 PulseOximeter pox; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); uint32_t lastReport = 0; void onBeatDetected() { digitalWrite(GREEN_LED, HIGH); delay(50); digitalWrite(GREEN_LED, LOW); } void setup() { Serial.begin(9600); lcd.begin(16, 2); pinMode(GREEN_LED, OUTPUT); pinMode(RED_LED, OUTPUT); pinMode(BUZZER, OUTPUT); lcd.print("Initializing..."); if (!pox.begin()) { lcd.clear(); lcd.print("SENSOR ERROR!"); while(1); } pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); pox.setOnBeatDetectedCallback(onBeatDetected); lcd.clear(); lcd.print("Place finger..."); } void loop() { pox.update(); if (millis() - lastReport > REPORTING_PERIOD_MS) { float bpm = pox.getHeartRate(); uint8_t spo2 = pox.getSpO2(); lcd.clear(); lcd.print("BPM: "); lcd.print(bpm, 0); lcd.setCursor(0, 1); lcd.print("SpO2: "); lcd.print(spo2); lcd.print("%"); // Health classification if (spo2 >= 95) { lcd.setCursor(10, 1); lcd.print("OK"); digitalWrite(RED_LED, LOW); noTone(BUZZER); } else if (spo2 >= 90) { lcd.setCursor(10, 1); lcd.print("LOW!"); digitalWrite(RED_LED, HIGH); } else if (spo2 > 0) { lcd.setCursor(10, 1); lcd.print("CRIT"); digitalWrite(RED_LED, HIGH); tone(BUZZER, 1500); // Continuous alarm! } // Check abnormal heart rate if (bpm > 120 || (bpm < 50 && bpm > 0)) { tone(BUZZER, 1000, 500); // Warning beep } lastReport = millis(); } }
7.6 Worked Examples
Example 1: Simple Heart Rate Reading
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; uint32_t lastReport = 0; void setup() { Serial.begin(9600); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); } void loop() { pox.update(); if(millis()-lastReport > 1000) { Serial.print("BPM: "); Serial.println(pox.getHeartRate()); lastReport = millis(); } }
Example 2: SpO2 Only Reading
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; uint32_t lastReport = 0; void setup() { Serial.begin(9600); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); } void loop() { pox.update(); if(millis()-lastReport > 1000) { uint8_t spo2 = pox.getSpO2(); Serial.print("SpO2: "); Serial.print(spo2); Serial.println("%"); lastReport = millis(); } }
Example 3: Beat Detection with LED Blink
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; int ledPin = 13; void onBeat() { digitalWrite(ledPin, !digitalRead(ledPin)); } void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); pox.setOnBeatDetectedCallback(onBeat); } void loop() { pox.update(); }
Example 4: Heart Rate on LCD
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> #include <LiquidCrystal.h> PulseOximeter pox; LiquidCrystal lcd(12,11,5,4,3,2); uint32_t lastReport = 0; void setup() { lcd.begin(16,2); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); lcd.print("Place finger..."); } void loop() { pox.update(); if(millis()-lastReport > 1000) { lcd.clear(); lcd.print("Heart Rate:"); lcd.setCursor(0,1); lcd.print(pox.getHeartRate(), 0); lcd.print(" BPM"); lastReport = millis(); } }
Example 5: SpO2 + BPM on LCD with Status
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> #include <LiquidCrystal.h> PulseOximeter pox; LiquidCrystal lcd(12,11,5,4,3,2); uint32_t lastReport = 0; void setup() { lcd.begin(16,2); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); } void loop() { pox.update(); if(millis()-lastReport > 1000) { float bpm = pox.getHeartRate(); uint8_t spo2 = pox.getSpO2(); lcd.clear(); lcd.print("BPM:"); lcd.print(bpm,0); lcd.setCursor(9,0); lcd.print("O2:"); lcd.print(spo2); lcd.print("%"); lcd.setCursor(0,1); if(spo2>=95) lcd.print("Status: NORMAL"); else if(spo2>=90) lcd.print("Status: LOW!"); else if(spo2>0) lcd.print("CRITICAL!!!"); else lcd.print("No finger..."); lastReport = millis(); } }
Example 6: Data Logger to Serial (CSV)
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; uint32_t lastReport = 0; int reading = 0; void setup() { Serial.begin(9600); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); Serial.println("Reading,BPM,SpO2,Time_ms"); } void loop() { pox.update(); if(millis()-lastReport > 2000) { reading++; Serial.print(reading); Serial.print(","); Serial.print(pox.getHeartRate()); Serial.print(","); Serial.print(pox.getSpO2()); Serial.print(","); Serial.println(millis()); lastReport = millis(); } }
Example 7: Heart Rate Zone Indicator
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; uint32_t lastReport = 0; void setup() { Serial.begin(9600); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); } void loop() { pox.update(); if(millis()-lastReport > 1000) { float bpm = pox.getHeartRate(); Serial.print("BPM: "); Serial.print(bpm); if(bpm < 60) Serial.println(" โ Resting"); else if(bpm < 100) Serial.println(" โ Normal"); else if(bpm < 140) Serial.println(" โ Exercise"); else Serial.println(" โ DANGER! Too high!"); lastReport = millis(); } }
Example 8: Moving Average BPM (Smoothing)
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; float readings[5]; int idx=0; uint32_t lastReport = 0; void setup() { Serial.begin(9600); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); for(int i=0;i<5;i++) readings[i]=0; } void loop() { pox.update(); if(millis()-lastReport > 1000) { readings[idx] = pox.getHeartRate(); idx = (idx+1) % 5; float avg = 0; for(int i=0;i<5;i++) avg += readings[i]; avg /= 5; Serial.print("Avg BPM: "); Serial.println(avg); lastReport = millis(); } }
Example 9: Low SpO2 Alarm System
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> PulseOximeter pox; int buzzer = 8, redLed = 7; uint32_t lastReport = 0; void setup() { Serial.begin(9600); pinMode(buzzer,OUTPUT); pinMode(redLed,OUTPUT); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); } void loop() { pox.update(); if(millis()-lastReport > 1000) { uint8_t spo2 = pox.getSpO2(); Serial.print("SpO2: "); Serial.println(spo2); if(spo2 > 0 && spo2 < 90) { digitalWrite(redLed, HIGH); tone(buzzer, 2000); Serial.println("!!! CRITICAL SpO2 !!!"); } else { digitalWrite(redLed, LOW); noTone(buzzer); } lastReport = millis(); } }
Example 10: Full Patient Monitor (LCD + Buzzer + LEDs)
Arduino #include <Wire.h> #include <MAX30100_PulseOximeter.h> #include <LiquidCrystal.h> PulseOximeter pox; LiquidCrystal lcd(12,11,5,4,3,2); int greenLed=6, redLed=7, buzzer=8; uint32_t lastReport=0; void onBeat() { digitalWrite(greenLed,HIGH); delay(30); digitalWrite(greenLed,LOW); } void setup() { Serial.begin(9600); lcd.begin(16,2); pinMode(greenLed,OUTPUT); pinMode(redLed,OUTPUT); pinMode(buzzer,OUTPUT); pox.begin(); pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA); pox.setOnBeatDetectedCallback(onBeat); lcd.print("Patient Monitor"); lcd.setCursor(0,1); lcd.print("Place finger..."); } void loop() { pox.update(); if(millis()-lastReport > 1000) { float bpm=pox.getHeartRate(); uint8_t spo2=pox.getSpO2(); lcd.clear(); lcd.print("BPM:"); lcd.print(bpm,0); lcd.setCursor(8,0); lcd.print("O2:"); lcd.print(spo2); lcd.print("%"); lcd.setCursor(0,1); bool alarm = false; if(spo2>0 && spo2<90) { lcd.print("SpO2 CRITICAL!"); alarm=true; } else if(bpm>120) { lcd.print("BPM HIGH!"); alarm=true; } else if(bpm>0 && bpm<50) { lcd.print("BPM LOW!"); alarm=true; } else lcd.print("Status: NORMAL"); digitalWrite(redLed, alarm?HIGH:LOW); if(alarm) tone(buzzer,1500,500); else noTone(buzzer); // CSV log to Serial Serial.print(bpm); Serial.print(","); Serial.print(spo2); Serial.print(","); Serial.println(alarm?"ALARM":"OK"); lastReport = millis(); } }
pox.update() must be called very frequently โ avoid using delay() in your loop! (4) Some MAX30100 modules need I2C pull-up resistors removed (if module already has them). (5) Try different setIRLedCurrent() values.
7.7 MCQs โ Chapter 7 (20 Questions)
MAX30100 measures which two parameters?
- Temperature and humidity
- Heart rate (BPM) and blood oxygen (SpO2)
- Blood pressure and pulse
- ECG and respiration rate
MAX30100 communicates with Arduino using:
- SPI
- I2C
- UART
- One-Wire
What is the I2C address of MAX30100?
- 0x27
- 0x3C
- 0x57
- 0x68
Which two wavelengths of light does MAX30100 use?
- Red (660nm) and Infrared (880nm)
- Green (530nm) and Blue (470nm)
- UV (365nm) and Red (660nm)
- White and Infrared
Normal SpO2 range for a healthy person is:
- 80โ90%
- 85โ95%
- 95โ100%
- 100% only
Why must pox.update() be called frequently in loop()?
- To save battery
- To process raw sensor data and calculate BPM/SpO2
- To reset the sensor
- To calibrate the LEDs
Oxygenated hemoglobin absorbs more:
- Red light
- Infrared light
- Green light
- UV light
Which Arduino pins are used for I2C?
- D0, D1
- D10, D11
- A4 (SDA), A5 (SCL)
- D2, D3
What does SpO2 stand for?
- Special Oxygen Level 2
- Peripheral capillary oxygen saturation
- Systemic Pulse Oxygen
- Standard Pulse Output 2
The setOnBeatDetectedCallback() function is used to:
- Set the heart rate manually
- Register a function called each time a heartbeat is detected
- Stop the sensor
- Calibrate the sensor
SpO2 below 90% is classified as:
- Normal
- Low
- Critical โ needs immediate medical attention
- Moderate
Why do cold fingers give inaccurate SpO2 readings?
- Cold damages the sensor
- Reduced blood flow to extremities weakens the signal
- Cold changes oxygen levels
- The sensor can't work below 20ยฐC
MAX30100 module operating voltage is:
- 1.8V only
- 3.3V only
- 5V (module has onboard voltage regulator)
- 12V
Normal resting heart rate for adults is:
- 30โ50 BPM
- 60โ100 BPM
- 100โ150 BPM
- 150โ200 BPM
During COVID-19, AIIMS recommended hospitalization if SpO2 falls below:
- 98%
- 96%
- 94%
- 90%
What does the photodetector in MAX30100 measure?
- Temperature of the finger
- Light transmitted through or reflected from the finger
- Electrical signals from the heart
- Blood pressure
Using delay() in the loop with MAX30100 causes:
- More accurate readings
- Sensor to read faster
- Inaccurate or zero readings due to missed sampling
- No effect
I2C uses how many data wires?
- 1
- 2
- 3
- 4
To smooth noisy BPM readings, which technique is used?
- Increase LED current
- Moving average filter
- Reset the sensor
- Use SPI instead of I2C
pox.getSpO2() returns which data type?
- float
- int
- uint8_t (unsigned 8-bit integer)
- String
Bluetooth with Arduino (HC-05)
๐ฏ Why This Matters
Your smartphone connects to speakers, fitness bands, and car systems via Bluetooth. With HC-05 and Arduino, you can build wireless control systems for โน150!
8.1 HC-05 Bluetooth Module
Specifications:
| Parameter | Value |
|---|---|
| Protocol | Bluetooth 2.0 + EDR |
| Frequency | 2.4 GHz ISM band |
| Range | ~10 meters |
| Operating Voltage | 3.3Vโ6V |
| Baud Rate (default) | 9600 bps |
| Modes | Master / Slave / Loop-back |
| Interface | UART (TX, RX) |
8.2 Pin Diagram & Connections
HC-05 Module Pins: โโโโโโโโโโโโโโโโโโโโโโโโ โ HC-05 Bluetooth โ โ โ โ VCC โโโโ 5V Arduino โ โ GND โโโโ GND โ โ TXD โโโโ Pin 10 (RX)โ โ RXD โโโโ Pin 11 (TX)โ โ ๏ธ Use voltage divider! โ EN โโโโ (for AT) โ RXD is 3.3V tolerant โ STATE โโ (optional) โ Use 1K + 2K divider โโโโโโโโโโโโโโโโโโโโโโโโ
| HC-05 Pin | Arduino Pin | Notes |
|---|---|---|
| VCC | 5V | Power supply |
| GND | GND | Common ground |
| TXD | Pin 10 (Software RX) | HC-05 sends data |
| RXD | Pin 11 (Software TX) | Via voltage divider (5Vโ3.3V) |
8.3 AT Commands
Hold EN/KEY button while powering ON to enter AT command mode (LED blinks slowly ~2s).
| Command | Function | Response |
|---|---|---|
| AT | Test connection | OK |
| AT+NAME=MyBT | Set device name | OK |
| AT+BAUD4 | Set baud to 9600 | OK9600 |
| AT+ROLE=0 | Set as slave | OK |
| AT+PSWD=1234 | Set pairing PIN | OK |
| AT+ADDR? | Get MAC address | +ADDR:... |
8.4 Arduino Code: LED Control via Bluetooth
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX=10, TX=11
int ledPin = 13;
void setup() {
Serial.begin(9600);
BTSerial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("Bluetooth LED Control Ready!");
}
void loop() {
if (BTSerial.available()) {
char command = BTSerial.read();
Serial.print("Received: ");
Serial.println(command);
if (command == '1') {
digitalWrite(ledPin, HIGH);
BTSerial.println("LED ON");
Serial.println("LED turned ON");
}
else if (command == '0') {
digitalWrite(ledPin, LOW);
BTSerial.println("LED OFF");
Serial.println("LED turned OFF");
}
}
}
8.5 Multi-Device Control Project
// Control 4 devices via Bluetooth
// Send: 'A'=LED1 ON, 'a'=LED1 OFF, 'B'=Fan ON, etc.
#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11);
int led1=2, led2=3, fan=4, buzzer=5;
void setup() {
BT.begin(9600);
pinMode(led1, OUTPUT); pinMode(led2, OUTPUT);
pinMode(fan, OUTPUT); pinMode(buzzer, OUTPUT);
}
void loop() {
if (BT.available()) {
char c = BT.read();
switch(c) {
case 'A': digitalWrite(led1, HIGH); BT.println("LED1 ON"); break;
case 'a': digitalWrite(led1, LOW); BT.println("LED1 OFF"); break;
case 'B': digitalWrite(fan, HIGH); BT.println("Fan ON"); break;
case 'b': digitalWrite(fan, LOW); BT.println("Fan OFF"); break;
case 'C': digitalWrite(buzzer, HIGH); BT.println("Buzzer ON"); break;
case 'c': digitalWrite(buzzer, LOW); BT.println("Buzzer OFF"); break;
}
}
}
8.6 MCQs โ Chapter 8 (20 Questions)
(a) 900 MHz (b) 2.4 GHz โ (c) 5 GHz (d) 433 MHz
(a) 4800 (b) 9600 โ (c) 115200 (d) 38400
(a) 5V (b) 3.3V โ (c) 1.8V (d) 12V
(a) AT+BAUD (b) AT+NAME โ (c) AT+ROLE (d) AT+PSWD
(a) Wire.h (b) SoftwareSerial.h โ (c) SPI.h (d) Servo.h
(a) 0000 (b) 1234 โ (c) 9999 (d) 1111
(a) 100m (b) ~10m โ (c) 1km (d) 50cm
(a) Slave (b) Master โ (c) Loop-back (d) Monitor
(a) Reset (b) Power-on โ (c) Data transfer (d) Pairing
(a) 10K+10K (b) 1K+2K โ (c) 100+200 (d) 4.7K+4.7K
(a) True/False (b) Number of bytes available โ (c) String (d) Void
(a) AT mode (b) Not connected (waiting) โ (c) Connected (d) Sleep
(a) 4.0 BLE (b) 2.0 + EDR โ (c) 5.0 (d) 3.0
(a) TX (b) RX โ (c) VCC (d) GND
(a) Master (b) Slave โ (c) Bridge (d) Off
(a) WhatsApp (b) Serial Bluetooth Terminal โ (c) Chrome (d) Calculator
(a) 1 Mbps (b) 2-3 Mbps โ (c) 100 Mbps (d) 10 kbps
(a) AM (b) GFSK โ (c) QAM (d) PSK
(a) String (b) Single byte (char) โ (c) Integer array (d) Float
(a) Frequency (b) HC-05 can be master+slave, HC-06 slave only โ (c) Range (d) Price
WiFi with Arduino (ESP8266)
๐ Why This Matters
ESP8266 gives your Arduino WiFi for โน120! Build web-controlled devices, IoT dashboards, and smart home systems โ all accessible from any browser on your network.
9.1 ESP8266 Module Overview
| Parameter | Value |
|---|---|
| CPU | Tensilica L106, 80/160 MHz |
| WiFi | 802.11 b/g/n, 2.4 GHz |
| Flash | 512KB โ 4MB |
| GPIO Pins | 17 (varies by module) |
| Operating Voltage | 3.3V (โ ๏ธ NOT 5V tolerant!) |
| Modes | Station (STA), Access Point (AP), STA+AP |
| Protocols | TCP/IP, HTTP, MQTT |
ESP8266 Pin Layout (ESP-01): โโโโโโโโโโโโโโโโโโโโ โ ESP-01 Module โ โ โ โ VCC โโโ 3.3V โ โ ๏ธ MUST be 3.3V! โ GND โโโ GND โ โ TX โโโ Pin 10 โ โ RX โโโ Pin 11 โ Via voltage divider โ CH_PDโโ 3.3V โ Enable pin (pull HIGH) โ RST โโโ 3.3V โ Reset (pull HIGH) โ GPIO0โโ Float โ LOW = flash mode โ GPIO2โโ Float โ โโโโโโโโโโโโโโโโโโโโ
9.2 AT Commands for ESP8266
| Command | Function |
|---|---|
| AT | Test (response: OK) |
| AT+CWMODE=1 | Station mode |
| AT+CWMODE=2 | Access Point mode |
| AT+CWJAP="SSID","password" | Connect to WiFi |
| AT+CIFSR | Get IP address |
| AT+CIPMUX=1 | Enable multiple connections |
| AT+CIPSERVER=1,80 | Start web server on port 80 |
9.3 Web Server โ Control LED from Browser
Using NodeMCU (ESP8266 board) with Arduino IDE:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = "YourWiFi";
const char* password = "YourPassword";
int ledPin = D2; // GPIO4
ESP8266WebServer server(80);
void handleRoot() {
String html = "<!DOCTYPE html><html><head>";
html += "<title>IoT LED Control</title>";
html += "<style>body{font-family:Arial;text-align:center;padding:50px;}";
html += "button{padding:20px 40px;font-size:24px;margin:10px;border-radius:12px;";
html += "border:none;cursor:pointer;color:white;}";
html += ".on{background:#10b981;} .off{background:#ef4444;}</style></head>";
html += "<body><h1>๐ Smart LED Control</h1>";
html += "<p>LED is: " + String(digitalRead(ledPin) ? "ON ๐ก" : "OFF ๐") + "</p>";
html += "<a href='/on'><button class='on'>Turn ON</button></a>";
html += "<a href='/off'><button class='off'>Turn OFF</button></a>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleOn() { digitalWrite(ledPin, HIGH); server.sendHeader("Location","/"); server.send(303); }
void handleOff() { digitalWrite(ledPin, LOW); server.sendHeader("Location","/"); server.send(303); }
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nConnected! IP: " + WiFi.localIP().toString());
server.on("/", handleRoot);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.begin();
}
void loop() { server.handleClient(); }
9.4 Sending Sensor Data via HTTP
// Send DHT22 data to a web page
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
DHT dht(D4, DHT22);
ESP8266WebServer server(80);
void handleData() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
String json = "{\"temperature\":" + String(temp) +
",\"humidity\":" + String(hum) + "}";
server.send(200, "application/json", json);
}
void setup() {
dht.begin();
WiFi.begin("SSID", "PASS");
while (WiFi.status() != WL_CONNECTED) delay(500);
server.on("/data", handleData);
server.begin();
}
void loop() { server.handleClient(); }
9.5 MCQs โ Chapter 9 (20 Questions)
(a) 5V (b) 3.3V โ (c) 12V (d) 1.8V
(a) AP (b) Station โ (c) Mesh (d) Off
(a) 802.11ac (b) 802.11 b/g/n โ (c) 802.11ax (d) 802.15.4
(a) Stops WiFi (b) Connects to WiFi network โ (c) Creates AP (d) Scans networks
(a) Timer (b) URL route handler โ (c) Interrupt (d) Sensor
(a) MAC address (b) IP address โ (c) SSID (d) Password
(a) Not Found (b) OK (Success) โ (c) Redirect (d) Error
(a) 16 MHz (b) 80/160 MHz โ (c) 1 GHz (d) 8 MHz
(a) GND (b) 3.3V (HIGH) โ (c) 5V (d) Float
(a) Normal mode (b) Flash/Programming mode โ (c) Sleep (d) AT mode
(a) Mode (b) IP address โ (c) SSID (d) Baud rate
(a) Arduino (b) Espressif Systems โ (c) Microchip (d) Intel
(a) setup() (b) loop() โ (c) Header (d) Global scope
(a) I2C only (b) TCP/IP, HTTP, MQTT โ (c) CAN only (d) USB only
(a) ATmega328 (b) ESP8266 โ (c) PIC16F (d) STM32
(a) Disconnected (b) Successfully connected โ (c) Error (d) Scanning
(a) GET (b) POST โ (c) DELETE (d) PATCH
(a) 17 (b) 2 (GPIO0, GPIO2) โ (c) 8 (d) 4
(a) Port (b) HTTP status code โ (c) Delay (d) Pin number
(a) Cheaper (b) Dual-core + BLE + more GPIO โ (c) Smaller (d) Less power
IoT Cloud & Futuristic Technologies
โ๏ธ Why This Matters
ThingSpeak lets you visualize sensor data from anywhere in the world โ for FREE! AWS IoT and Azure IoT power billions of devices. Silicon Labs kits bring IoT to Indian smart homes.
10.1 ThingSpeak IoT Platform
Steps: 1. Create account at thingspeak.com โ 2. Create Channel โ 3. Note API Key โ 4. Send data from ESP8266
// Send DHT22 data to ThingSpeak
#include <ESP8266WiFi.h>
#include <DHT.h>
const char* ssid = "YourWiFi";
const char* password = "YourPass";
const char* server = "api.thingspeak.com";
String apiKey = "YOUR_WRITE_API_KEY";
DHT dht(D4, DHT22);
WiFiClient client;
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
Serial.println("WiFi Connected! IP: " + WiFi.localIP().toString());
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
if (client.connect(server, 80)) {
String postStr = "api_key=" + apiKey;
postStr += "&field1=" + String(temp);
postStr += "&field2=" + String(hum);
client.println("POST /update HTTP/1.1");
client.println("Host: api.thingspeak.com");
client.println("Content-Type: application/x-www-form-urlencoded");
client.println("Content-Length: " + String(postStr.length()));
client.println();
client.print(postStr);
Serial.println("Sent: Temp=" + String(temp) + " Hum=" + String(hum));
}
client.stop();
delay(20000); // ThingSpeak requires 15s minimum between updates
}
10.2 Cloud Platforms Comparison
| Platform | Free Tier | Protocol | Best For |
|---|---|---|---|
| ThingSpeak | Yes (3M messages/yr) | HTTP, MQTT | Learning, prototyping |
| AWS IoT Core | 12 months free | MQTT, HTTP, WebSocket | Enterprise scale |
| Azure IoT Hub | 8000 msgs/day free | MQTT, AMQP, HTTP | Microsoft ecosystem |
| Google Cloud IoT | Limited | MQTT, HTTP | Data analytics |
| Blynk | Yes (limited) | Custom | Mobile app control |
10.3 Smart Home Project
System: ESP8266 + Relay Module + ThingSpeak + Mobile App
// Smart Home: Control relay via ThingSpeak
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
int relayPin = D1;
String readApiKey = "YOUR_READ_API_KEY";
void setup() {
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // Relay OFF (active LOW)
WiFi.begin("SSID", "PASS");
while (WiFi.status() != WL_CONNECTED) delay(500);
}
void loop() {
HTTPClient http;
String url = "http://api.thingspeak.com/channels/YOUR_CHANNEL/fields/1/last.txt";
url += "?api_key=" + readApiKey;
http.begin(url);
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
if (payload.toInt() == 1) digitalWrite(relayPin, LOW); // ON
else digitalWrite(relayPin, HIGH); // OFF
}
http.end();
delay(5000);
}
10.4 Silicon Labs W7230F1 EVB/Kit
Setup Steps:
- Download and install Simplicity Studio from silabs.com
- Connect W7230F1 EVB via USB
- Select board in Simplicity Studio โ Create new project
- Use GPIO driver to control onboard LED
- For mobile control: Use BLE/WiFi to send commands from phone app
// Pseudocode: Si Labs W7230F1 LED Control
// In Simplicity Studio C project:
#include "em_gpio.h"
#include "em_cmu.h"
void initGPIO(void) {
CMU_ClockEnable(cmuClock_GPIO, true);
GPIO_PinModeSet(gpioPortF, 4, gpioModePushPull, 0); // LED0
GPIO_PinModeSet(gpioPortF, 5, gpioModePushPull, 0); // LED1
}
void toggleLED(int led) {
if (led == 0) GPIO_PinOutToggle(gpioPortF, 4);
else GPIO_PinOutToggle(gpioPortF, 5);
}
// Mobile phone control: BLE GATT service receives ON/OFF
// commands and calls toggleLED() โ smart home application
10.5 Future of IoT in India
| Domain | Application | Indian Example |
|---|---|---|
| Smart Cities | Traffic, parking, waste | Smart Cities Mission (100 cities) |
| Agriculture | Soil moisture, drone spray | Fasal, CropIn, Stellapps |
| Healthcare | Remote monitoring, wearables | COVID telemedicine, SanketLife |
| Industry 4.0 | Predictive maintenance | Tata Steel, L&T smart factory |
| Energy | Smart grid, solar monitoring | EESL smart meters |
10.6 MCQs โ Chapter 10 (20 Questions)
(a) 1 second (b) 15 seconds โ (c) 1 minute (d) 5 seconds
(a) CAN (b) HTTP and MQTT โ (c) I2C (d) SPI
(a) Login (b) Authentication for data read/write โ (c) Encryption (d) Routing
(a) HTTP only (b) MQTT โ (c) FTP (d) SMTP
(a) Only DC (b) Both AC and DC devices โ (c) Only AC (d) Only sensors
(a) Arduino (b) Silicon Labs โ (c) Raspberry Pi (d) ESP8266
(a) 10 cities (b) 100 cities โ (c) 500 cities (d) 28 states
(a) Maximum Query Transfer (b) Message Queuing Telemetry Transport โ (c) Multi Queue TCP (d) Minimal Query Transport
(a) 4 (b) 8 โ (c) 16 (d) Unlimited
(a) HIGH (b) LOW โ (c) Floating (d) PWM
(a) Hardware clone (b) Virtual replica of physical system โ (c) Backup server (d) Mirror website
(a) Cloud processing (b) Processing data near the source โ (c) Central server (d) Manual entry
(a) Healthcare (b) Agriculture โ (c) Banking (d) Education
(a) Arduino IDE (b) Simplicity Studio โ (c) VS Code (d) Eclipse
(a) String (b) HTTP status code (int) โ (c) Boolean (d) Void
(a) Web only (b) Mobile app IoT control โ (c) Database (d) Email
(a) First industrial revolution (b) Smart manufacturing with IoT/AI โ (c) Steam power (d) Assembly line
(a) Solar panels (b) Smart meters โ (c) Drones (d) EVs only
(a) Big models (b) Machine learning on microcontrollers โ (c) Cloud ML (d) Database
(a) New Bluetooth (b) Narrowband Internet of Things โ (c) Network Bridge (d) Normal Band
Lab Programs (10 Experiments)
Lab 1: LED Brightness Control using PWM
Objective: Control LED brightness using analogWrite()
Components: Arduino UNO, LED, 220ฮฉ resistor, breadboard
| Arduino | Component |
|---|---|
| Pin 9 (PWM) | LED Anode (+) via 220ฮฉ |
| GND | LED Cathode (โ) |
int ledPin = 9;
void setup() { pinMode(ledPin, OUTPUT); }
void loop() {
for (int i = 0; i <= 255; i += 5) {
analogWrite(ledPin, i); // Increase brightness
delay(30);
}
for (int i = 255; i >= 0; i -= 5) {
analogWrite(ledPin, i); // Decrease brightness
delay(30);
}
}
Viva: 1) What is PWM? 2) analogWrite range? (0-255) 3) Which pins support PWM? (~3,5,6,9,10,11) 4) Duty cycle at analogWrite(127)? (50%) 5) PWM frequency on Arduino? (~490 Hz)
Lab 2: LCD Interfacing
Objective: Display text on 16x2 LCD
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // RS,EN,D4-D7
void setup() { lcd.begin(16, 2); lcd.print("Hello EduArtha!"); lcd.setCursor(0, 1); lcd.print("IoT Lab 2"); }
void loop() {}
Viva: 1) LCD modes? (4-bit, 8-bit) 2) RS pin function? (Register Select) 3) How many chars per line? (16) 4) lcd.setCursor(0,1)? (Row 2, Col 1) 5) V0 pin? (Contrast)
Lab 3: Analog Read and ADC Programming
Objective: Read potentiometer value using ADC
int potPin = A0;
void setup() { Serial.begin(9600); }
void loop() {
int val = analogRead(potPin); // 0-1023
float voltage = val * (5.0/1023.0); // Convert to voltage
Serial.print("ADC: "); Serial.print(val);
Serial.print(" | Voltage: "); Serial.println(voltage);
delay(500);
}
Viva: 1) ADC resolution? (10-bit = 1024 levels) 2) analogRead range? (0-1023) 3) Reference voltage? (5V) 4) Step size? (5/1024 โ 4.88mV) 5) Analog pins? (A0-A5)
Lab 4: DHT22 Temperature & Humidity
#include <DHT.h>
DHT dht(2, DHT22);
void setup() { Serial.begin(9600); dht.begin(); }
void loop() {
float t = dht.readTemperature();
float h = dht.readHumidity();
Serial.print("Temp: "); Serial.print(t); Serial.print("ยฐC | Hum: "); Serial.print(h); Serial.println("%");
delay(2000);
}
Viva: 1) DHT22 accuracy? (ยฑ0.5ยฐC) 2) Protocol? (Single-wire) 3) Pull-up resistor value? (10Kฮฉ) 4) Min read interval? (2s) 5) DHT11 vs DHT22? (DHT22 more accurate)
Lab 5: LDR, Ultrasonic & IR Sensor
// Ultrasonic HC-SR04
int trigPin = 9, echoPin = 10;
void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); }
void loop() {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm");
delay(500);
}
Viva: 1) Speed of sound? (340 m/s) 2) Why divide by 2? (Round trip) 3) HC-SR04 range? (2-400cm) 4) LDR principle? (Resistance โ 1/Light) 5) IR sensor output? (Digital HIGH/LOW)
Lab 6: RFID Module (RC522)
#include <SPI.h>
#include <MFRC522.h>
MFRC522 rfid(10, 9); // SS=10, RST=9
void setup() { Serial.begin(9600); SPI.begin(); rfid.PCD_Init(); Serial.println("Scan RFID card..."); }
void loop() {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) return;
Serial.print("UID: ");
for (byte i = 0; i < rfid.uid.size; i++) { Serial.print(rfid.uid.uidByte[i], HEX); Serial.print(" "); }
Serial.println();
rfid.PICC_HaltA();
}
Viva: 1) RFID frequency? (13.56 MHz) 2) SPI pins? (MOSI=11, MISO=12, SCK=13) 3) UID bytes? (4-7) 4) Active vs Passive tags? 5) Indian use? (FASTag, Metro)
Lab 7: DC Motors with L298N
int ENA=5, IN1=6, IN2=7;
void setup() { pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); }
void loop() {
// Forward
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENA, 200);
delay(2000);
// Reverse
digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENA, 200);
delay(2000);
// Stop
digitalWrite(IN1, LOW); digitalWrite(IN2, LOW);
delay(1000);
}
Viva: 1) L298N channels? (2) 2) Max current per channel? (2A) 3) H-bridge purpose? (Direction control) 4) ENA pin for? (Speed via PWM) 5) Why not connect motor directly? (Current limit)
Lab 8: Bluetooth and WiFi Interfacing
// Bluetooth HC-05: See Chapter 8 code // WiFi ESP8266: See Chapter 9 code // Combined: BT for local control, WiFi for remote dashboard
Viva: 1) HC-05 default baud? (9600) 2) ESP8266 voltage? (3.3V) 3) BT range? (~10m) 4) WiFi standard? (802.11 b/g/n) 5) SoftwareSerial purpose? (Extra UART)
Lab 9: Silicon Labs W7230F1 โ Simplicity Studio + LED Control
Steps:
- Download Simplicity Studio v5 from silabs.com/developers
- Install supported packages for W7230F1
- Connect EVB via USB, select board in IDE
- Create new C project โ Add GPIO driver
- Use GPIO_PinOutToggle() to blink onboard LED
- Build โ Flash โ Verify LED blinks
Viva: 1) Simplicity Studio based on? (Eclipse) 2) GPIO init function? (GPIO_PinModeSet) 3) Clock enable? (CMU_ClockEnable) 4) Push-pull vs open-drain? 5) Debug interface? (SWD/JTAG)
Lab 10: Silicon Labs Mobile Phone Control (Smart Home)
Steps:
- Configure BLE GATT service on W7230F1
- Create characteristic for LED ON/OFF command
- Use EFR Connect mobile app (Android/iOS) to discover device
- Send write command to toggle onboard LED
- Extend: Add relay module for AC appliance control
Viva: 1) BLE vs Classic BT? (Low power) 2) GATT? (Generic Attribute Profile) 3) Characteristic? (Data endpoint) 4) EFR Connect app by? (Silicon Labs) 5) Smart home protocol? (BLE/Zigbee/WiFi)
Appendices
Appendix A: Arduino Uno R3 Pin Reference
| Pin | Type | Function |
|---|---|---|
| D0 | Digital | RX (Serial receive) |
| D1 | Digital | TX (Serial transmit) |
| D2-D7 | Digital | General purpose I/O |
| D3,5,6,9,10,11 | PWM | analogWrite() capable (~) |
| D10-D13 | SPI | SS, MOSI, MISO, SCK |
| A0-A5 | Analog | 10-bit ADC (0-1023) |
| A4, A5 | I2C | SDA, SCL |
| VIN | Power | External supply (7-12V) |
| 5V, 3.3V | Power | Regulated output |
| GND | Power | Ground (3 pins) |
Appendix B: Common Libraries Quick Reference
| Library | Purpose | Key Functions |
|---|---|---|
| LiquidCrystal.h | 16x2 LCD | begin(), print(), setCursor() |
| Servo.h | Servo motor | attach(), write(), read() |
| DHT.h | DHT11/22 sensor | readTemperature(), readHumidity() |
| SPI.h | SPI protocol | begin(), transfer() |
| Wire.h | I2C protocol | begin(), requestFrom(), write() |
| SoftwareSerial.h | Extra UART | begin(), read(), print() |
| MFRC522.h | RFID RC522 | PCD_Init(), ReadCardSerial() |
| ESP8266WiFi.h | ESP8266 WiFi | begin(), localIP(), status() |
| MD_Parola.h | LED Matrix | begin(), displayText() |
Appendix C: Troubleshooting Guide
| Problem | Cause | Solution |
|---|---|---|
| COM port not detected | Driver missing | Install CH340/CP2102 driver |
| Upload failed | Wrong board/port | Check Tools โ Board and Port |
| Sensor reads NaN | Wiring or pull-up | Check connections, add 10K pull-up |
| Motor not spinning | Insufficient current | Use external power supply for motor driver |
| ESP8266 keeps resetting | 3.3V power insufficient | Use dedicated 3.3V regulator (AMS1117) |
| LCD shows blocks | Contrast not set | Adjust V0 potentiometer |
| Bluetooth not pairing | Wrong mode/PIN | Reset HC-05, use AT commands to configure |
Appendix D: IoT Project Ideas for Portfolio
| # | Project | Components | Difficulty |
|---|---|---|---|
| 1 | Smart Weather Station | DHT22 + LCD + ESP8266 + ThingSpeak | โญโญ |
| 2 | Home Automation (4 devices) | ESP8266 + 4-Relay + Web Server | โญโญโญ |
| 3 | RFID Attendance System | RC522 + LCD + SD Card + RTC | โญโญโญ |
| 4 | Smart Parking System | Ultrasonic + Servo + LCD + IR | โญโญ |
| 5 | Health Monitor Wearable | MAX30100 + OLED + BLE | โญโญโญโญ |
| 6 | Smart Agriculture System | Soil moisture + DHT22 + Relay + ESP8266 | โญโญโญ |
| 7 | GPS Vehicle Tracker | NEO-6M GPS + SIM800L + Arduino | โญโญโญโญ |
| 8 | Robot Car with App Control | L298N + 2 DC Motors + HC-05 + App | โญโญโญ |
โ Programming IoT: COMPLETE!
๐ Congratulations! You have completed all 10 chapters covering LCD, Sensors, Motors, RFID, Pulse Oximeter, Bluetooth, WiFi, IoT Cloud, and Futuristic Technologies.
๐ 200 MCQs solved | ๐ฌ 10 Lab Programs done | ๐ 4 Appendices referenced
๐ You are IoT-Ready & Hackathon-Ready!