Arduino Colour Sorting Machine with TCS3200, Servo Chute, IR Feeder Check & 16×2 LCD Counter

Connection diagram of the Arduino Uno colour sorting machine with TCS3200 colour sensor, feeder and chute servos, IR sensor, buttons, buzzer and 16x2 I2C LCD

Build an Arduino Uno colour sorting machine that feeds objects one by one, reads their colour with a TCS3200 sensor, turns a servo chute to the right bin and counts every colour on a 16×2 LCD, with a learn mode and EEPROM memory.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUArduino Uno (ATmega328P)
  • Parts12 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Sorting things by colour is a real job in factories: sweets, plastic pellets, pharmacy capsules, beads and even recycled bottle caps are sorted by machines that look at each piece and push it into the right bin. This Arduino colour sorting machine is a desktop version of that idea. You pour objects into a tube, and the machine takes them one at a time, checks the colour, and drops each one into its own cup while the LCD keeps count.

It is a complete combination project: a TCS3200 colour sensor, two servo motors working in sequence, an IR sensor that knows when the tube is empty, two buttons, a buzzer and a 16×2 I2C LCD, all controlled by one ATmega328P. You will learn how a colour sensor turns light into frequency, how to calibrate a sensor with white and black references, nearest-colour matching, smooth servo motion and saving data in EEPROM.

Connection diagram of the Arduino Uno colour sorting machine with TCS3200 colour sensor, feeder and chute servos, IR sensor, buttons, buzzer and 16x2 I2C LCD

How It Works

  • Feeding: the top servo turns a disc with one hole in it. At 165° the hole sits under the feed tube and one object falls in. The disc then turns slowly to 95°, which carries the object under the colour sensor.
  • Presence check: an IR obstacle sensor looks into the hole at the sensing position. If nothing is there, the tube is empty: the machine beeps, shows Tube empty? and pauses until you refill it and press START.
  • Reading the colour: the TCS3200 has an 8×8 grid of photodiodes with red, green, blue and clear filters. Pins S2 and S3 select the filter, and the OUT pin gives a square wave whose frequency rises with the amount of light. The Arduino measures the period of that wave with pulseIn() for each filter, averaging 8 readings.
  • Normalising: raw periods depend on distance and lighting, so the sketch maps each one between your black-card and white-card readings to a value from 0 to 255. This makes the numbers stable and easy to compare.
  • Matching: the reading is compared with six learned reference colours (red, orange, yellow, green, blue and brown) using the sum of the R, G and B differences. The closest colour wins. If even the closest one is more than 60 points away, the object goes to the reject bin.
  • Sorting: the bottom servo turns the chute to the angle for that colour (20° to 170°, seven positions), then the feeder disc turns to 30° and the object drops down the chute into its cup.
  • Counting and memory: each bin has a counter shown on the LCD and printed on the Serial Monitor. Counters and the learned colours are saved in EEPROM, so they are still there after power-off. A long press (2 s) on START resets the counters.

Components Required

  • Arduino Uno R3 or Nano (ATmega328P, 16 MHz) – 1
  • TCS3200 / TCS230 colour sensor module (with 4 white LEDs) – 1
  • SG90 micro servo for the feeder disc – 1
  • MG90S metal-gear servo for the chute – 1
  • IR obstacle sensor module (FC-51 or similar) – 1
  • 16×2 LCD with I2C backpack (PCF8574, address 0x27 or 0x3F) – 1
  • 5 V active buzzer – 1
  • 12 mm tactile push buttons (START and LEARN) – 2
  • 5 V 2 A power supply or LM2596 buck converter for the servos – 1
  • 470 µF 16 V electrolytic capacitor (across the servo supply) – 1
  • Breadboard or perfboard, jumper wires and a white/black calibration card – 1 set
  • Frame: 3 mm MDF, acrylic or 3D-printed parts, a 12 mm feed tube and 7 small cups – 1 set

Wiring Table

Module / pinArduino Uno pinNotes
TCS3200 VCC / GND5V / GNDModule also powers its 4 white LEDs
TCS3200 S0D4HIGH together with S1 LOW = 20 % output scaling
TCS3200 S1D5LOW
TCS3200 S2D6Filter select
TCS3200 S3D7Filter select
TCS3200 OUTD8Square-wave output measured with pulseIn()
TCS3200 OEGNDOutput enable (active LOW); some modules tie it already
Feeder servo SG90 signalD9Red to external 5 V, brown to common GND
Chute servo MG90S signalD10Red to external 5 V, brown to common GND
IR sensor OUTD11VCC 5V, GND; output LOW when an object is in front
START buttonD2Other leg to GND, internal pull-up
LEARN buttonD12Other leg to GND, internal pull-up
Active buzzer +D3Buzzer – to GND (use a buzzer under 30 mA)
LCD I2C SDA / SCLA4 / A5VCC 5V, GND
External 5 V 2 A supply (–)GNDMust be joined to the Arduino GND

Pin check: D9 and D10 both work for servos because the Servo library uses Timer1 on the Uno. That also disables analogWrite() on D9 and D10, which this project does not need. The on-board LED on D13 lights while the machine is running.

Connection Diagram

The diagram above shows how the modules connect to the Arduino and how an object moves through the machine. The drawing below lists every pin exactly as used in the code.

Arduino Colour Sorting Machine – Pin-Accurate Wiring Arduino Uno D2 START button → GND (internal pull-up) D3 Active buzzer (+), buzzer (–) → GND D4 TCS3200 S0 (frequency scale) D5 TCS3200 S1 D6 TCS3200 S2 (filter select) D7 TCS3200 S3 D8 TCS3200 OUT (square wave); OE → GND D9 Feeder servo SG90 signal (orange wire) D10 Chute servo MG90S signal (orange wire) D11 IR obstacle sensor OUT (LOW = object) D12 LEARN button → GND (internal pull-up) A4 / A5 LCD I2C SDA / SCL 5V VCC of TCS3200, IR sensor and LCD only GND Common GND: Uno, sensors, LCD AND servo supply (–) External 5 V 2 A supply (+) → red wire of both servos (–) → servo brown wires + Uno GND 470 µF across (+) and (–) Never power the two servos from the Uno 5V pin: the current spikes reset the board and spoil colour readings. Mount the TCS3200 about 10–15 mm above the feeder hole and shade it from room light with a black tube or box.
Pin-accurate connection diagram for the Arduino colour sorting machine.

Building the Mechanism

  • Feed tube: a 12–15 mm plastic tube or a rolled card tube, a little wider than your objects. Fix it vertically above the feeder disc.
  • Feeder disc: a 50 mm round disc (MDF, acrylic or 3D print) with one hole slightly bigger than one object, screwed to the SG90 horn. Under the disc, a fixed base plate has no hole except at the drop position (30°), so the object rides in the hole until it reaches the chute.
  • Sensor window: mount the TCS3200 looking down on the hole at 95°, 10–15 mm above it, inside a small black shroud so room light does not change the reading. Put the IR sensor at the side of the same position.
  • Chute: a 120 mm half pipe (cut PVC pipe or folded card) glued to the MG90S horn. Arrange 7 cups in a half circle under the end of the chute.
  • Tune the angles: adjust FEED_LOAD, FEED_SENSE, FEED_DROP and CHUTE_ANGLE[] at the top of the sketch to match your build.

Code

Install LiquidCrystal I2C (by Frank de Brabander) from the Library Manager. Servo, Wire and EEPROM come with the Arduino IDE. Select Arduino Uno (or Nano, ATmega328P) and upload. The sketch was compile-checked for the Uno: about 11 KB of flash and 870 bytes of RAM.

/*
  Arduino Colour Sorting Machine
  TCS3200 colour sensor + 2 servos + 16x2 I2C LCD + IR presence sensor + buzzer
  Board: Arduino Uno / Nano (ATmega328P, 16 MHz)
  Arduino Project Hub - ardiunoprojecthub.online - Project #68

  How it works:
   1. The feeder servo picks one object (bead, candy, small block) from the tube
      and carries it under the TCS3200 colour sensor.
   2. The sensor measures red, green, blue and clear light. The sketch compares
      the reading with six learned reference colours (nearest match).
   3. The chute servo turns to the bin for that colour, the feeder drops the
      object, and the LCD shows the colour and the count for each bin.
   4. Counts and learned colours are kept in EEPROM, so they survive power-off.

  Buttons (to GND, internal pull-ups):
   START (D2)  : short press = run / pause, long press (2 s) = reset counters
   LEARN (D12) : hold while powering up = learn mode (teach the 6 colours)
*/

#include <Wire.h>
#include <Servo.h>
#include <EEPROM.h>
#include <LiquidCrystal_I2C.h>

// ---------------- Pin map ----------------
const uint8_t PIN_START  = 2;   // start / pause button
const uint8_t PIN_BUZZER = 3;   // active buzzer (+)
const uint8_t PIN_S0     = 4;   // TCS3200 frequency scaling
const uint8_t PIN_S1     = 5;
const uint8_t PIN_S2     = 6;   // TCS3200 photodiode filter select
const uint8_t PIN_S3     = 7;
const uint8_t PIN_OUT    = 8;   // TCS3200 square-wave output
const uint8_t PIN_FEED   = 9;   // feeder (top) servo signal
const uint8_t PIN_CHUTE  = 10;  // chute (bottom) servo signal
const uint8_t PIN_IR     = 11;  // IR obstacle sensor OUT (LOW = object present)
const uint8_t PIN_LEARN  = 12;  // learn button
const uint8_t PIN_LED    = 13;  // status LED (on-board)

// ---------------- Mechanics (tune for your build) ----------------
const uint8_t FEED_LOAD   = 165;  // feeder hole under the tube
const uint8_t FEED_SENSE  = 95;   // feeder hole under the colour sensor
const uint8_t FEED_DROP   = 30;   // feeder hole over the chute
const uint8_t CHUTE_ANGLE[7] = {20, 45, 70, 95, 120, 145, 170}; // 6 colours + reject bin

// ---------------- Colour table ----------------
const uint8_t NUM_COLOURS = 6;
const char* const COLOUR_NAME[7] = {"Red", "Orange", "Yellow", "Green", "Blue", "Brown", "Reject"};
const uint8_t REJECT = 6;
const uint16_t MATCH_LIMIT = 60;   // larger distance than this = unknown colour

struct Rgb { uint16_t r, g, b; };  // normalised values 0..255 (higher = more of that colour)

// Typical defaults for a TCS3200 at 20% scaling, ~15 mm above the object.
// Run learn mode once for best results with your own lighting and objects.
Rgb ref[NUM_COLOURS] = {
  {190,  60,  70}, {200, 110,  60}, {200, 185,  80},
  { 80, 170,  90}, { 60, 110, 200}, {120,  90,  80}
};

uint16_t binCount[7] = {0};

// ---------------- EEPROM layout ----------------
const uint16_t EE_MAGIC_ADDR = 0;     // 2 bytes
const uint16_t EE_REF_ADDR   = 2;     // 6 x 6 bytes
const uint16_t EE_COUNT_ADDR = 40;    // 7 x 2 bytes
const uint16_t EE_MAGIC      = 0xC068;

LiquidCrystal_I2C lcd(0x27, 16, 2);   // change to 0x3F if your LCD stays blank
Servo feeder, chute;

bool running = false;
uint16_t whiteRef[3] = {0, 0, 0};     // period (us) under white card, for normalising
uint16_t blackRef[3] = {0, 0, 0};     // period (us) under black card

// ---------------- Helpers ----------------
void beep(uint16_t ms) {
  digitalWrite(PIN_BUZZER, HIGH);
  delay(ms);
  digitalWrite(PIN_BUZZER, LOW);
}

void lcdLine(uint8_t row, const char* text) {
  lcd.setCursor(0, row);
  uint8_t n = 0;
  while (text[n] && n < 16) { lcd.write(text[n]); n++; }
  while (n < 16) { lcd.write(' '); n++; }    // clear the rest of the row
}

// Wait for a button press and its release (with debounce). Returns press time in ms.
uint32_t waitPress(uint8_t pin) {
  while (digitalRead(pin) == HIGH) {}
  delay(25);
  uint32_t t0 = millis();
  while (digitalRead(pin) == LOW) {}
  delay(25);
  return millis() - t0;
}

// Move a servo slowly so the object does not jump out of the feeder hole.
void moveSlow(Servo &s, uint8_t target) {
  int pos = s.read();
  int step = (target > pos) ? 1 : -1;
  while (pos != target) {
    pos += step;
    s.write(pos);
    delay(6);
  }
}

// Read one filter channel: average period of the OUT square wave in microseconds.
// Lower period = more light of that colour.
uint16_t readPeriod(bool s2, bool s3) {
  digitalWrite(PIN_S2, s2);
  digitalWrite(PIN_S3, s3);
  delay(5);                                  // let the filter settle
  uint32_t sum = 0;
  uint8_t ok = 0;
  for (uint8_t i = 0; i < 8; i++) {
    uint32_t p = pulseIn(PIN_OUT, LOW, 20000UL);
    if (p > 0) { sum += p; ok++; }
  }
  if (ok == 0) return 0xFFFF;               // no signal: sensor not wired or too dark
  return (uint16_t)(sum / ok);
}

// Raw periods for red, green and blue filters
void readRaw(uint16_t raw[3]) {
  raw[0] = readPeriod(LOW, LOW);      // red filter
  raw[1] = readPeriod(HIGH, HIGH);    // green filter
  raw[2] = readPeriod(LOW, HIGH);     // blue filter
}

// Convert periods to 0..255 using the black and white calibration
Rgb readColour() {
  uint16_t raw[3];
  readRaw(raw);
  uint16_t v[3];
  for (uint8_t i = 0; i < 3; i++) {
    long x = map((long)raw[i], (long)blackRef[i], (long)whiteRef[i], 0L, 255L);
    v[i] = (uint16_t)constrain(x, 0L, 255L);
  }
  Rgb c = {v[0], v[1], v[2]};
  return c;
}

// Nearest reference colour (Manhattan distance). Returns REJECT if nothing is close.
uint8_t classify(const Rgb &c, uint16_t &bestDist) {
  uint8_t best = REJECT;
  bestDist = 0xFFFF;
  for (uint8_t i = 0; i < NUM_COLOURS; i++) {
    uint16_t d = abs((int)c.r - (int)ref[i].r) +
                 abs((int)c.g - (int)ref[i].g) +
                 abs((int)c.b - (int)ref[i].b);
    if (d < bestDist) { bestDist = d; best = i; }
  }
  if (bestDist > MATCH_LIMIT) best = REJECT;
  return best;
}

// ---------------- EEPROM ----------------
void saveCounts() {
  for (uint8_t i = 0; i < 7; i++) EEPROM.put(EE_COUNT_ADDR + i * 2, binCount[i]);
}

void saveRefs() {
  EEPROM.put(EE_MAGIC_ADDR, EE_MAGIC);
  for (uint8_t i = 0; i < NUM_COLOURS; i++) EEPROM.put(EE_REF_ADDR + i * 6, ref[i]);
  // black/white calibration stored after the colour table
  EEPROM.put(EE_REF_ADDR + 36 + 16, whiteRef);
  EEPROM.put(EE_REF_ADDR + 36 + 22, blackRef);
}

bool loadEeprom() {
  uint16_t magic;
  EEPROM.get(EE_MAGIC_ADDR, magic);
  if (magic != EE_MAGIC) return false;
  for (uint8_t i = 0; i < NUM_COLOURS; i++) EEPROM.get(EE_REF_ADDR + i * 6, ref[i]);
  for (uint8_t i = 0; i < 7; i++) {
    EEPROM.get(EE_COUNT_ADDR + i * 2, binCount[i]);
    if (binCount[i] == 0xFFFF) binCount[i] = 0;
  }
  EEPROM.get(EE_REF_ADDR + 36 + 16, whiteRef);
  EEPROM.get(EE_REF_ADDR + 36 + 22, blackRef);
  return true;
}

// ---------------- Learn mode ----------------
// Step 1: white card, step 2: black card, steps 3..8: one sample of each colour.
void learnMode() {
  char buf[17];
  moveSlow(feeder, FEED_SENSE);

  lcdLine(0, "LEARN: put WHITE");
  lcdLine(1, "card, press LRN");
  waitPress(PIN_LEARN);
  readRaw(whiteRef);
  beep(60);

  lcdLine(0, "LEARN: put BLACK");
  lcdLine(1, "card, press LRN");
  waitPress(PIN_LEARN);
  readRaw(blackRef);
  beep(60);

  for (uint8_t i = 0; i < NUM_COLOURS; i++) {
    snprintf(buf, sizeof(buf), "LEARN: %s", COLOUR_NAME[i]);
    lcdLine(0, buf);
    lcdLine(1, "place, press LRN");
    waitPress(PIN_LEARN);
    // average three readings for a stable reference
    uint32_t r = 0, g = 0, b = 0;
    for (uint8_t k = 0; k < 3; k++) {
      Rgb c = readColour();
      r += c.r; g += c.g; b += c.b;
    }
    ref[i].r = r / 3; ref[i].g = g / 3; ref[i].b = b / 3;
    snprintf(buf, sizeof(buf), "R%3u G%3u B%3u", ref[i].r, ref[i].g, ref[i].b);
    lcdLine(1, buf);
    beep(60);
    delay(800);
  }
  saveRefs();
  lcdLine(0, "Colours saved!");
  lcdLine(1, "Press START");
  beep(200);
}

// ---------------- Display ----------------
void showIdle() {
  char buf[17];
  uint16_t total = 0;
  for (uint8_t i = 0; i < 7; i++) total += binCount[i];
  lcdLine(0, running ? "RUNNING" : "PAUSED - START");
  snprintf(buf, sizeof(buf), "Total sorted %u", total);
  lcdLine(1, buf);
}

// ---------------- Sort one object ----------------
void sortOne() {
  char buf[17];

  // 1. pick up an object from the tube
  moveSlow(feeder, FEED_LOAD);
  delay(400);

  // 2. carry it under the sensor
  moveSlow(feeder, FEED_SENSE);
  delay(300);

  // 3. is there really an object? (IR sensor looks into the feeder hole)
  if (digitalRead(PIN_IR) == HIGH) {
    lcdLine(0, "Tube empty?");
    lcdLine(1, "Refill & START");
    beep(400);
    running = false;
    return;
  }

  // 4. read and classify the colour
  Rgb c = readColour();
  uint16_t dist;
  uint8_t bin = classify(c, dist);

  snprintf(buf, sizeof(buf), "%-7s d=%u", COLOUR_NAME[bin], dist);
  lcdLine(0, buf);
  snprintf(buf, sizeof(buf), "R%3u G%3u B%3u", c.r, c.g, c.b);
  lcdLine(1, buf);

  Serial.print(F("RGB "));
  Serial.print(c.r); Serial.print(' ');
  Serial.print(c.g); Serial.print(' ');
  Serial.print(c.b);
  Serial.print(F(" -> "));
  Serial.println(COLOUR_NAME[bin]);

  // 5. turn the chute, then drop the object
  moveSlow(chute, CHUTE_ANGLE[bin]);
  delay(150);
  moveSlow(feeder, FEED_DROP);
  delay(350);

  binCount[bin]++;
  saveCounts();                // EEPROM.put only writes bytes that changed
  if (bin == REJECT) beep(150);

  snprintf(buf, sizeof(buf), "%s bin: %u", COLOUR_NAME[bin], binCount[bin]);
  lcdLine(1, buf);
}

// ---------------- Setup / loop ----------------
void setup() {
  Serial.begin(9600);
  pinMode(PIN_START, INPUT_PULLUP);
  pinMode(PIN_LEARN, INPUT_PULLUP);
  pinMode(PIN_IR, INPUT);
  pinMode(PIN_BUZZER, OUTPUT);
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_S0, OUTPUT); pinMode(PIN_S1, OUTPUT);
  pinMode(PIN_S2, OUTPUT); pinMode(PIN_S3, OUTPUT);
  pinMode(PIN_OUT, INPUT);
  digitalWrite(PIN_S0, HIGH);  // 20% output frequency scaling (S0=H, S1=L)
  digitalWrite(PIN_S1, LOW);

  lcd.init();
  lcd.backlight();

  feeder.attach(PIN_FEED);
  chute.attach(PIN_CHUTE);
  feeder.write(FEED_SENSE);
  chute.write(CHUTE_ANGLE[3]);

  bool haveData = loadEeprom();
  if (!haveData) {
    // first power-up: sensible default periods (white ~ 40 us, black ~ 400 us)
    for (uint8_t i = 0; i < 3; i++) { whiteRef[i] = 40; blackRef[i] = 400; }
    for (uint8_t i = 0; i < 7; i++) binCount[i] = 0;
    saveRefs();            // write defaults so counts are kept from now on
    saveCounts();
  }

  lcdLine(0, "Colour Sorter");
  lcdLine(1, haveData ? "Data loaded" : "Defaults - LEARN");
  beep(80);
  delay(1200);

  if (digitalRead(PIN_LEARN) == LOW) {   // LEARN held at power-up
    while (digitalRead(PIN_LEARN) == LOW) {}
    delay(50);
    learnMode();
  }
  showIdle();
}

void loop() {
  // START button: short press toggles run/pause, long press resets the counters
  if (digitalRead(PIN_START) == LOW) {
    uint32_t held = waitPress(PIN_START);
    if (held > 2000) {
      for (uint8_t i = 0; i < 7; i++) binCount[i] = 0;
      saveCounts();
      running = false;
      lcdLine(0, "Counters reset");
      beep(300);
      delay(1000);
    } else {
      running = !running;
      beep(40);
    }
    showIdle();
  }

  digitalWrite(PIN_LED, running);
  if (running) {
    sortOne();
    if (!running) showIdle();
  }
}

Calibration and Testing

  • Learn mode: hold the LEARN button while you power up (or press reset), then release it. The LCD asks for a white card, then a black card, then one sample of each of the six colours. Place each one in the feeder hole under the sensor and press LEARN. The values are saved in EEPROM.
  • Check readings: open the Serial Monitor at 9600 baud. Each sorted object prints a line like RGB 192 64 71 -> Red. If two colours give very similar numbers (for example orange and brown), run learn mode again with better shading.
  • Run: press START to begin. The LED on D13 lights and the machine sorts about one object every 2–3 seconds. Press START again to pause; hold it for 2 seconds to reset the counters.
  • Tune the reject limit: raise MATCH_LIMIT if too many good objects go to reject, lower it if wrong colours slip into a bin.

Troubleshooting

ProblemFix
LCD backlight is on but no textTurn the blue contrast pot on the I2C backpack. If still blank, change the address in the sketch from 0x27 to 0x3F.
Arduino resets when the servos moveThe servos are drawing current from the Uno. Power them from a separate 5 V 2 A supply, join the grounds and add the 470 µF capacitor.
All readings are 0 or 255OUT is not reaching D8 or OE is not tied to GND. Check S0 to S3 wiring and that the four white LEDs on the module are lit.
Colour changes with room lightShade the sensor with a black tube or box and run learn mode again in the same lighting.
Every object goes to rejectLearn mode was skipped and the defaults do not match your objects. Hold LEARN at power-up and teach all six colours.
Machine says Tube empty? with objects presentAdjust the IR sensor’s blue trim pot until its LED turns on only when an object is in the hole. Matt black objects may need the sensor moved closer.
Objects jam between disc and baseMake the hole 1–2 mm bigger than the object and sand the edges. The slow servo movement in the code also helps.
Chute misses the cupsChange the values in CHUTE_ANGLE[] in 5° steps until each object lands in the middle of its cup.

Ideas to Extend

  • Add an HC-05 Bluetooth module to send the counts to a phone.
  • Replace the SG90 feeder with a small stepper motor for faster, more precise feeding.
  • Add a seventh learned colour (purple or white) by using the reject position as a real bin.

ATmega16 Fire & Gas Safety System with MQ-2, Flame Sensor, LCD & Exhaust Fan

ATmega16 fire and gas safety system on a breadboard with MQ-2 gas sensor, flame sensor, LM35, 16x2 LCD showing SAFE, 2-channel relay with exhaust fan, buzzer, red and green LEDs and push button

Build an ATmega16 fire and gas safety system that watches an MQ-2 gas/smoke sensor, an IR flame sensor and an LM35 temperature sensor, shows the status on a 16×2 LCD, switches on an exhaust fan, closes a gas valve relay and sounds a latched alarm.

  • DifficultyAdvanced
  • Build time5–6 hours
  • Board / MCUATmega16 (8 MHz internal)
  • Parts15 items
  • CodeEmbedded C (AVR-GCC)

Need it ready-made? Buy Ready Project

This ATmega16 fire and gas safety system is a complete kitchen and workshop safety controller built around one 40-pin AVR chip. It watches three sensors at the same time: an MQ-2 module for LPG, smoke and other combustible gases, an IR flame sensor that sees an open flame, and an LM35 for room temperature. A 16×2 LCD shows the live gas level, temperature and system state, while a 2-channel relay module drives an exhaust fan and a gas solenoid valve (or a mains cut-off contactor).

When gas starts to build up, the fan switches on automatically and the buzzer gives a slow warning beep. If there is a flame, heavy gas or smoke, or a very high temperature, the system goes into a latched ALARM: the fan runs, the valve relay closes the gas supply, the red LED flashes and the buzzer sounds fast. The alarm stays on until the danger is gone and someone presses the RESET button, just like a real fire panel. It is a big combination project that teaches multi-channel ADC, sensor calibration, state machines, relay control and 4-bit LCD driving in plain AVR C.

Safety note: this is a learning project, not a certified gas or fire detector. Keep a certified smoke and LPG alarm installed, and let a qualified electrician do any 230V mains wiring.

ATmega16 fire and gas safety system on a breadboard with MQ-2 gas sensor, flame sensor, LM35, 16x2 LCD showing SAFE, 2-channel relay with exhaust fan, buzzer, red and green LEDs and push button

How It Works

  • Warm-up and auto-calibration: the MQ-2 heater needs about a minute to stabilise, so the LCD counts down 60 seconds while the LEDs blink. The ATmega16 then averages 200 readings from ADC0 in clean air and stores this as the baseline. All gas readings are shown as a rise above the baseline (for example Gas:+35), which makes the project work with any MQ-2 module.
  • Gas and smoke (PA0): the MQ-2 tin-dioxide element lowers its resistance when LPG, methane, propane, hydrogen or smoke reaches it, so the AOUT voltage rises. 16 samples are averaged every 100 ms to remove noise.
  • Temperature (PA1): the LM35 outputs 10 mV per °C. With the 5V AVCC reference each ADC step is about 4.9 mV, so the code converts it with temp = raw × 500 / 1023.
  • Flame (PD2): the flame module’s comparator output goes LOW when it sees the infrared light from a flame. The internal pull-up keeps the line HIGH otherwise.
  • Three states: SAFE (green LED, relays off), WARNING (gas rise of 80+ counts or 45 °C+: fan on and a slow beep) and ALARM (flame, gas rise of 220+ counts or 60 °C+: fan on, valve relay on, red LED flashing and a fast beep). All limits are #define values at the top of the code.
  • Latched alarm and silence: during an alarm, one press of the button mutes the buzzer for 60 seconds (an M appears on the LCD). After the sensors return to normal the alarm stays latched until you press the button again, so nobody misses a short event.
  • Fan run-on: after gas clears, the exhaust fan keeps running for 30 more seconds to push the remaining gas out of the room.

Components Required

  • ATmega16 microcontroller (40-pin DIP) – 1
  • USBasp programmer (10-pin to 6-pin adapter if needed) – 1
  • MQ-2 gas/smoke sensor module (with AOUT pin) – 1
  • IR flame sensor module (3-pin, DO output) – 1
  • LM35 temperature sensor (TO-92) – 1
  • 16×2 character LCD (HD44780) with 10 kΩ contrast pot – 1
  • 2-channel 5V relay module (opto-isolated) – 1
  • 12V DC exhaust fan (or small 5V fan for the demo) – 1
  • 12V solenoid gas valve (or any load for the demo) – 1
  • Active buzzer 5V + 2N2222 transistor + 1 kΩ resistor – 1 set
  • Red and green 5 mm LEDs with 220 Ω resistors – 1 each
  • Tactile push button (SILENCE / RESET) – 1
  • 10 kΩ resistor (RESET pull-up) and 100 nF capacitors – 1 and 3
  • 12V 2A adapter + LM7805 regulator (or 5V 2A supply) – 1
  • Large breadboard or perfboard and jumper wires – 1 set

Wiring Table

Part / pinATmega16 pinNotes
7805 output +5VVCC (10), AVCC (30)100 nF from each to GND; AREF (32) 100 nF to GND
GNDGND (11, 31)Common ground for sensors, relay module, LCD and 12V supply
RESETPin 910 kΩ to +5V (also to USBasp RESET)
MQ-2 AOUTPA0 / ADC0 (40)MQ-2 VCC to +5V (heater draws about 150 mA)
LM35 Vout (middle pin)PA1 / ADC1 (39)Left pin +5V, right pin GND (flat face towards you)
Flame sensor DOPD2 (16)Module VCC +5V, GND; set sensitivity with its blue pot
SILENCE / RESET buttonPD3 (17) and GNDInternal pull-up, no resistor needed
LCD RS / RW / ENPB0 (1) / GND / PB1 (2)LCD VSS GND, VDD +5V, V0 to 10 kΩ pot wiper
LCD D4, D5, D6, D7PB4, PB5, PB6, PB7 (5–8)D0–D3 unused; backlight A via 220 Ω to +5V, K to GND
Relay IN1 (exhaust fan)PC0 (22)Fan +12V through relay COM/NO
Relay IN2 (gas valve / cut-off)PC1 (23)Valve +12V through relay COM/NO
Relay module VCC / GND+5V / GNDActive-LOW inputs; set RELAY_ACTIVE_LOW 0 for active-HIGH boards
Buzzer driverPD5 (19)1 kΩ to 2N2222 base, emitter GND, buzzer between +5V and collector
Red ALARM LEDPD6 (20)Through 220 Ω, cathode to GND
Green SAFE LEDPD7 (21)Through 220 Ω, cathode to GND

Fuses: the code runs on the internal 8 MHz oscillator with JTAG disabled so all of PORTC is free: lfuse = 0xE4, hfuse = 0xD9. A fresh ATmega16 has JTAG enabled, which blocks PC2–PC5, so always set the fuses first.

Connection Diagram

The illustration above shows the parts laid out on a breadboard. It is a layout guide only, so follow the pin-accurate drawing below, which matches the wiring table.

ATmega16 Fire & Gas Safety System – Pin-Accurate Wiring ATmega16 VCC/AVCC (10,30) +5V from 7805; AREF (32) via 100 nF to GND GND (11,31) Common GND for all modules and supplies PA0 / ADC0 (40) MQ-2 module AOUT PA1 / ADC1 (39) LM35 middle pin (Vout) PB0 (1) LCD RS (pin 4); LCD RW (pin 5) to GND PB1 (2) LCD EN (pin 6) PB4-PB7 (5-8) LCD D4-D7 (pins 11-14) PC0 (22) Relay IN1 – exhaust fan PC1 (23) Relay IN2 – gas valve / cut-off PD2 / INT0 (16) Flame sensor DO (LOW = flame) PD3 (17) SILENCE/RESET button to GND PD5 (19) 1 kΩ to 2N2222 base; buzzer on collector PD6 (20) 220 Ω to red ALARM LED PD7 (21) 220 Ω to green SAFE LED RESET (9): 10 kΩ to +5V. Program with USBasp: MOSI PB5, MISO PB6, SCK PB7, RESET.
Pin-accurate connection diagram for the ATmega16 fire and gas safety system.

Code

The firmware is plain AVR C with no external libraries (about 1.9 KB of flash). Save it as main.c, then compile and flash it with avr-gcc and a USBasp:

avr-gcc -mmcu=atmega16 -Os -o main.elf main.c
avr-objcopy -O ihex -R .eeprom main.elf main.hex
avrdude -c usbasp -p m16 -U lfuse:w:0xE4:m -U hfuse:w:0xD9:m
avrdude -c usbasp -p m16 -U flash:w:main.hex:i

You can also use Microchip Studio: create a GCC C project for the ATmega16, paste the code and build. Keep F_CPU at 8000000 to match the fuses.

/*
 * ATmega16 Fire & Gas Safety System
 * MQ-2 gas/smoke sensor + IR flame sensor + LM35 temperature sensor,
 * 16x2 LCD, 2-channel relay (exhaust fan + gas valve / mains cut-off),
 * buzzer, LEDs and a SILENCE / RESET button.
 * ardiunoprojecthub.online
 *
 * MCU   : ATmega16 @ 8 MHz internal oscillator
 * Fuses : lfuse=0xE4 (internal 8 MHz), hfuse=0xD9 (JTAG off so PORTC is free)
 *
 * Pins
 *   MQ-2 AOUT        -> PA0 (ADC0)
 *   LM35 Vout        -> PA1 (ADC1)
 *   Flame sensor DO  -> PD2 (LOW = flame seen, internal pull-up on)
 *   SILENCE button   -> PD3 to GND (internal pull-up)
 *   LCD 16x2 4-bit   : RS=PB0, EN=PB1, D4=PB4, D5=PB5, D6=PB6, D7=PB7, RW=GND
 *   Relay CH1 (fan)  -> PC0
 *   Relay CH2 (valve)-> PC1
 *   Buzzer (active)  -> PD5 (via 2N2222 or direct if < 20 mA)
 *   Red LED ALARM    -> PD6 (220 ohm)
 *   Green LED SAFE   -> PD7 (220 ohm)
 *   AVCC -> 5V, AREF -> 100 nF to GND (AVCC used as ADC reference)
 *
 * States
 *   SAFE    : green LED, relays off.
 *   WARNING : gas rising or temperature high -> exhaust fan ON, slow beep.
 *   ALARM   : flame, heavy gas/smoke or very high temperature ->
 *             fan ON, gas valve relay CLOSES supply, fast beep, red LED.
 *   ALARM is latched: once conditions are safe again, press SILENCE/RESET
 *   to return to SAFE. While in ALARM, SILENCE mutes the buzzer for 60 s.
 */
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include <stdlib.h>

/* ---------- user settings ---------- */
#define WARMUP_S        60     /* MQ-2 heater warm-up time            */
#define GAS_WARN_DELTA  80     /* ADC counts above clean-air baseline */
#define GAS_ALARM_DELTA 220
#define TEMP_WARN_C     45
#define TEMP_ALARM_C    60
#define FAN_RUNON_S     30     /* fan keeps running after gas clears  */
#define SILENCE_S       60
#define RELAY_ACTIVE_LOW 1     /* most blue relay modules are active-LOW */

/* ---------- LCD (HD44780 4-bit on PORTB) ---------- */
#define LCD_RS PB0
#define LCD_EN PB1

static void lcd_pulse(void)
{
    PORTB |= (1 << LCD_EN); _delay_us(1);
    PORTB &= ~(1 << LCD_EN); _delay_us(50);
}
static void lcd_nibble(uint8_t n)
{
    PORTB = (PORTB & 0x0F) | (n & 0xF0);
    lcd_pulse();
}
static void lcd_byte(uint8_t b, uint8_t rs)
{
    if (rs) PORTB |= (1 << LCD_RS); else PORTB &= ~(1 << LCD_RS);
    lcd_nibble(b);
    lcd_nibble(b << 4);
    if (!rs && b < 4) _delay_ms(2);
}
static void lcd_cmd(uint8_t c)  { lcd_byte(c, 0); }
static void lcd_char(char c)    { lcd_byte((uint8_t)c, 1); }
static void lcd_goto(uint8_t col, uint8_t row) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_line(uint8_t row, const char *s)
{   /* print a full 16-char line, padding with spaces (no flicker) */
    uint8_t i = 0;
    lcd_goto(0, row);
    while (*s && i < 16) { lcd_char(*s++); i++; }
    while (i++ < 16) lcd_char(' ');
}
static void lcd_init(void)
{
    DDRB |= 0xF3;                 /* PB0, PB1, PB4..PB7 outputs */
    _delay_ms(50);
    PORTB &= ~(1 << LCD_RS);
    lcd_nibble(0x30); _delay_ms(5);
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x30); _delay_us(150);
    lcd_nibble(0x20);             /* 4-bit mode */
    lcd_cmd(0x28);                /* 2 lines, 5x8 font */
    lcd_cmd(0x0C);                /* display on, cursor off */
    lcd_cmd(0x06);                /* entry mode */
    lcd_cmd(0x01);                /* clear */
}

/* ---------- ADC ---------- */
static void adc_init(void)
{
    ADMUX  = (1 << REFS0);                                 /* AVCC ref */
    ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1);    /* 8 MHz/64 = 125 kHz */
}
static uint16_t adc_read(uint8_t ch)
{
    ADMUX = (1 << REFS0) | (ch & 0x07);
    _delay_us(20);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC));
    return ADC;
}
static uint16_t adc_avg(uint8_t ch, uint8_t n)
{
    uint32_t sum = 0;
    for (uint8_t i = 0; i < n; i++) sum += adc_read(ch);
    return (uint16_t)(sum / n);
}

/* ---------- outputs ---------- */
static void relay(uint8_t pin, uint8_t on)
{
#if RELAY_ACTIVE_LOW
    if (on) PORTC &= ~(1 << pin); else PORTC |= (1 << pin);
#else
    if (on) PORTC |= (1 << pin); else PORTC &= ~(1 << pin);
#endif
}
#define FAN   PC0
#define VALVE PC1
#define BUZ_ON()   (PORTD |=  (1 << PD5))
#define BUZ_OFF()  (PORTD &= ~(1 << PD5))
#define RED(x)     ((x) ? (PORTD |= (1 << PD6)) : (PORTD &= ~(1 << PD6)))
#define GREEN(x)   ((x) ? (PORTD |= (1 << PD7)) : (PORTD &= ~(1 << PD7)))
#define FLAME_SEEN()   (!(PIND & (1 << PD2)))
#define BTN_PRESSED()  (!(PIND & (1 << PD3)))

enum { SAFE, WARNING, ALARM };

static void beep(uint16_t ms) { BUZ_ON(); while (ms--) _delay_ms(1); BUZ_OFF(); }

int main(void)
{
    char num[7];

    /* I/O setup */
    DDRC |= (1 << FAN) | (1 << VALVE);
    relay(FAN, 0); relay(VALVE, 0);
    DDRD |= (1 << PD5) | (1 << PD6) | (1 << PD7);
    DDRD &= ~((1 << PD2) | (1 << PD3));
    PORTD |= (1 << PD2) | (1 << PD3);           /* pull-ups */

    lcd_init();
    adc_init();

    /* ---- warm-up of the MQ-2 heater ---- */
    lcd_line(0, "Fire&Gas Safety");
    for (int s = WARMUP_S; s > 0; s--) {
        itoa(s, num, 10);
        lcd_line(1, "");
        lcd_goto(0, 1); lcd_print("Warm-up "); lcd_print(num); lcd_print(" s");
        RED(s & 1); GREEN(!(s & 1));
        _delay_ms(1000);
    }

    /* ---- learn clean-air baseline ---- */
    lcd_line(1, "Calibrating...");
    uint32_t sum = 0;
    for (uint16_t i = 0; i < 200; i++) { sum += adc_read(0); _delay_ms(5); }
    uint16_t baseline = (uint16_t)(sum / 200);
    RED(0); GREEN(1);
    beep(100);

    uint8_t  state = SAFE, latched = 0;
    uint16_t fan_runon = 0, silence = 0;   /* in 100 ms ticks */
    uint8_t  tick = 0, btn_prev = 0;

    for (;;) {
        /* ---- read sensors (every 100 ms) ---- */
        uint16_t gas  = adc_avg(0, 16);
        int16_t  diff = (int16_t)gas - (int16_t)baseline;
        if (diff < 0) diff = 0;
        uint16_t traw = adc_avg(1, 16);
        int16_t  temp = (int16_t)((traw * 500UL) / 1023);   /* LM35: 10 mV/C */
        uint8_t  flame = FLAME_SEEN();

        /* ---- decide state ---- */
        uint8_t now;
        if (flame || diff >= GAS_ALARM_DELTA || temp >= TEMP_ALARM_C) now = ALARM;
        else if (diff >= GAS_WARN_DELTA || temp >= TEMP_WARN_C)      now = WARNING;
        else                                                          now = SAFE;

        if (now == ALARM) { latched = 1; }
        if (latched) state = ALARM; else state = now;

        /* ---- button: silence buzzer or reset latched alarm ---- */
        uint8_t btn = BTN_PRESSED();
        if (btn && !btn_prev) {
            if (latched && now != ALARM) { latched = 0; state = now; silence = 0; beep(60); }
            else if (state == ALARM) { silence = SILENCE_S * 10; }
        }
        btn_prev = btn;
        if (silence) silence--;

        /* ---- outputs ---- */
        if (state != SAFE || diff >= GAS_WARN_DELTA) fan_runon = FAN_RUNON_S * 10;
        else if (fan_runon) fan_runon--;
        relay(FAN, fan_runon > 0);
        relay(VALVE, state == ALARM);           /* close gas / cut supply */

        GREEN(state == SAFE);
        if (state == ALARM)        { RED(tick & 2); if (!silence && (tick & 2)) BUZ_ON(); else BUZ_OFF(); }
        else if (state == WARNING) { RED(tick < 2); if (tick == 0) BUZ_ON(); else BUZ_OFF(); }
        else                       { RED(0); BUZ_OFF(); }

        /* ---- LCD every 500 ms ---- */
        if (tick % 5 == 0) {
            const char *msg;
            if (state == ALARM)
                msg = flame ? "!! FIRE ALARM !!" : (diff >= GAS_ALARM_DELTA ? "!! GAS  ALARM !!" :
                      (temp >= TEMP_ALARM_C ? "!! HEAT ALARM !!" : "ALARM-press RST "));
            else if (state == WARNING) msg = "WARNING  Fan ON ";
            else msg = fan_runon ? "SAFE    Fan ON  " : "SAFE  All normal";
            lcd_line(0, msg);

            /* line 2: "Gas:+123 T:31C F" */
            itoa(diff, num, 10);
            lcd_goto(0, 1);
            lcd_print("Gas:+"); lcd_print(num); lcd_print("   ");
            lcd_goto(9, 1);
            itoa(temp, num, 10);
            lcd_print("T:"); lcd_print(num); lcd_print("C");
            lcd_print(temp < 10 ? "  " : (temp < 100 ? " " : ""));
            lcd_goto(15, 1);
            lcd_char(flame ? 'F' : (silence ? 'M' : ' '));
        }

        if (++tick >= 10) tick = 0;
        _delay_ms(100 - 20);   /* ~100 ms loop including ADC time */
    }
}

Testing and Calibration

  • Power up in clean air. After the warm-up the LCD should read SAFE All normal with a gas value close to +0 and the room temperature.
  • Gas test: hold an unlit lighter near the MQ-2 and press its gas button briefly (do not light it). The gas value rises, the fan relay clicks on (WARNING) and, with more gas, the system goes to GAS ALARM and the valve relay turns on.
  • Flame test: light a candle about 30–50 cm in front of the flame sensor. Its DO LED lights and the LCD shows FIRE ALARM. Adjust the module’s pot so normal room light does not trigger it.
  • Heat test: warm the LM35 gently with your fingers or a hair dryer on low to see the temperature go up; lower TEMP_WARN_C temporarily to test the warning.
  • Press the button during an alarm to mute it, then again after the reading is normal to reset. Tune GAS_WARN_DELTA and GAS_ALARM_DELTA to suit your room.

Troubleshooting

ProblemFix
LCD shows black boxes or nothingTurn the 10 kΩ contrast pot. Check RW is tied to GND and the D4–D7 lines go to PB4–PB7 in order.
LCD garbled or code runs very slowlyThe fuses are still at 1 MHz or the clock does not match F_CPU. Program lfuse 0xE4 and hfuse 0xD9.
Relays click the wrong way (on when SAFE)Your relay board is active-HIGH. Change RELAY_ACTIVE_LOW to 0 and rebuild.
Goes to GAS ALARM right after startIt calibrated in dirty air or the MQ-2 is new. Burn in a new sensor for 24–48 hours, then reset the ATmega16 in fresh air.
FIRE ALARM in sunlight or bright lampSunlight contains infrared. Turn the flame module’s pot to lower sensitivity and point it away from windows.
Temperature reads 0 or jumps a lotCheck the LM35 pin order and add a 100 nF capacitor from its output to GND. Keep its wires away from the relay wires.
Controller resets when the fan or valve switchesFeed the 12V loads from their own supply, keep only GND common, add a flyback diode across the solenoid valve and a 470 µF capacitor on the 5V rail.

Ideas to Extend

  • Add a SIM800L GSM module on the ATmega16 UART (PD0/PD1) to send an SMS on alarm.
  • Log alarm events with a time stamp using a DS1307 RTC and the internal EEPROM.
  • Add a second MQ-2 in another room on ADC2 and show which zone is in alarm.

ATmega16 Temperature Controller with LM35, 16×2 LCD & Fan Relay

Wiring diagram of an ATmega16 temperature controller with an LM35 sensor, 16x2 LCD, relay-driven cooling fan, status LED, buzzer and 7805 power supply

Build an ATmega16 temperature controller with an LM35 sensor, 16×2 LCD, relay-driven fan and alarm. Wiring table, diagram, fuses and full AVR C code.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUATmega16
  • Parts14 items
  • CodeAVR C

Need it ready-made? Buy Ready Project

This ATmega16 temperature controller reads an LM35 sensor, shows the temperature on a 16×2 LCD, and switches a 12 V cooling fan through a relay when it gets too warm. If the temperature keeps rising past a second limit, a red LED and buzzer warn you. It is a practical project for a cabinet, an inverter box, an incubator or a small server shelf.

It is a medium-level build. You use the ATmega16’s built-in 10-bit ADC, drive an HD44780 LCD in 4-bit mode without any library, and write a simple control loop with hysteresis, all in plain AVR C.

How the ATmega16 Temperature Controller Works

  • Sensing: the LM35 gives 10 mV per °C, so 30 °C is 0.30 V. Its output goes to PA0 (ADC0).
  • Measuring: the ADC uses the ATmega16’s internal 2.56 V reference. Each ADC step is 2.5 mV, which is 0.25 °C. The code averages 16 readings to remove noise.
  • Fan control with hysteresis: the fan relay on PC7 turns on at 35 °C and stays on until the temperature falls to 32 °C. The 3 °C gap stops the relay chattering on and off around one value.
  • Alarm: at 45 °C the LED on PD7 and the buzzer on PD6 blink, and the LCD shows ALARM!.
  • Display: line 1 shows the temperature to 0.1 °C, line 2 shows the fan state and the set point.

One ATmega16 detail matters here: PC2–PC5 are also the JTAG pins, and JTAG is on from the factory. The code writes the JTD bit twice at start-up to turn JTAG off, and the fuse values below also disable it, so the LCD data lines work normally.

Components Required

  • ATmega16 or ATmega16A microcontroller (DIP-40) – 1
  • 16 MHz crystal – 1, with 22 pF ceramic capacitors – 2
  • LM35 temperature sensor (TO-92) – 1
  • 16×2 character LCD (HD44780 compatible) – 1
  • 10 kΩ potentiometer for LCD contrast – 1
  • 1-channel 5 V relay module – 1
  • 12 V DC cooling fan – 1
  • Active 5 V buzzer – 1
  • Red LED – 1, with 330 Ω resistor – 1
  • 10 kΩ resistor (reset pull-up) – 1, 220 Ω resistor (LCD backlight) – 1
  • 7805 voltage regulator – 1, 10 µF and 100 µF electrolytic capacitors, 100 nF ceramic capacitors – 3
  • 12 V DC adapter (powers the fan and, through the 7805, the 5 V rail)
  • USBasp or another AVR ISP programmer
  • Breadboard or perfboard and jumper wires

Wiring Table (Pin-to-Pin)

PartPart PinATmega16 PinNotes
7805IN / GND / OUT12 V in / GND / 5 V rail10 µF on input, 100 µF + 100 nF on output
ATmega16VCC (10), AVCC (30)5 VAVCC must be connected for the ADC
ATmega16GND (11, 31)GND100 nF between VCC and GND near the chip
ATmega16RESET (9)10 kΩ to 5 VAlso goes to the ISP header
16 MHz crystalBoth legsXTAL1 (13), XTAL2 (12)22 pF from each pin to GND
ATmega16AREF (32)100 nF to GNDDo not tie AREF to 5 V (code uses 2.56 V internal)
LM351 (+Vs)5 VFlat face toward you, pins left to right
LM352 (Vout)PA0 / ADC0 (40)10 mV per °C
LM353 (GND)GND
LCD1 VSS, 5 RW, 16 KGNDRW tied low (write only)
LCD2 VDD5 V
LCD3 V010 kΩ pot wiperPot ends to 5 V and GND
LCD4 RSPC0 (22)
LCD6 EPC1 (23)
LCD11–14 D4–D7PC2–PC5 (24–27)JTAG pins, disabled in code and fuses
LCD15 A5 V through 220 ΩBacklight
Relay moduleIN / VCC / GNDPC7 (29) / 5 V / GNDUsually active-low
Relay contactsCOM / NO12 V + / fan +Fan − to 12 V −
Buzzer+ / −PD6 (20) / GNDActive buzzer, under 20 mA
LEDAnode / cathodePD7 (21) via 330 Ω / GNDAlarm indicator

Connection Diagram

The illustration below is also the featured image and gives an overview of the build. Use the pin-accurate drawing under it, which matches the wiring table, when you connect the parts.

Wiring diagram of an ATmega16 temperature controller with an LM35 sensor, 16x2 LCD, relay-driven cooling fan, status LED, buzzer and 7805 power supply
ATmega16 temperature controller overview: LM35, 16×2 LCD, relay and fan, LED, buzzer and 7805 supply.
ATmega16 Temperature Controller – Wiring ATmega16 (DIP-40) PA0/ADC0 (40) AREF (32) VCC (10), AVCC (30) GND (11, 31) RESET (9) XTAL1 (13), XTAL2 (12) PC0 (22) RS PC1 (23) E PC2–PC5 (24–27) D4–D7 PC7 (29) relay PD6 (20) buzzer PD7 (21) LED LM35 (flat face front) Pin 1 +Vs → 5 V Pin 2 Vout → PA0 Pin 3 GND → GND AREF 100 nF→GND RESET: 10 kΩ to 5 V 16 MHz crystal XTAL1–XTAL2 22 pF from each XTAL pin to GND 100 nF VCC–GND near chip 16×2 LCD (HD44780) Temp: 31.5 CFan:ON Set:35 1 VSS→GND, 2 VDD→5V, 3 V0→10k pot wiper 4 RS→PC0, 5 RW→GND, 6 E→PC1 11–14 D4–D7→PC2–PC5, 15 A→5V(220Ω), 16 K→GND 5 V Relay Module + 12 V Fan IN→PC7, VCC→5V, GND→GND 12 V + → COM, NO → fan + fan − → 12 V − PD6 → active 5 V buzzer (+), buzzer (−) → GND PD7 → 330 Ω → red LED anode, cathode → GND 7805 supply: 9–12 V in → 7805 → 5 V rail 10 µF on input, 100 µF + 100 nF on output; all grounds common Yellow = sensor signal, green = LCD bus, blue = relay, orange = alarm outputs, red = power. Pin numbers are for the DIP-40 package.
Pin-accurate connection diagram: LM35 on PA0, LCD on PC0–PC5, relay on PC7, buzzer on PD6 and LED on PD7.

ATmega16 Code (AVR-GCC)

Create a new GCC C project for the ATmega16 in Microchip Studio, or save the file as main.c if you use avr-gcc from the command line. No external libraries are needed. You can change the fan and alarm temperatures at the top of the file.

/*
  ATmega16 Temperature Controller
  LM35 sensor + 16x2 LCD (4-bit) + relay-driven fan + LED and buzzer alarm
  Compiler : AVR-GCC (Microchip Studio, or avr-gcc + avrdude)
  Clock    : 16 MHz external crystal  (fuses: lfuse 0xFF, hfuse 0xD9)

  Wiring
    LM35 Vout -> PA0 (ADC0)    AREF -> 100 nF -> GND    AVCC -> 5 V
    LCD RS -> PC0   E -> PC1   D4..D7 -> PC2..PC5   RW -> GND
    Relay IN -> PC7            Buzzer -> PD6         LED -> PD7 (330 ohm)
*/

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>

// ---- user settings (temperatures in tenths of a degree C) ----
#define FAN_ON_X10     350   // fan turns ON at 35.0 C
#define FAN_OFF_X10    320   // fan turns OFF at 32.0 C (3 C hysteresis)
#define ALARM_X10      450   // buzzer + LED alarm at 45.0 C
#define RELAY_ACTIVE_LOW 1   // most blue relay modules switch ON when IN is LOW

// ---- LCD pins on PORTC ----
#define LCD_RS PC0
#define LCD_E  PC1
// D4..D7 are PC2..PC5

#define RELAY_PIN  PC7
#define BUZZER_PIN PD6
#define LED_PIN    PD7

// Send the low 4 bits of n to D4..D7 and pulse E
static void lcd_nibble(uint8_t n) {
  PORTC = (PORTC & 0xC3) | ((n & 0x0F) << 2);   // keep PC0, PC1, PC6, PC7
  PORTC |= (1 << LCD_E);
  _delay_us(1);
  PORTC &= ~(1 << LCD_E);
  _delay_us(50);
}

static void lcd_send(uint8_t value, uint8_t is_data) {
  if (is_data) PORTC |= (1 << LCD_RS); else PORTC &= ~(1 << LCD_RS);
  lcd_nibble(value >> 4);
  lcd_nibble(value);
  if (!is_data && value < 4) _delay_ms(2);        // clear / home are slow
}

static void lcd_cmd(uint8_t c)  { lcd_send(c, 0); }
static void lcd_char(char c)    { lcd_send((uint8_t)c, 1); }
static void lcd_print(const char *s) { while (*s) lcd_char(*s++); }
static void lcd_goto(uint8_t row, uint8_t col) { lcd_cmd(0x80 | (row ? 0x40 : 0x00) | col); }

static void lcd_init(void) {
  _delay_ms(50);                 // wait for LCD power-up
  PORTC &= ~(1 << LCD_RS);
  lcd_nibble(0x03); _delay_ms(5);
  lcd_nibble(0x03); _delay_ms(1);
  lcd_nibble(0x03);
  lcd_nibble(0x02);              // switch to 4-bit mode
  lcd_cmd(0x28);                 // 4-bit, 2 lines, 5x8 font
  lcd_cmd(0x0C);                 // display on, cursor off
  lcd_cmd(0x06);                 // auto-increment
  lcd_cmd(0x01);                 // clear
}

// ADC with the internal 2.56 V reference: 1 step = 2.5 mV = 0.25 C for the LM35
static void adc_init(void) {
  ADMUX  = (1 << REFS1) | (1 << REFS0);                               // 2.56 V ref, channel ADC0
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);  // enable, 16 MHz / 128 = 125 kHz
}

static uint16_t adc_read(void) {
  ADCSRA |= (1 << ADSC);
  while (ADCSRA & (1 << ADSC)) { }
  return ADC;
}

// Average 16 readings and convert to tenths of a degree C
static int16_t read_temp_x10(void) {
  uint32_t sum = 0;
  for (uint8_t i = 0; i < 16; i++) { sum += adc_read(); _delay_ms(2); }
  // temp_x10 = adc * 2.5 mV / 10 mV per C * 10  = adc * 2.5
  return (int16_t)((sum * 25UL) / 160UL);
}

static void set_relay(uint8_t on) {
  uint8_t high = RELAY_ACTIVE_LOW ? !on : on;
  if (high) PORTC |= (1 << RELAY_PIN); else PORTC &= ~(1 << RELAY_PIN);
}

int main(void) {
  // PC2..PC5 are JTAG pins on the ATmega16. Turn JTAG off in software
  // (JTD must be written twice within 4 clock cycles) so the LCD can use them.
  uint8_t m = MCUCSR | (1 << JTD);
  MCUCSR = m;
  MCUCSR = m;

  // Relay off level first, then make the pins outputs (no click at power-up)
  set_relay(0);
  DDRC = 0xFF;                                   // LCD + relay
  DDRD |= (1 << BUZZER_PIN) | (1 << LED_PIN);
  PORTD &= ~((1 << BUZZER_PIN) | (1 << LED_PIN));

  lcd_init();
  adc_init();
  lcd_print(" ATmega16 Temp ");
  lcd_goto(1, 0);
  lcd_print("  Controller   ");
  _delay_ms(1500);
  lcd_cmd(0x01);

  uint8_t fan_on = 0;
  uint8_t blink = 0;
  char line[17];

  while (1) {
    int16_t t = read_temp_x10();

    // Fan control with hysteresis
    if (!fan_on && t >= FAN_ON_X10)  fan_on = 1;
    if (fan_on  && t <= FAN_OFF_X10) fan_on = 0;
    set_relay(fan_on);

    // Over-temperature alarm: LED and buzzer blink together
    uint8_t alarm = (t >= ALARM_X10);
    blink ^= 1;
    if (alarm && blink) PORTD |= (1 << BUZZER_PIN) | (1 << LED_PIN);
    else                PORTD &= ~((1 << BUZZER_PIN) | (1 << LED_PIN));

    // Line 1: temperature
    snprintf(line, sizeof(line), "Temp:%3d.%d C    ", t / 10, t % 10);
    lcd_goto(0, 0); lcd_print(line);
    // Line 2: fan state and set point (or ALARM)
    if (alarm) snprintf(line, sizeof(line), "Fan:ON  ALARM!  ");
    else       snprintf(line, sizeof(line), "Fan:%s Set:%2d  ", fan_on ? "ON " : "OFF", FAN_ON_X10 / 10);
    lcd_goto(1, 0); lcd_print(line);

    _delay_ms(400);
  }
}

Compile, Set Fuses and Upload

A new ATmega16 runs from its internal 1 MHz oscillator with JTAG enabled. Set the fuses once so it uses the 16 MHz crystal and frees PORTC. With a USBasp and avrdude:

avr-gcc -mmcu=atmega16 -Os -o main.elf main.c
avr-objcopy -O ihex -R .eeprom main.elf main.hex
avrdude -c usbasp -p m16 -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m
avrdude -c usbasp -p m16 -U flash:w:main.hex:i

Connect the crystal before writing the fuses. If the fuse is set to an external crystal and none is fitted, the chip will not respond to the programmer until you give it a clock.

Testing and Calibration

  1. Power the board and turn the contrast pot until the LCD text is clear.
  2. Check the room temperature on the LCD against a known thermometer. The LM35 is usually within ±0.5 °C at room temperature.
  3. Warm the LM35 gently with your fingers or a hair dryer on low. At 35 °C the relay should click and the fan should start.
  4. Let it cool. The fan should stop at 32 °C, not at 34.9 °C, which shows the hysteresis is working.
  5. Heat it carefully past 45 °C to check that the LED, buzzer and ALARM! message work.

Troubleshooting

ProblemFix
LCD shows only black boxesAdjust the contrast pot. If it still shows boxes, check RS, E and D4–D7, and confirm JTAG is off (hfuse 0xD9).
LCD shows random charactersThe clock is wrong, so the delays are wrong. Check the crystal, the 22 pF capacitors and lfuse 0xFF.
Temperature reads 0 or jumps wildlyConnect AVCC (pin 30) to 5 V and fit the 100 nF capacitor on AREF. Keep the LM35 wire short or use shielded cable.
Temperature reads far too highAREF is probably tied to 5 V. Remove that link; the internal 2.56 V reference needs AREF free with only a capacitor.
Fan works the wrong way roundYour relay module is active-high. Set RELAY_ACTIVE_LOW to 0.
Chip resets when the relay clicksAdd a 100 µF capacitor on the 5 V rail and keep fan wires away from the LM35 and the reset line.

Ideas to Extend This Project

  • Add two push-buttons on PD2 and PD3 to change the set point, and save it in EEPROM.
  • Replace the relay with a logic-level MOSFET and use PWM on OC1A (PD5) for variable fan speed.
  • Add a second LM35 on PA1 to compare inside and outside temperature.
  • Send the readings over the UART (PD0/PD1) to a PC or a Bluetooth module for logging.

FAQ

Can I use an ATmega32 instead? Yes. The ATmega32 has the same pinout and registers for everything used here, so change only the -mmcu and avrdude part names.

Why use the 2.56 V reference and not 5 V? The LM35 output stays under 1.5 V for normal temperatures. A smaller reference gives 0.25 °C steps instead of about 0.5 °C, so the reading is finer.

Can the relay switch a mains fan? The relay contacts may be rated for 250 V AC, but start with a 12 V DC fan. Switch mains only inside a closed, insulated enclosure, and ask a qualified electrician if you are not sure.

Related Projects

Browse more ATmega16 on Arduino Project Hub.

Automatic Water Tank Controller with LM358, 555 & ULN2003

Connection diagram of an automatic water tank controller using LM358, NE555, ULN2003 and 7805 ICs with tank probes, pump relay and overflow buzzer

Build an automatic overhead water tank controller with LM358, 555, ULN2003 and 7805. No microcontroller or code: probe wiring, pump latch, overflow alarm and diagram.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUNo MCU: LM358 + NE555
  • Parts16 items
  • CodeNot needed

Need it ready-made? Buy Ready Project

This automatic water tank controller fills an overhead tank and switches the pump off when the water reaches the high probe. It is built from four everyday non-programmable ICs — a 7805 regulator, an LM358 dual op-amp, a NE555 timer and a ULN2003A Darlington array — so there is no microcontroller and no code to upload. Two transistors form a set-reset latch: the pump starts when the tank falls below the low probe and keeps running until the high probe gets wet. A fourth overflow probe enables the 555, which sounds a buzzer if the tank ever overfills.

Build and test it with a 12 V DC water pump (an aquarium or diaphragm pump is ideal). That keeps the whole project on low voltage. If you later switch a 230 V mains pump, use a properly rated enclosed relay or contactor and have the mains wiring done by a qualified person. Never put mains voltages on a breadboard.

Below you get a clear description of how the latch and alarm work, the full parts list, a pin-to-pin wiring table, and a connection diagram. Because every chip here is analog or a simple logic array, this project has no sketch to copy.

How the Water Tank Controller Works

A 12 V DC adapter powers the pump relay and the ULN2003 clamp pin. The same 12 V goes into a 7805, which makes a clean 5 V rail for the LM358 and the 555. Put a 10 µF electrolytic and a 0.1 µF ceramic capacitor on both the regulator input and the output, close to the 7805 pins.

Four stainless steel probes hang in the tank. The COM probe sits at the bottom and is wired to +5 V. The LOW, HIGH and OVERFLOW probes sit at about 20 percent, 90 percent and just above the high mark. Each sense probe has a 100 kΩ resistor to ground. When water touches a probe, it conducts from COM and the probe voltage rises well above the 2.5 V reference (two 10 kΩ resistors between +5 V and ground).

Inside the LM358, op-amp A compares the HIGH probe (pin 3) with 2.5 V (pin 2). Pin 1 goes high when the tank is full. Op-amp B compares the LOW probe (pin 5) with 2.5 V (pin 6). Pin 7 goes high when water is at or above the low probe.

The pump must not chatter every time the water ripples around one probe. That is what the latch is for:

  • Start: when the tank is below LOW, pin 7 is low. Transistor Q1 inverts that signal, so START is high. Diode D1 pulls the RUN node high and the pump turns on.
  • Hold: once the relay closes, its normally-open contact feeds 12 V into a 15 kΩ + 10 kΩ divider (about 4.8 V). Diode D2 keeps RUN high even after the water rises past the low probe and START falls.
  • Stop: when the tank reaches HIGH, pin 1 goes high and transistor Q2 shorts RUN to ground. The relay drops out, HOLD disappears, and the pump stays off until the water falls below LOW again.

The ULN2003A sinks the relay coil from IN1/OUT1, so the small RUN signal never has to carry coil current. Pin 9 (COM) goes to +12 V and uses the chip’s built-in clamp diodes. A green LED on IN3/OUT3 lights while the pump is on. A red LED driven from LM358 pin 1 (through another ULN2003 channel) lights when the tank is full.

The NE555 runs as a slow astable (about 0.7 Hz with 10 kΩ, 100 kΩ and 10 µF). Its RESET pin (pin 4) is held low by a 100 kΩ resistor, so the chip stays silent. When water reaches the overflow probe, that pin is pulled up through the water toward +5 V, the 555 starts, and pin 3 drives ULN2003 IN2. OUT2 then beeps the buzzer. If the high-level shutoff is working, you should never hear this alarm — it is the safety net.

Components Required

  • 7805 voltage regulator – 1
  • LM358 dual op-amp – 1
  • NE555 timer – 1
  • ULN2003A Darlington transistor array – 1
  • 12 V SPDT relay (coil 12 V; contacts rated for your pump) – 1
  • 12 V DC water pump – 1 (for safe testing)
  • 12 V DC adapter, 1 A or more – 1
  • Active buzzer, 5 V or 12 V – 1
  • BC547 or 2N2222 NPN transistors – 2
  • 1N4148 diodes – 2
  • Stainless steel probes or bolts with insulated wire – 4
  • Resistors: 10 kΩ × 6, 100 kΩ × 4, 15 kΩ × 1, 330 Ω × 2
  • Capacitors: 10 µF / 25 V electrolytic × 2, 10 µF / 16 V electrolytic × 1, 0.1 µF ceramic × 2, 10 nF ceramic × 1
  • LEDs: green (pump on) and red (tank full) – 1 each
  • 8-pin IC sockets (optional) – 2, and one 16-pin socket for the ULN2003
  • Breadboard or perfboard, jumper wires, and a small heatsink for the 7805 if it runs warm

Wiring Table (Pin-to-Pin)

PartPin / NodeConnects ToNotes
7805IN (pin 1)+12 V adapter +10 µF and 0.1 µF from IN to GND, close to the regulator
7805GND (pin 2)Circuit GNDJoin to the adapter −
7805OUT (pin 3)+5 V rail10 µF and 0.1 µF from OUT to GND
LM358VCC (pin 8)+5 VDo not run the op-amp from 12 V in this build
LM358GND (pin 4)GNDCommon ground
Reference dividerMidpoint of two 10 kΩ resistorsLM358 pins 2 and 6Top 10 kΩ to +5 V, bottom 10 kΩ to GND (about 2.5 V)
Probe COMBottom of the tank+5 VLowest stainless rod; stays in water whenever the tank is not empty
Probe LOWAbout 20% heightLM358 pin 5100 kΩ from pin 5 to GND
Probe HIGHAbout 90% heightLM358 pin 3100 kΩ from pin 3 to GND
Probe OVERFLOWA few centimetres above HIGHNE555 RESET (pin 4)100 kΩ from pin 4 to GND
LM358Pin 7 (low-level output)Q1 base through 10 kΩHigh when water is at or above LOW
Q1 (BC547)EmitterGNDInverts pin 7 to make START
Q1 (BC547)Collector (START)RUN node through D1 (1N4148)Also a 10 kΩ pull-up from the collector to +5 V
LM358Pin 1 (high-level output)Q2 base through 10 kΩHigh when the tank is full
Q2 (BC547)EmitterGNDReset transistor
Q2 (BC547)CollectorRUN nodeShorts RUN to ground when the tank is full
RelayNO contactHOLD divider, then D2 to RUN15 kΩ from NO to the midpoint, 10 kΩ from the midpoint to GND, then D2 (1N4148) to RUN
RUN node—ULN2003 IN1 (pin 1) and IN3 (pin 3)High means the pump should run
ULN2003AGND (pin 8)GNDCommon ground
ULN2003ACOM (pin 9)+12 VClamp diodes for the relay coil
ULN2003AOUT1 (pin 16)Relay coil −Relay coil + goes to +12 V
RelayCOM+12 VSwitched pump supply
RelayNO12 V pump + and the HOLD dividerPump − goes to GND
NE555VCC (pin 8)+5 V
NE555GND (pin 1)GND
NE555TR (pin 2) and TH (pin 6)Tied togetherAstable mode
NE555DIS (pin 7)10 kΩ to +5 V and 100 kΩ to pins 2 and 6Timing resistors
Timing capacitor10 µFPins 2 and 6 to GNDGives a beep of about 0.7 Hz
NE555CTRL (pin 5)10 nF to GNDKeeps the control pin quiet
NE555OUT (pin 3)ULN2003 IN2 (pin 2)Alarm drive
ULN2003AOUT2 (pin 15)Buzzer −Buzzer + to +12 V, or to +5 V if you use a 5 V buzzer
Green LEDAnode through 330 Ω to +5 VCathode to ULN2003 OUT3 (pin 14)IN3 is tied to RUN
Red LEDAnode through 330 Ω to +5 VCathode to ULN2003 OUT4 (pin 13)IN4 (pin 4) is tied to LM358 pin 1

Use one common ground for the adapter, the 7805, both 8-pin ICs, the ULN2003, the two transistors and the pump. If your buzzer is a 5 V type, take its positive lead to +5 V instead of +12 V so you do not burn it out.

Connection Diagram

The overview image shows the main blocks. Use the labelled diagram that follows, and the wiring table, for the exact pin connections.

Connection diagram of an automatic water tank controller using LM358, NE555, ULN2003 and 7805 ICs with tank probes, pump relay and overflow buzzer
Automatic water tank controller wiring diagram with LM358, 555, ULN2003 and 7805 Four tank probes to LM358 and 555, a transistor latch driving ULN2003 IN1 and a pump relay, and a 555 overflow alarm driving a buzzer through ULN2003 IN2. Power comes from 12 V through a 7805 regulator. Automatic Water Tank Controller: Connection Diagram LM358 level sensors + transistor latch + ULN2003 pump drive + NE555 overflow alarm (no microcontroller) 7805 regulator IN = +12 V (adapter +) GND = adapter – / circuit GND OUT = +5 V rail +12 V rail +5 V rail (add 10 µF and 0.1 µF on IN and OUT) Overhead tank OVERFLOW HIGH LOW COM (+5 V) Stainless probes LM358 dual op-amp 8 VCC = +5 V 3 HIGH probe (100k to GND) 2 2.5 V reference 1 OUT = tank full 5 LOW probe (100k to GND) 6 2.5 V reference 7 OUT = water at/above LOW 4 GND 2.5 V from two 10 kΩ resistors (+5 V to GND) Latch (set / reset) Q1 BC547 inverter Base: pin 7 via 10 kΩ Collector: START (10 kΩ to +5 V) Q2 BC547 reset Base: pin 1 via 10 kΩ RUN node D1 from START, D2 from HOLD pin 1 pin 7 ULN2003A IN1 (pin 1) = RUN OUT1 (pin 16) = relay coil – IN2 (pin 2) = 555 pin 3 OUT2 (pin 15) = buzzer – COM (pin 9) = +12 V GND (pin 8) = GND IN3 = RUN, OUT3 = green LED – RUN 12 V SPDT relay Coil + = +12 V Coil – = ULN OUT1 COM = +12 V NO = pump + and HOLD 12 V DC pump + from relay NO, – to GND HOLD: relay NO through 15 kΩ + 10 kΩ divider, then D2 to RUN NE555 overflow alarm (astable) 8 VCC = +5 V 1 GND 4 RESET = OVERFLOW probe 2 and 6 tied, 10 µF to GND 7 10 kΩ to +5 V, 100 kΩ to pins 2 and 6 5 10 nF to GND 3 OUT to ULN2003 IN2 555 pin 3 overflow wire from tank Active buzzer + to +12 V (or +5 V if 5 V type) – to ULN2003 OUT2 Indicators Green LED: pump ON (330 Ω to +5 V, cathode OUT3) Red LED: tank full (LM358 pin 1 to ULN IN4) Follow the wiring table for every resistor and diode. Common GND for the adapter, 7805, ICs, transistors, ULN2003 and pump.
Connection diagram for the LM358, 555 and ULN2003 water tank controller. Match each labelled pin to the wiring table above.

How to Build and Set the Probes

  1. Wire the 7805 first and confirm you have a steady 5 V rail before you insert the other ICs.
  2. Add the 2.5 V reference divider and check that LM358 pins 2 and 6 sit near 2.5 V.
  3. Fit the LM358, the two transistors, the two diodes and the ULN2003, then the relay and the green LED. Leave the 555 and buzzer until the pump latch works.
  4. Hang the four probes so they cannot swing into each other. COM must be the lowest. Space LOW, HIGH and OVERFLOW to match your tank.
  5. For a first test, stand the four probes in a plastic jar or bucket instead of the real overhead tank. Use a 12 V DC pump that recirculates water back into the same jar, or simply watch the relay and the green LED.
  6. If tap water is very pure and a probe does not switch the comparator, raise the pull-down resistors from 100 kΩ to 470 kΩ, or move that pair of probes closer together. Do not add salt to a drinking-water tank.
  7. When the latch works, add the 555, the overflow probe resistor and the buzzer. Raise the water to the overflow probe on purpose once, confirm the alarm, then lower the probe so normal fill-and-stop never reaches it.

Testing the Controller

  1. Start with the jar below the LOW probe. The green LED should light and the relay should click on. The 12 V pump (if connected) should run.
  2. Raise the water past LOW but not as far as HIGH. The pump must stay on. That proves the HOLD path through the relay contact and D2.
  3. Raise the water to HIGH. The red LED should light, the relay should drop out and the pump should stop.
  4. Lower the water so HIGH goes dry but LOW is still wet. The pump must stay off. That is the other half of the latch.
  5. Lower the water below LOW. The pump should start again.
  6. Raise the water to the overflow probe. The buzzer should beep on and off about once a second. Drop the water below that probe and the alarm should stop.

Troubleshooting

ProblemFix
7805 gets very hotThe relay coil or a wiring short is drawing too much from the 5 V rail. The coil must run from +12 V through the ULN2003, not from 5 V. Add a heatsink and check for solder bridges.
Pump never startsCheck RUN with a meter. If it never goes high, look at Q1, the 10 kΩ collector pull-up and D1. Confirm COM is on +5 V and the LOW probe really reaches pin 5.
Pump never stopsConfirm the HIGH probe reaches LM358 pin 3 and that Q2 can pull RUN to ground (about 0 V) when you touch the HIGH probe to COM. Check that pin 1 goes high when HIGH is wet.
Pump chatters on and off near one probeThe latch is not holding. Check D2, the 15 kΩ + 10 kΩ divider on the relay NO contact, and that the relay COM is really at +12 V when the coil is energised.
A probe does nothingClean the metal, shorten the gap to COM, or raise that probe’s 100 kΩ pull-down to 470 kΩ. Very long thin wires pick up noise — keep probe cables reasonably short.
Buzzer stays silent at overflowRESET (pin 4) must rise well above 0.7 V. Check the overflow pull-down and the ULN2003 IN2/OUT2 path. A passive buzzer (no internal oscillator) will only click — use an active buzzer.
Buzzer runs all the timePin 4 is not pulled down, or the overflow probe is touching COM or sitting in water. Confirm the 100 kΩ from pin 4 to GND.

Ideas to Extend This Project

  • Add a sump or underground-tank dry-run probe with a second LM358 so the pump cannot run if the source is empty.
  • Wire a second relay channel on the ULN2003 to switch a solenoid valve instead of, or as well as, a pump.
  • Bring LOW, HIGH and OVERFLOW status to three extra LEDs so you can see each probe without dipping a meter in the tank.
  • Replace the two 10 kΩ reference resistors with a 10 kΩ preset if you want to tune the trip point for very pure or very hard water.

FAQ

Why is there no code? The 7805, LM358, NE555 and ULN2003 are analog and logic chips, not microcontrollers. The behaviour is set by the wiring, the probe heights and a few resistors.

Can I use this on a 230 V borewell or overhead-tank pump? The control side stays at 12 V and 5 V. Only a properly rated enclosed relay or contactor should switch a mains pump, and a qualified person should do that wiring. For learning and for the tests in this article, use a 12 V DC pump.

Will the probes rust? Use stainless steel rods or bolts. Ordinary iron or copper will corrode in water and give false readings. Keep the wiring joints above the water line.

Can I power the LM358 from 12 V instead of 5 V? The LM358 can run from 12 V, but then the probe pull-ups, the 2.5 V divider and the 555 supply would no longer match. Keep the op-amp and the 555 on the 7805’s 5 V rail as drawn.

What pump current can the ULN2003 handle? The ULN2003 drives the relay coil, not the pump motor. A typical 12 V relay coil is 30 to 80 mA, which is well inside one ULN2003 channel (500 mA). Size the relay contacts for the pump’s own current.

Related Projects

Browse more Industrial Automation on Arduino Project Hub.

Automatic Plant Watering System with Arduino and Soil Moisture Sensor

Potted plant with a capacitive soil moisture sensor wired to an Arduino Uno, relay module and mini water pump in a glass – Arduino automatic plant watering system

Build an automatic irrigation system with Arduino Uno, a capacitive soil moisture sensor, relay and pump. Calibration, wiring table, full code and FAQ.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUArduino Uno / Nano
  • Parts6 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Going on holiday, or simply forgetting to water your plants? This automatic plant watering system with Arduino and a soil moisture sensor checks the soil every half second and switches on a small water pump only when the soil is dry. It stops as soon as the soil is moist enough, and it has two safety features most online versions skip: a maximum pump run time (so a broken sensor cannot flood your floor) and a soak delay that gives water time to spread before the next check.

How It Works

A capacitive soil moisture sensor acts like a capacitor whose value changes with the water content of the soil around it. Its on-board circuit converts this into an analog voltage: higher voltage when dry, lower when wet. The Arduino reads it on A0, converts it to a 0–100 % moisture value using two calibration points, and controls a relay that switches a 5 V DC submersible pump. The code uses hysteresis – start below 35 %, stop above 60 % – so the pump does not rapidly switch on and off around a single value.

We use the capacitive sensor (v1.2) instead of the two-prong resistive “YL-69” probe because resistive probes pass current through the soil and corrode within weeks.

Components Required

  • Arduino Uno R3 – 1
  • Capacitive soil moisture sensor v1.2 – 1
  • 1-channel 5 V relay module – 1
  • 3–6 V DC mini submersible pump with silicone tube – 1
  • Separate 5 V power supply for the pump (or 4×AA battery pack)
  • Water container, jumper wires, small screwdriver

Wiring Table (Pin-to-Pin)

ModuleModule PinConnect ToNotes
Soil sensorVCCArduino 5VWorks on 3.3–5.5 V
Soil sensorGNDArduino GND
Soil sensorAOUTArduino A0SOIL_PIN = A0
Relay moduleVCCArduino 5V
Relay moduleGNDArduino GND
Relay moduleINArduino D7RELAY_PIN = 7
RelayCOMPump supply + (5 V)Pump power does not come from the Arduino
RelayNOPump red (+) wirePump runs only when relay is ON
PumpBlack (−)Pump supply −Also connect supply − to Arduino GND only if your relay module needs a common ground

Libraries

No external libraries are needed – the sketch uses only built-in Arduino functions (analogRead, map, constrain, millis). The code is original and written for this tutorial.

Calibrating the Sensor (Important)

  1. Upload any sketch that prints analogRead(A0), or temporarily print raw in the code below.
  2. Hold the sensor in dry air and note the value (typically 500–600). Put it in DRY_VALUE.
  3. Dip the sensor in a glass of water up to the line (never past the electronics) and note the value (typically 250–300). Put it in WET_VALUE.
  4. Upload the final code. 0 % now means your dry reading and 100 % your wet reading.

Complete Arduino Code

// Automatic Plant Watering System - Arduino Uno + Capacitive Soil Moisture Sensor + Relay + Pump
// No external libraries needed
const int SOIL_PIN  = A0;   // sensor AOUT
const int RELAY_PIN = 7;    // relay IN
const bool RELAY_ACTIVE_LOW = true;

// Calibrate these two values for YOUR sensor (see tutorial)
const int DRY_VALUE = 520;  // reading in dry air / dry soil
const int WET_VALUE = 260;  // reading in a glass of water

const int START_PUMP_BELOW = 35;  // % moisture: start watering
const int STOP_PUMP_ABOVE  = 60;  // % moisture: stop watering
const unsigned long MAX_PUMP_MS = 15000UL;  // safety: max 15 s per cycle
const unsigned long SOAK_MS     = 60000UL;  // wait 60 s for water to spread

bool pumpOn = false;
unsigned long pumpStart = 0, lastStop = 0;

void setPump(bool on) {
  pumpOn = on;
  digitalWrite(RELAY_PIN, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW);
}

int readMoisturePercent() {
  long sum = 0;
  for (int i = 0; i < 10; i++) { sum += analogRead(SOIL_PIN); delay(5); }
  int raw = sum / 10;
  int pct = map(raw, DRY_VALUE, WET_VALUE, 0, 100);
  return constrain(pct, 0, 100);
}

void setup() {
  Serial.begin(9600);
  pinMode(RELAY_PIN, OUTPUT);
  setPump(false);
}

void loop() {
  int moisture = readMoisturePercent();
  unsigned long now = millis();

  if (!pumpOn && moisture < START_PUMP_BELOW && (lastStop == 0 || now - lastStop > SOAK_MS)) {
    setPump(true);
    pumpStart = now;
  } else if (pumpOn && (moisture > STOP_PUMP_ABOVE || now - pumpStart > MAX_PUMP_MS)) {
    setPump(false);
    lastStop = now;
  }

  Serial.print("Moisture: ");
  Serial.print(moisture);
  Serial.print("%  Pump: ");
  Serial.println(pumpOn ? "ON" : "OFF");
  delay(500);
}

Code Explanation

  • readMoisturePercent() averages 10 readings to reduce noise, maps the raw value between your dry and wet calibration points, and clamps the result to 0–100 %.
  • Hysteresis: the pump starts below 35 % and stops above 60 %. Change these for your plant (succulents like it drier, ferns wetter).
  • MAX_PUMP_MS stops the pump after 15 seconds even if the sensor still says dry – this protects against a sensor that has fallen out of the pot.
  • SOAK_MS waits 60 seconds after watering before the pump may start again, because water takes time to reach the sensor.
  • setPump() supports both active-LOW and active-HIGH relay modules via RELAY_ACTIVE_LOW.

Step-by-Step Instructions

  1. Wire the sensor and relay to the Arduino as in the table.
  2. Wire the pump circuit separately: supply + → relay COM, relay NO → pump +, pump − → supply −.
  3. Calibrate the sensor and update DRY_VALUE and WET_VALUE.
  4. Upload the code and open Serial Monitor at 9600 baud.
  5. Put the sensor in dry soil – the relay should click and the pump should run.
  6. Pour some water or move the sensor to wet soil – the pump stops once moisture is above 60 %.
  7. Place the pump in the water container and route the tube to the base of the plant. Push the sensor into the soil about 5 cm from the stem, up to the white line.
  8. Watch it for a full day and fine-tune the thresholds and MAX_PUMP_MS for your pot size.

Troubleshooting

ProblemFix
Moisture stuck at 0 % or 100 %Calibration values wrong or swapped; re-measure dry and wet readings.
Arduino resets when pump startsPump is drawing current from the Arduino – use a separate supply for the pump.
Pump runs when it should be offRelay is active-HIGH: set RELAY_ACTIVE_LOW = false.
Readings drift over daysSeal the top electronics of the sensor with hot glue or nail polish to keep water out.
Pump hums but no waterPump must be fully submerged and primed; check the tube is not kinked.

Upgrade Ideas

  • Use an ESP32 to send moisture levels to your phone and get “tank empty” alerts.
  • Add a float switch or ultrasonic sensor to stop the pump when the water tank is empty.
  • Control several plants with multiple sensors and a 4-channel relay.
  • Run it on a solar panel and battery for a balcony garden.

Frequently Asked Questions

Can I use the cheap resistive soil sensor?

Yes, the code works with it too, but resistive probes corrode quickly. If you use one, power it from a digital pin and turn it on only while reading.

How often does the plant get watered?

Only when moisture drops below 35 %. In practice that may be once a day or once a week, depending on the plant, pot and weather.

Can I power the pump from the Arduino 5V pin?

Not recommended – even small pumps draw 100–300 mA with large start-up spikes that can reset the Arduino. Use a separate supply.

Can I water multiple plants?

Yes. Use one sensor per pot (A0, A1, A2…) and one relay or a drip line with several outlets.

Related Projects

Browse more Arduino Projects on Arduino Project Hub.