Unit 2: Input devices with NodeMCU - Subjective Questions
ECE237 — Architecting Smart Iot Devices • Practice Questions with Detailed Answers
20 questions
Define the DHT11 sensor and explain how it can be interfaced with a NodeMCU.
DHT11 is a digital sensor used to measure temperature and relative humidity.
Interfacing with NodeMCU:
- Connect the DHT11 VCC pin to the NodeMCU 3.3 V pin.
- Connect GND to a NodeMCU ground pin.
- Connect the DATA pin to a digital GPIO pin such as D2 (GPIO4).
- When using a bare DHT11 sensor, connect a 4.7 kΩ to 10 kΩ pull-up resistor between VCC and DATA.
- Install a compatible DHT sensor library in the Arduino IDE.
- Initialize the sensor using its GPIO pin and sensor type.
- Read temperature and humidity at intervals of at least one to two seconds.
The sensor sends calibrated digital data, so the NodeMCU does not require an analog-to-digital conversion for these measurements.
Describe the steps required to program a NodeMCU to read temperature and humidity from a DHT11 sensor.
The programming procedure is as follows:
- Include the required DHT library using
#include <DHT.h>. - Define the GPIO pin connected to the sensor, for example
D2. - Define the sensor type as
DHT11. - Create a DHT object using the selected pin and type.
- Start serial communication in
setup()usingSerial.begin(115200). - Initialize the sensor by calling
dht.begin(). - In
loop(), calldht.readHumidity()anddht.readTemperature(). - Check whether the returned values are valid using
isnan(). - Display the readings on the Serial Monitor.
- Add a delay of about two seconds between measurements.
A validity check is important because communication errors may cause the library to return a Not-a-Number (NaN) value.
Write and explain a NodeMCU program that reads data from a DHT11 sensor and displays it on the Serial Monitor.
A suitable Arduino program is:
#include <DHT.h>
#define DHTPIN D2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT11");
delay(2000);
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" deg C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
delay(2000);
}
Explanation:
DHTPINidentifies the GPIO used for communication.DHTTYPEselects the correct sensor protocol.dht.begin()initializes the sensor.- The read functions return temperature and humidity as floating-point values.
isnan()detects failed measurements.- The delay prevents polling the relatively slow DHT11 too frequently.
Compare the DHT11 and DHT22 sensors with respect to range, accuracy, resolution, sampling rate, cost, and suitable applications.
Comparison of DHT11 and DHT22:
| Parameter | DHT11 | DHT22 |
|---|---|---|
| Temperature range | Approximately 0°C to 50°C | Approximately -40°C to 80°C |
| Temperature accuracy | About ±2°C | About ±0.5°C |
| Humidity range | Approximately 20% to 80% RH | Approximately 0% to 100% RH |
| Humidity accuracy | About ±5% RH | Typically ±2% to ±5% RH |
| Resolution | Lower | Higher |
| Sampling rate | About one reading per second | About one reading every two seconds |
| Cost | Lower | Higher |
Application selection:
- DHT11 is suitable for low-cost indoor projects, basic room monitoring, and educational prototypes.
- DHT22 is preferable for environmental monitoring, agriculture, weather stations, and applications requiring a wider range and better accuracy.
Although both use a similar single-wire digital interface, the correct sensor type must be specified in the program.
Explain the working principle of an ultrasonic distance sensor and its connection to a NodeMCU.
An ultrasonic sensor such as the HC-SR04 measures distance using the time-of-flight principle.
Working principle:
- The NodeMCU applies a short pulse to the TRIG pin.
- The sensor emits a burst of ultrasonic sound, usually at 40 kHz.
- The sound travels toward an object and is reflected.
- The ECHO pin remains HIGH for the round-trip travel time.
- The NodeMCU measures this pulse duration and calculates distance.
Connections:
- VCC connects to the supply required by the sensor, commonly 5 V for an HC-SR04.
- GND connects to the common ground.
- TRIG connects to a NodeMCU output GPIO.
- ECHO connects to a NodeMCU input GPIO through a voltage divider or level shifter.
The level shifter is important because a standard HC-SR04 can produce a 5 V ECHO signal, while ESP8266 GPIO pins operate at 3.3 V and are not 5 V tolerant.
Derive the formula used to calculate distance from the echo duration of an ultrasonic sensor.
Let the measured echo duration be and the speed of sound be .
During time , the ultrasonic wave travels from the sensor to the object and then returns to the sensor. Therefore, the measured path is twice the actual distance :
Hence,
Taking the speed of sound at room temperature as approximately :
If time is measured in microseconds and distance is required in centimetres, the commonly used approximation is:
Alternatively, since sound travels approximately :
Division by two is essential because the measured duration includes both the outward and return journeys.
Write and explain a NodeMCU program for measuring distance using an HC-SR04 ultrasonic sensor.
A basic program is:
#define TRIG_PIN D5
#define ECHO_PIN D6
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) {
Serial.println("No echo received");
} else {
float distance = duration * 0.0343 / 2.0;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
Explanation:
- A 10 µs trigger pulse starts the measurement.
pulseIn()measures the ECHO pulse width.- The timeout prevents the program from waiting indefinitely.
- The distance is calculated from the speed of sound.
- The ECHO connection must be reduced to a safe 3.3 V logic level before reaching the NodeMCU.
Discuss the major sources of error in ultrasonic distance measurement and explain how they can be reduced.
Major sources of error include:
- Temperature: The speed of sound changes with air temperature, affecting calculated distance.
- Object angle: A tilted surface may reflect sound away from the receiver.
- Soft materials: Cloth, foam, and similar materials absorb ultrasonic energy.
- Small targets: An object may be too small to produce a reliable echo.
- Electrical noise: Poor wiring or unstable power can create false measurements.
- Multiple reflections: Nearby surfaces may generate delayed or incorrect echoes.
- Minimum range: Objects inside the sensor's blind zone cannot be measured reliably.
Methods of improvement:
- Take several readings and use an average or median filter.
- Add a timeout to
pulseIn(). - Keep the target reasonably flat and perpendicular to the sensor.
- Maintain correct spacing between successive trigger pulses.
- Use short, secure wires and a common ground.
- Apply temperature compensation when higher accuracy is required.
- Reject readings outside the sensor's specified range.
Explain how an analog temperature sensor such as the LM35 can be interfaced and programmed with a NodeMCU.
The LM35 is an analog temperature sensor whose output voltage is proportional to temperature in degrees Celsius, typically at 10 mV per °C.
Interfacing procedure:
- Connect the sensor supply and ground according to the LM35 and development-board specifications.
- Connect the LM35 output to the NodeMCU A0 analog input.
- Ensure that the voltage reaching A0 does not exceed the permitted ADC input range of the particular NodeMCU board.
- Read the ADC value using
analogRead(A0). - Convert the ADC count into voltage using the ADC resolution and reference or full-scale input voltage.
- Convert voltage into temperature.
The general equations are:
Here, is the actual full-scale voltage accepted at A0. This value must be confirmed for the specific NodeMCU board because development boards may include an onboard voltage divider.
Write a NodeMCU program to read an LM35 temperature sensor through the analog input and explain the conversion process.
Assuming that the NodeMCU board's A0 pin has a 3.3 V full-scale input, an example program is:
const int sensorPin = A0;
const float adcFullScale = 3.3;
const float adcMaximum = 1023.0;
void setup() {
Serial.begin(115200);
}
void loop() {
int adcValue = analogRead(sensorPin);
float voltage = adcValue * adcFullScale / adcMaximum;
float temperatureC = voltage * 100.0;
Serial.print("ADC: ");
Serial.print(adcValue);
Serial.print(" Temperature: ");
Serial.print(temperatureC);
Serial.println(" deg C");
delay(1000);
}
Conversion:
- The ESP8266 ADC reading normally ranges from 0 to 1023.
- Voltage is calculated as for the stated assumption.
- Since the LM35 produces V per °C, temperature is .
The value adcFullScale must be changed to match the actual A0 input range of the board. The LM35 supply requirements must also be checked, since a standard LM35 may require more than 3.3 V for reliable operation.
Distinguish between analog and digital temperature sensors when used with a NodeMCU.
Analog temperature sensors:
- Produce a continuously varying voltage.
- Require the NodeMCU ADC input.
- Need conversion from ADC count to voltage and then temperature.
- Accuracy depends on ADC range, resolution, reference accuracy, and electrical noise.
- Examples include LM35 and thermistor-based circuits.
Digital temperature sensors:
- Send temperature as encoded digital data.
- Use protocols such as single-wire signaling, OneWire, I2C, or SPI.
- Usually include internal conversion and calibration.
- Are less affected by analog noise over short connections.
- Examples include DHT11, DHT22, DS18B20, and digital I2C sensors.
An analog sensor may offer simple and fast readings, whereas a digital sensor generally simplifies calibration and may provide better repeatability. Selection depends on accuracy, range, available pins, sampling speed, cost, and environmental conditions.
Describe the construction and working of a typical IR obstacle detection sensor module.
A typical IR obstacle sensor module contains:
- An infrared LED transmitter that emits infrared radiation.
- An IR photodiode or phototransistor receiver that detects reflected radiation.
- A comparator circuit, commonly based on an LM393.
- A potentiometer for adjusting detection sensitivity or threshold.
- A digital output pin and, on some modules, an analog output pin.
Working:
- The transmitter continuously emits infrared light.
- When an object is present, some of the radiation is reflected toward the receiver.
- The receiver produces a signal proportional to the reflected intensity.
- The comparator checks this signal against the threshold set by the potentiometer.
- The digital output changes state when the threshold is crossed.
Detection depends on object distance, surface colour, reflectivity, angle, ambient infrared light, and the selected threshold. Many modules provide an active-LOW output, but this must be verified for the specific module.
Write and explain a NodeMCU program that uses an IR sensor to detect an obstacle and control an LED.
Assuming an active-LOW IR module, the program is:
#define IR_PIN D5
#define LED_PIN D4
void setup() {
Serial.begin(115200);
pinMode(IR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
}
void loop() {
int sensorState = digitalRead(IR_PIN);
if (sensorState == LOW) {
digitalWrite(LED_PIN, HIGH);
Serial.println("Obstacle detected");
} else {
digitalWrite(LED_PIN, LOW);
Serial.println("No obstacle");
}
delay(100);
}
Explanation:
- The IR module's digital output is connected to
IR_PIN. digitalRead()obtains the current obstacle state.- For an active-LOW module, LOW means that reflected IR has crossed the detection threshold.
- The LED is switched on when an obstacle is detected.
- A short delay limits repeated messages and reduces rapid output changes.
If the module is active-HIGH or the selected board has an active-LOW onboard LED, the output logic must be adjusted.
Explain the limitations of an IR obstacle sensor and suggest methods to improve detection reliability.
Limitations:
- Dark or matte objects may absorb IR and produce weak reflections.
- Shiny or angled surfaces may reflect IR away from the receiver.
- Sunlight and incandescent lamps can introduce infrared interference.
- Detection distance varies with object size and surface properties.
- The module generally indicates presence only and does not provide accurate distance.
- Rapid threshold changes can cause output flickering.
Methods to improve reliability:
- Adjust the onboard potentiometer for the operating environment.
- Shield the receiver from direct sunlight.
- Mount the transmitter and receiver at a suitable angle.
- Confirm detection using multiple consecutive readings.
- Add software debouncing or a time threshold.
- Use analog output, when available, for more flexible threshold processing.
- Use modulated IR transmitters and matched receivers in high-interference environments.
- Choose ultrasonic or time-of-flight sensors when accurate distance measurement is required.
Define an LDR and explain how a voltage-divider circuit enables a NodeMCU to measure light intensity.
An LDR (Light Dependent Resistor) is a photoresistor whose resistance changes with incident light. Its resistance is generally high in darkness and decreases as light intensity increases.
Because the NodeMCU measures voltage rather than resistance directly, the LDR is connected as part of a voltage divider with a fixed resistor.
For an LDR connected to the supply and a fixed resistor connected to ground, with the midpoint connected to A0:
- In brighter light, decreases, so generally increases in this arrangement.
- In darkness, increases, so decreases.
If the LDR and fixed resistor positions are reversed, the direction of the ADC change is also reversed. The divider output must remain within the allowed voltage range of the NodeMCU A0 pin.
Write a NodeMCU program to read an LDR and automatically control a lamp or LED according to ambient light.
A threshold-based program is:
#define LDR_PIN A0
#define LED_PIN D5
const int darkThreshold = 400;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int lightValue = analogRead(LDR_PIN);
Serial.print("LDR value: ");
Serial.println(lightValue);
if (lightValue < darkThreshold) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
delay(200);
}
Explanation:
analogRead(A0)returns an ADC value representing the divider voltage.- The measured value is compared with a calibrated threshold.
- When the value represents darkness, the LED is switched on.
- In bright conditions, the LED is switched off.
This code assumes the ADC value decreases in darkness. If the divider is wired in the opposite orientation, the comparison must be reversed. A transistor or relay driver is required for controlling a high-power lamp; it must not be driven directly from a GPIO pin.
Explain how an LDR-based light sensing system can be calibrated for day and night detection.
Calibration procedure:
- Assemble the LDR voltage divider and verify that its maximum output does not exceed the A0 input limit.
- Record several ADC readings under bright daylight conditions.
- Record several readings under the darkest expected operating condition.
- Calculate representative bright and dark values using averages or medians.
- Choose a threshold between the two groups of readings.
- Test the threshold at intermediate light levels and adjust it if required.
- Use two thresholds to implement hysteresis, for example one threshold to switch on and another to switch off.
Importance of hysteresis:
- Without hysteresis, readings close to one threshold may cause rapid switching.
- If the lamp switches on below 350 and switches off above 450, small fluctuations between these values do not change the output.
Calibration must be performed in the actual installation environment because LDR readings depend on component tolerance, divider resistance, sensor placement, weather, shadows, and artificial lighting.
Describe the important electrical precautions that must be followed when connecting DHT, ultrasonic, temperature, IR, and LDR sensors to a NodeMCU.
Important precautions include:
- Keep all connected modules on a common ground.
- Do not apply a 5 V signal directly to ESP8266 GPIO pins, which use 3.3 V logic.
- Reduce the HC-SR04 ECHO signal with a voltage divider or logic-level converter.
- Verify whether an IR sensor module's output is safe for 3.3 V input.
- Keep the analog voltage at A0 within the full-scale range specified for the exact NodeMCU board.
- Use a pull-up resistor on the DATA pin of a bare DHT sensor.
- Check sensor supply-voltage requirements before connecting VCC.
- Use a transistor, MOSFET, relay module, or driver circuit for loads that require more current than a GPIO can supply.
- Avoid GPIO pins that affect ESP8266 boot mode unless their startup states are understood.
- Use short connections, stable power, and suitable decoupling capacitors to reduce noise and resets.
These precautions protect the NodeMCU and improve measurement reliability.
Compare the output and programming requirements of DHT11, ultrasonic, IR, analog temperature, and LDR sensors.
| Sensor | Output type | Main NodeMCU operation | Typical processing |
|---|---|---|---|
| DHT11 | Encoded digital data | Library-based GPIO communication | Decode temperature and humidity and check for NaN |
| Ultrasonic sensor | Trigger input and timed ECHO pulse | digitalWrite() and pulse timing |
Convert round-trip time into distance |
| IR obstacle module | Usually digital HIGH or LOW | digitalRead() |
Interpret threshold-based obstacle state |
| Analog temperature sensor | Analog voltage | analogRead(A0) |
Convert ADC value to voltage and temperature |
| LDR divider | Analog voltage | analogRead(A0) |
Compare light-dependent reading with calibrated thresholds |
Key differences:
- DHT11 provides already calibrated measurement data.
- The ultrasonic sensor requires precise pulse generation and time measurement.
- A digital IR module gives a binary result rather than accurate distance.
- Analog temperature and LDR circuits share the single ESP8266 ADC input and require correct voltage scaling.
- Each sensor requires a sampling interval appropriate to its physical and electrical behaviour.
Design a NodeMCU-based monitoring system using a DHT11, ultrasonic sensor, IR sensor, and LDR. Explain its operation and program structure.
A multi-sensor system can monitor environmental conditions, distance, object presence, and ambient light.
Possible connections:
- DHT11 DATA to a digital pin such as D2.
- Ultrasonic TRIG and level-shifted ECHO to two digital pins.
- IR module output to another digital input.
- LDR voltage-divider output to A0.
Program structure:
- Define all pins and include the DHT library.
- Initialize serial communication, DHT11, input pins, and output pins in
setup(). - Read DHT11 temperature and humidity at its supported interval.
- Generate the ultrasonic trigger pulse and measure ECHO duration with a timeout.
- Read the IR module as a digital obstacle state.
- Read the LDR through A0 and compare it with calibrated day/night thresholds.
- Validate readings before using or transmitting them.
- Display the results or publish them through Wi-Fi to an IoT platform.
Good design considerations:
- Use non-blocking timing with
millis()so slow DHT sampling does not prevent other sensor operations. - Use filtering for ultrasonic and LDR readings.
- Ensure 3.3 V logic compatibility and a common ground.
- Use a driver circuit for alarms, lamps, or motors.
- Assign pins carefully to avoid ESP8266 boot-mode problems.
Such a system could provide room-condition monitoring, automatic lighting, occupancy detection, and proximity alerts.
Define the DHT11 sensor and explain how it can be interfaced with a NodeMCU.
DHT11 is a digital sensor used to measure temperature and relative humidity.
Interfacing with NodeMCU:
- Connect the DHT11 VCC pin to the NodeMCU 3.3 V pin.
- Connect GND to a NodeMCU ground pin.
- Connect the DATA pin to a digital GPIO pin such as D2 (GPIO4).
- When using a bare DHT11 sensor, connect a 4.7 kΩ to 10 kΩ pull-up resistor between VCC and DATA.
- Install a compatible DHT sensor library in the Arduino IDE.
- Initialize the sensor using its GPIO pin and sensor type.
- Read temperature and humidity at intervals of at least one to two seconds.
The sensor sends calibrated digital data, so the NodeMCU does not require an analog-to-digital conversion for these measurements.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →