Embedded Systems

AVR C lab · pump simulation

Smart Environment Monitoring and Automatic Irrigation

An ATmega328P / AVR C lab integrating DHT11, soil moisture and LM35 sensing with a 16×2 LCD and 40% / 45% simulated irrigation control.

Actual breadboard prototype from report Figure 3: Arduino Uno, battery supply, LCD and sensor connections. This documents a lab build, not a deployed irrigation installation.

Chathuranga Polkotuwa

DT124A · Lab 6 · Kristianstad University, Sweden

Report cover: 10 June 2025 · AVR C lab

3

Sensor types

16 × 2

LCD display

40% / 45%

Switching thresholds

Lab prototype · simulated pump only. The manual describes mains-powered equipment, but no mains-safety or real irrigation validation was supplied. The uploaded code is an LED exercise, not the full monitor firmware.

Project purpose and evidence

This AVR C lab combines three sensor types and four environmental readings: DHT11 air temperature and humidity, analog soil moisture, and LM35 temperature. An Arduino Uno / ATmega328P processes the inputs, presents them on a 16×2 LCD and uses a relay to simulate automatic watering.

The report credits Polkotuwa Walawwe Chathuranga Bandara Polkotuwa. Its cover is dated 10 June 2025, while its authorship statement refers to work on 10 May 2025; these are source dates, not a newly established project timeline.

The lab report, seven-page user manual and original photos now support this case study. The two supplied C files are identical LED-blink programs, not the environmental-monitor firmware. No connected greenhouse, water-saving measurement or certified product is claimed.

Sensors and system architecture

ElementInterface / purposeEvidence boundary
DHT11Digital air temperature and humidityChecksum handling described in report; complete driver absent
Soil moistureAnalog input A0 / ADC0Percentage conversion requires sensor and soil calibration
LM35Analog input A1 / ADC1, nominal 10 mV/°CNo measured comparison against a reference thermometer
1602A LCDFour-bit parallel data interfaceFour data wires, plus RS and Enable; contrast potentiometer
Push buttonPolled, internal pull-up describedPress cycles DHT11 → soil → LM35
RelayActive-HIGH control describedSimulated pump; no real-load verification
Status LEDsNormal / warning feedbackColors and meanings differ across documents

The hardware list also includes 220 Ω LED resistors, a 10 kΩ LCD contrast potentiometer, breadboard and jumper wires. Microchip Studio compiles the AVR C application; the report describes upload using an AVR ISP programmer.

Pin-map conflict: page 10 assigns LCD data to PD0–PD3, DHT11 to PD2 and the button to PD3. It also assigns LCD RS to PD5 and Enable to PD6 while reusing PD5/PD6 for status LEDs. These shared assignments cannot be assumed to work as independent signals without additional circuitry or a documented multiplexing strategy. The verified final pin map and full firmware must resolve this before reproduction.

From measurements to a simulated output

  1. Inputs

    DHT11 digital frame · soil ADC0 · LM35 ADC1 · button

  2. ATmega328P

    Validate → display mode → moisture state

  3. Outputs

    16×2 LCD · LEDs · relay simulation

Source-derived functional chart, not verified pin wiring. This local AVR project has no documented Wi-Fi or cloud connection.
Report Figure 2: original illustrated circuit arrangement. The report’s written GPIO assignments contain conflicts; do not use this as verified wiring.

Acquisition and display step by step

  1. Initialize: configure GPIO direction, input pull-ups, ADC, relay output and the LCD; display the welcome message.
  2. Acquire: read the DHT11 digital frame or select an ADC channel for soil / LM35. The report describes ADMUX channel masking so unrelated configuration bits are preserved.
  3. Validate: reject a failed DHT11 checksum and give a visible fault indication. The complete implementation and disconnected-soil behavior are not supplied.
  4. Handle the button: confirm the press after the report’s 20 ms debounce delay and advance the display mode. Ensure one mode change per press-and-release, not repeated advances during a held button.
  5. Update the LCD: clear / refresh the selected sensor display. Blocking sensor reads, debounce delays and LCD clearing affect response time; no measured loop timing is available.
  6. Apply control: compare moisture against both thresholds and preserve relay state in the middle band. A robust integrated version should keep moisture control running regardless of the displayed sensor; the absent firmware prevents verifying this scheduling.

Teaching example of the report’s three-mode counter—not extracted original firmware:

mode = (mode + 1) % 3;
// 0: DHT11 temperature + humidity
// 1: soil moisture
// 2: LM35 temperature

For a teaching calculation only, a 10-bit ADC reading of 51 with an assumed 5.00 V reference gives:

V=511023×5.00≈0.249  VV = \frac{51}{1023} \times 5.00 \approx 0.249\;V

TLM35=0.2490.010≈24.9  ∘CT_{LM35} = \frac{0.249}{0.010} \approx 24.9\;^{\circ}C

Actual reference voltage, sensor offset and ADC quantization affect this result. Soil moisture cannot use this temperature formula; establish dry/wet reference readings for the particular probe and soil.

Report Figure 4 shows the soil-moisture display at 55%. A single historical reading is not a calibration or accuracy measurement.
Report Figure 5 documents the temperature display mode on the same breadboard setup.

Moisture hysteresis and simulated watering

Both documents specify ON below 40% and OFF above 45%. In the inclusive 40–45% band, retain the previous state. This avoids switching repeatedly around one noisy threshold; it does not prove a measured improvement in pump lifetime.

The following AVR-style logic is a teaching reconstruction, not code from either uploaded main file:

if (moisture_percent < 40) {
    pump_on = 1;
} else if (moisture_percent > 45) {
    pump_on = 0;
}
// At 40 through 45 inclusive, do not change pump_on.
// Apply the state only to a verified low-voltage test output.

Example sequence: 50% → OFF; 39% → ON; 42% → stays ON; 46% → OFF; 42% → stays OFF. The repeated 42% reading produces different outputs depending on history: that is hysteresis, not an error. The initial state and fault response must be specified before hardware use.

Hysteresis · teaching simulation

Below 40%

Switch ON

40% through 45%

Keep previous state

Above 45%

Switch OFF

Simulated pump: OFF

Starts at 50% with the simulated output OFF. Browser-only state; does not operate hardware or establish firmware startup behavior.

Uploaded C code explained

main.c and main-2.c have identical contents. Both toggle PD5 every 500 ms. They contain no ADC, DHT11, LCD, button, relay, moisture scaling or hysteresis routines. The report’s full monitoring application therefore remains unavailable.

Original uploaded code, unchanged:

#define F_CPU 16000000UL  // Define clock speed as 16 MHz
#include <avr/io.h>       // Include AVR register definitions
#include <util/delay.h>   // Include delay functions

int main(void)
{
    // Set PD5 (Pin 11 on ATmega328PB) as output
    DDRD |= (1 << PD5);

    while (1)
    {
        // Toggle PD5 (turn LED on/off)
        PORTD ^= (1 << PD5);

        // Wait for 500 milliseconds
        _delay_ms(500);
    }
}
  1. F_CPU: 16,000,000 Hz informs the delay calculation. It does not configure clock fuses or make hardware run at 16 MHz.
  2. Headers: avr/io.h exposes device registers; util/delay.h provides the blocking delay. Select the actual MCU and correct clock in the toolchain.
  3. Direction: 1 shifted left by PD5 produces binary 00100000. OR assigns the DDRD bit without clearing other direction bits; PD5 becomes an output.
  4. Toggle: XOR flips only PORTD bit 5. For example, 00000000 → 00100000 → 00000000. Other PORTD bits remain unchanged.
  5. Delay and repeat: each transition is followed by 500 ms of blocking delay. Two transitions form a nominal 1 s cycle: 1 Hz, 50% duty cycle, after startup under the assumed clock.

Pin-number caution: the uploaded comment names ATmega328PB physical pin 11. The lab project instead names ATmega328P / Arduino Uno. On an Uno, PD5 corresponds to digital D5, not Arduino digital D11. Physical package numbering depends on the device/package and must be checked. Do not connect an LED without a current-limiting resistor; LED polarity determines whether HIGH appears illuminated.

This standalone exercise introduces the same register-level ideas used in the larger project, but it must not be flashed as a replacement monitor application.

PD5 toggle timing · idealized example

HIGH

0–500 ms

LOW

500–1000 ms

HIGH

1000–1500 ms

LOW

1500–2000 ms

Illustrative waveform assuming initial PORTD bit 5 is LOW and an actual 16 MHz clock. Nominal period 1000 ms, frequency 1 Hz and 50% duty cycle; not an oscilloscope measurement.

Reported tests and limitations

The report’s Table 2 marks all eight functional cases Pass. These are author-reported outcomes, not newly reproduced tests or a statistical reliability score.

TestDocumented conditionReported outcome
StartupApply power; welcome message and normal indicationPass
Button switchingPress once; next display modePass
All modesRepeated presses cycle DHT11 / soil / LM35Pass
DHT11Connected valid sensor; temperature and humidity visiblePass
Soil readingSimulated dry / wet inputs; percentage changesPass
LM35Temperature stimulus; display changesPass
Relay ONSimulated moisture below 40%; output HIGHPass
Relay OFFSimulated moisture above 45%; output LOWPass

No time-series dataset, calibration curve, water usage comparison, mains-load test or measured power consumption was provided. The manual’s water-saving language is a design intention, not a quantified result.

Source differences: the report alternates green / blue for the normal LED, with red indicating sensor errors. The manual associates blue with pump stopped and red with low moisture / pump started. Those are not identical meanings. The original flowchart also omits an explicit >45% OFF branch and ends at END despite the continuous-loop description. These documents are retained as evidence rather than silently corrected.

Report Figure 1, preserved as supplied. Its END node and branching do not fully express the described continuous loop or both hysteresis thresholds.

Safe use and troubleshooting

Use an isolated low-voltage supply and an LED or safe simulated load for student experiments. The manual describes a 230 V pump, built-in AC-to-5 V conversion and a 10 A limit; none of those statements establishes enclosure, insulation, isolation, fuse, earthing or pump inrush safety. They are not a verified safe operating rating. Mains connection and any real pump installation require competent qualified assessment; no mains-wiring tutorial is provided here.

SymptomSafe first check
Blank LCDIsolated low-voltage supply, contrast potentiometer and verified LCD pin map
Display does not changeButton pull-up, one press/release and debounce handling
Warning LEDCheck sensor connection and validity; resolve the documented LED-role difference
Relay output unchangedSimulate 39% and 46%, verify state logic and low-voltage output polarity
Unstable soil readingsInspect probe corrosion, connectors and calibration references

Keep electronics dry, separate probes from exposed contacts, and disconnect power before adjustments. The manual recommends cleaning the probe, checking connections and keeping the enclosure dry and away from children. Its product-style enclosure drawings remain concepts, not proof of an assembled certified device.

Illustration from the user manual, not a photograph of a verified enclosed product or a mains-safety approval.

Learning outcomes and next steps

This project demonstrates direct AVR register programming, mixed analog/digital sensing, four-bit LCD communication, a three-state user interface and stateful control with hysteresis. The most useful engineering lesson is that readable documentation must agree with the actual firmware and wiring.

To make the work reproducible, add the complete monitor firmware, definitive non-conflicting GPIO map, actual ADC reference, dry/wet soil calibration method, sensor-fault policy, initial relay state and dated test logs. Future improvements can replace blocking operations with scheduled acquisition and avoid full-screen LCD refreshes, but these are proposed extensions—not features verified in the uploaded code.

Original report references include course materials, lab discussions, Tinkercad circuit drawing, AlgoBuild flowchart tooling and the ATmega328P datasheet. The promised code-explanation video has no supplied URL, so no video link is invented.

Original project materials

Read the original 16-page report and seven-page manual, including the discrepancies described above. The identical uploaded LED programs are reproduced in the code explanation.

All projects