Historical Arduino energy-saving system overview, Arduino energy control, doorway counting, infrared sensors

Intelligent Energy Saving System

2.5K Views
40
700
60
25
60
PCBWay

Hello friends! Today we will build an intelligent energy-saving demonstration using an Arduino Uno, two doorway sensors, an LCD and controlled loads. The idea is to count completed entries and exits, then switch the model room's loads according to that count.

The interesting part is not simply turning a relay on. We need to recognize direction, handle an interrupted crossing, avoid counting the same person repeatedly and decide what to do when the count becomes uncertain. We will develop those rules before looking at the complete program.

This is a controlled educational demonstration. Two narrow beams cannot reliably count a crowd or guarantee that a real room is empty. We will use low-voltage demonstration loads and make the limitations visible rather than treating an imperfect counter as an unquestionable occupancy sensor.

Historical Arduino energy-saving system overview, Arduino energy control, doorway counting, infrared sensors
Figure: Historical Arduino energy-saving system overview.

How the System Works

Place beam A on the outside of the doorway and beam B slightly farther inside. A person entering encounters A before B; a person leaving encounters B before A. Neither sensor is permanently an “entry sensor” or an “exit sensor.” Direction comes from their sequence.

For the program in this tutorial, choose the spacing so a single crossing normally blocks both beams during part of the passage. A complete entry is A only, both blocked, B only, then both clear. Exit follows the reverse sequence.

This overlap requirement is deliberate. If the geometry permits a person to clear A completely before reaching B, the state machine below will reject the sequence. Change the mechanical arrangement or design a different sequence recognizer rather than silently assuming the code covers every doorway.

ConditionDemonstration response
Complete entryIncrease the count once
Complete exit with a positive countDecrease the count once
Known zero count and clear doorwaySwitch loads off after a short grace interval
Ambiguous sequence or timeoutMark count uncertain and keep demonstration loads on
StartupRequire manual confirmation of an empty room

The conservative “on when uncertain” policy favors avoiding a false empty-room decision in this model. It does not make the system suitable for emergency lighting, protective equipment or other loads whose operation must not depend on this counter.

Components and Pin Assignment

The original project used an Uno, infrared sensing stages, an LCD, relay circuits, a buzzer and a 7805 supply stage. Its earlier description mentioned a 16 by 2 display, while the full program used a 20 by 4 layout. The revised full example consistently uses a 20 by 4 parallel LCD.

FunctionUno pin or connection
Beam A digital outputA0, active-low blocked signal
Beam B digital outputA1, active-low blocked signal
Lighting relay inputA5
Fan relay inputA4
Active buzzer driver inputA3, active-low in this example
LCD RS and EnableD12 and D11
LCD data D4 through D7Arduino D5, D4, D3 and D2
Serial diagnosticsUSB serial at 9600 baud

The old complete schematic routes sensor signals differently in places. Follow this table for the revised program and update the model connections accordingly. Analog-labeled Uno pins can serve as ordinary digital inputs and outputs in this application.

Connect and Test the LCD First

Parallel LCD wiring used for the display test, Arduino energy control, doorway counting, infrared sensors
Figure: Parallel LCD wiring used for the display test.

The display uses the standard parallel interface in four-bit mode. Connect its read/write input to ground for write-only operation, provide the specified supply and set contrast using the module's recommended arrangement. The LCD's backlight may require a current-limiting resistor unless the module already includes one.

Historical LCD startup test output, Arduino energy control, doorway counting, infrared sensors
Figure: Historical LCD startup test output.

The retained LCD test images demonstrate a simple text check. For the full project, initialize the display with lcd.begin(20, 4). If you choose a 16 by 2 module instead, redesign the displayed information rather than writing to rows that do not exist.

Our LCD and Arduino circuit tutorial provides the wiring background. The Arduino LiquidCrystal library supplies the display interface used below.

Relay Outputs and Low-Voltage Loads

Two-channel active-high relay driver schematic, Arduino energy control, doorway counting, infrared sensors
Figure: Two-channel active-high relay driver schematic.

The historical relay diagram is active-high: its input LED is driven when the logic source is high. Some commercial relay modules are active-low. The code therefore keeps relay polarity in one constant instead of assuming that every module works the same way.

Use a suitable transistor or driver for the relay coil, a defined off-state bias and an appropriate flyback path for a DC coil. The Arduino pin should drive the interface, not supply the coil current directly. Confirm the relay's contact rating for the actual load type, including inrush.

The original example listed 100 W lamps and a 12 V fan. An incandescent lamp is primarily resistive during steady operation and has cold-filament inrush; a fan has different electrical behavior. Calling both loads simply “inductive” hides those differences.

For the first build, use low-voltage lamps or LEDs with suitable drivers and a low-voltage fan. The retained relay drawing does not specify a complete mains installation. Keep the learning task focused on counting and control without treating a breadboard schematic as a mains wiring plan.

Add the Buzzer and Beam Inputs

Historical buzzer driver states, Arduino energy control, doorway counting, infrared sensors
Figure: Historical buzzer driver states.

The buzzer indicates an uncertain count with a short periodic beep. Use the corrected current-limiting and bias guidance in our Proteus buzzer tutorial. A generic optocoupler symbol is not a pin-for-pin replacement for a physical PC817.

Infrared detector stage for doorway sensing, Arduino energy control, doorway counting, infrared sensors
Figure: Infrared detector stage for doorway sensing.

The original optical stage can be studied in our 555 timer infrared-sensor tutorial. For this program, the required interface is a stable digital signal that goes low while the beam is blocked. Verify that polarity on the actual sensor.

Button-controlled beam-interruption simulation, Arduino energy control, doorway counting, infrared sensors
Figure: Button-controlled beam-interruption simulation.

Buttons can represent those digital states in a logic simulation: connect each input to ground when pressed and use INPUT_PULLUP. Buttons do not reproduce optical alignment, ambient-light effects or a person's geometry, so a successful button test is only a test of the sequence logic.

Why the Old Blocking Loops Need Replacing

A loop such as while(sensorIsBlocked) waits indefinitely if a sensor remains blocked or a wire holds the input low. During that wait, the program cannot service the other beam, refresh the display or respond normally to another event.

We will instead remember the current crossing state and return to loop after every check. A five-second sequence deadline rejects a crossing that never finishes. Short input qualification reduces contact bounce in the button simulation and brief signal flicker.

An exit when the count is already zero is also suspicious. Silently forcing a negative count back to zero conceals the problem. The revised program marks the count uncertain, just as it does for a simultaneous first blockage or an invalid reversal.

Complete Arduino Demonstration Code

This sketch starts in the uncertain state. After confirming the model room is empty and both beams are clear, send the lowercase character z from the Serial Monitor to establish a zero count. Use that command only when the physical condition is actually known.

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const byte LIGHT_PIN = A5, FAN_PIN = A4, BUZZER_PIN = A3;
const bool RELAY_ACTIVE_HIGH = true; // Matches the historical relay drawing.
const unsigned long QUALIFY_MS = 20, CROSSING_MS = 5000, OFF_DELAY_MS = 10000;

struct Beam {
  byte pin;
  bool raw = false, blocked = false;
  unsigned long changed = 0;
  Beam(byte inputPin) : pin(inputPin) {}
  void begin() {
    pinMode(pin, INPUT_PULLUP);
    raw = blocked = (digitalRead(pin) == LOW);
    changed = millis();
  }
  void update(unsigned long now) {
    bool value = digitalRead(pin) == LOW;
    if (value != raw) { raw = value; changed = now; }
    if (now - changed >= QUALIFY_MS) blocked = raw;
  }
};
Beam a(A0), b(A1);

enum State { IDLE, ENTRY_A, ENTRY_BOTH, ENTRY_B,
             EXIT_B, EXIT_BOTH, EXIT_A };
State state = IDLE;
unsigned int people = 0;
bool uncertain = true;
unsigned long crossingStarted = 0, zeroSince = 0, lastDisplay = 0;

void setLoad(byte pin, bool on) {
  digitalWrite(pin, on == RELAY_ACTIVE_HIGH ? HIGH : LOW);
}

void fault() {
  uncertain = true;
  state = IDLE;
  Serial.println("Count uncertain: inspect the room and sensors.");
}

void countCrossing(unsigned long now) {
  if (uncertain) return;
  bool A = a.blocked, B = b.blocked;
  if (state != IDLE && now - crossingStarted >= CROSSING_MS) {
    fault(); return;
  }
  switch (state) {
    case IDLE:
      if (A && B) fault();
      else if (A) { state = ENTRY_A; crossingStarted = now; }
      else if (B) { state = EXIT_B; crossingStarted = now; }
      break;
    case ENTRY_A:
      if (A && B) state = ENTRY_BOTH;
      else if (!A) fault();
      break;
    case ENTRY_BOTH:
      if (!A && B) state = ENTRY_B;
      else if (!B) fault();
      break;
    case ENTRY_B:
      if (A) fault();
      else if (!B) {
        if (people < 999) { ++people; state = IDLE; }
        else fault();
      }
      break;
    case EXIT_B:
      if (A && B) state = EXIT_BOTH;
      else if (!B) fault();
      break;
    case EXIT_BOTH:
      if (A && !B) state = EXIT_A;
      else if (!A) fault();
      break;
    case EXIT_A:
      if (B) fault();
      else if (!A) {
        if (people > 0) { --people; state = IDLE; }
        else fault();
      }
      break;
  }
}

void blankRow(byte row) {
  lcd.setCursor(0, row);
  lcd.print("                    ");
  lcd.setCursor(0, row);
}

void setup() {
  Serial.begin(9600);
  setLoad(LIGHT_PIN, false);
  setLoad(FAN_PIN, false);
  digitalWrite(BUZZER_PIN, HIGH);
  pinMode(LIGHT_PIN, OUTPUT);
  pinMode(FAN_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  a.begin(); b.begin();
  lcd.begin(20, 4);
  zeroSince = millis();
  Serial.println("After confirming an empty room and clear beams, send z.");
}

void loop() {
  unsigned long now = millis();
  a.update(now); b.update(now);
  if (Serial.available()) {
    char command = Serial.read();
    if (command == 'z' && !a.blocked && !b.blocked
        && !a.raw && !b.raw
        && now - a.changed >= QUALIFY_MS
        && now - b.changed >= QUALIFY_MS) {
      people = 0; uncertain = false; state = IDLE; zeroSince = now;
      Serial.println("Confirmed empty baseline accepted.");
    }
  }
  countCrossing(now);
  if (people > 0 || state != IDLE || uncertain) zeroSince = now;
  bool loadsOn = uncertain || people > 0 || state != IDLE
                 || now - zeroSince < OFF_DELAY_MS;
  setLoad(LIGHT_PIN, loadsOn);
  setLoad(FAN_PIN, loadsOn);
  bool beep = uncertain && now % 2000UL < 150UL;
  digitalWrite(BUZZER_PIN, beep ? LOW : HIGH);

  if (now - lastDisplay >= 250) {
    lastDisplay = now;
    blankRow(0);
    if (uncertain) lcd.print("Count: UNKNOWN");
    else { lcd.print("People: "); lcd.print(people); }
    blankRow(1); lcd.print(loadsOn ? "Lights/Fan: ON" : "Lights/Fan: OFF");
    blankRow(2); lcd.print("A:"); lcd.print(a.blocked ? "BLOCK " : "CLEAR ");
    lcd.print("B:"); lcd.print(b.blocked ? "BLOCK" : "CLEAR");
    blankRow(3); lcd.print(uncertain ? "Inspect; empty: z" : "Counting ready");
  }
}

Understand the Program's Boundaries

The 20 ms input qualification and five-second crossing deadline are example settings for a slow demonstration. They are not universal human-motion constants. Test them against the intended sensor spacing and crossing speed.

The counter changes only when the complete sequence finishes and both beams clear. It does not count on the first interruption. An invalid reversal deliberately produces an uncertain state because this small example does not attempt to infer every possible movement.

The ten-second off delay starts when the known count reaches zero and no crossing is in progress. A new crossing keeps the loads on while its direction is being resolved. All elapsed-time checks use unsigned subtraction.

During uncertainty, the stored number is not displayed as authoritative. The demonstration loads remain on and the buzzer reminds the operator to inspect the room. Resetting the microcontroller also loses the baseline and returns to uncertainty.

The output initialization only applies once setup runs. External bias and the driver circuitry must define behavior during reset and power loss. A normally open relay contact will not stay energized without coil power, regardless of the software's “keep on” policy.

Complete Circuit and Simulation

Historical full schematic requiring revised pin mapping, Arduino energy control, doorway counting, infrared sensors
Figure: Historical full schematic requiring revised pin mapping.

The retained full schematic provides the historical system overview. Align it with the revised pin table, LCD dimensions and chosen relay polarity before loading the new program. Use the related Arduino Library for Proteus instructions when setting up the controller model.

Compile for the Uno, select the resulting program file and use the expected clock. Connect a Virtual Terminal if you want to issue the z baseline command in simulation. Match its baud rate to 9600 and connect both transmit and receive directions appropriately.

Input sequence after baselineExpected result
A, both, B, clearCount increases once
B, both, A, clear with positive countCount decreases once
Both blocked as the first eventCount becomes uncertain
A blocked longer than five secondsTimeout and uncertainty
Exit sequence when count is zeroUncertainty instead of a hidden negative count
Reset while someone is insideUnknown baseline; no automatic claim of an empty room

Hold each button state long enough to pass input qualification. A program that rejects an impossible or ambiguous sequence is behaving intentionally; do not remove the checks just to make arbitrary button presses increment the display.

Optional Temperature Display

The older program also referenced a DS18B20 on D8, although temperature was not used to decide the fan state. If you retain that feature, initialize the OneWire and DallasTemperature interfaces correctly and keep the sensor pin separate from doorway inputs.

The DS18B20 datasheet specifies resolution-dependent conversion time. A 12-bit conversion can take up to 750 ms; blocking doorway processing for that interval can miss a passage.

The DallasTemperature library supports asynchronous conversion. With an appropriately powered sensor, request a conversion, continue processing beams and read the result after its required interval. Handle disconnects and invalid readings explicitly. The main sketch above omits this optional feature to keep the counting behavior self-contained.

Estimate the Energy Saving

Energy is power multiplied by time: E(kWh) = P(W) × t(hours) / 1000. For an illustrative pair of 100 W lamps and a 20 W fan, the total is 220 W. Avoiding three hours of unnecessary operation would save 0.66 kWh before accounting for the controller's own consumption.

If the complete control system consumes an average of 2 W continuously, it uses 0.048 kWh per day. Under those illustrative conditions, the net daily saving is about 0.612 kWh. These figures are a worked example, not measured savings from the original project.

Use actual measured load power and realistic unused time for your own estimate. Relay coils that stay energized, a backlit LCD and an inefficient supply can reduce the benefit when controlling small loads. Compare complete-system energy, not just the Arduino board's current.

The original article linked to an energy-cost comparison resource. A tariff comparison concerns price per unit; this project concerns reducing units consumed. Keep those two effects separate when reporting a result.

Include the Power Supply in the Calculation

If a 7805 drops 12 V to 5 V while supplying 100 mA to the control electronics, its approximate dissipation is (12 − 5) × 0.1 = 0.7 W. The electronics receive 0.5 W while the regulator releases about 0.7 W as heat, ignoring its own additional current. That matters in a project whose purpose is to reduce consumption.

Choose the supply from the actual current budget, including LCD backlight, sensors and any relay coils it powers. Keep coil-current pulses out of sensitive sensor return paths where possible, and provide appropriate local decoupling. A controller that resets when a relay changes state can lose the occupancy baseline repeatedly.

The 7805's presence in the original parts list is not evidence that every load can be powered through it. A 12 V fan belongs on a suitable 12 V supply branch; the regulated 5 V rail serves compatible control circuitry. Verify thermal conditions rather than relying only on the regulator's headline current rating.

Measure Counting Performance Separately from Energy

Use a controlled test record with a known starting count. Ask one participant to complete a defined number of entries and exits, then compare the displayed count with an independent tally. Record rejected sequences as well as accepted ones. A counter that rejects most normal crossings is different from one that silently accepts incorrect crossings.

Include slow passages, pauses between beams, a turnaround, a carried bag and a blocked sensor. Then test the conditions the simple model cannot resolve, such as two people close together. The purpose is to identify the operating boundary, not to claim success from one carefully timed crossing.

Do not report an energy-saving percentage without defining the baseline. If the lights would already have been switched off manually, automatic control saves little additional energy for that interval. Conversely, if the system spends much of the day in its uncertain state with loads on, the theoretical saving may not occur.

A useful report contains load power, baseline operating hours, controlled operating hours, controller consumption and the number of manual corrections. Those observations connect the counter's performance to the energy result instead of assuming that correct software structure guarantees lower consumption.

Plan Manual Override and Recovery

The serial z command is suitable for a bench demonstration, where an operator can inspect the model room. A deployed controller would need an accessible, deliberate reconciliation method and clear feedback about whether the count is trusted.

A manual override should have a defined priority over automatic switching and an obvious indication while active. It should not merely alter the internal count to force the desired output, because that would mix an operator command with a measurement estimate. Keep those two states separate when extending the design.

Saving the count to nonvolatile memory does not fully solve recovery after power loss. People may cross while the controller is unpowered, and frequent writes can wear out EEPROM. Decide how the baseline is re-established after an interruption rather than trusting the last saved number indefinitely.

Project Review and FAQs

The project is useful for learning state machines, digital inputs, display updates and load control. Its central limitation is that doorway events are only an estimate of occupancy. Tailgating, two people passing together, another entrance or sensor obstruction can invalidate that estimate.

The retained video documents the original project. Its wiring, display and software behavior may differ from the revised demonstration, particularly the uncertainty handling and nonblocking sequence logic.

Why not set the count to zero every time the board starts?

A reset does not empty the room. Starting with an unknown baseline avoids treating lost memory as evidence of zero occupants.

Can I use this to control a real room immediately?

First evaluate sensor coverage, manual override, fault behavior and electrical installation requirements. The demonstration is not a reliable occupancy guarantee and should not control essential loads.

Why does reversing halfway cause an error?

The example accepts a specific complete crossing pattern. A more capable recognizer can handle additional patterns, but each one needs clear rules and tests rather than an assumption that every interruption represents a person.

Does temperature control the fan?

No. In the main example, both loads follow the estimated occupancy state. Temperature-based fan control would be a separate rule with its own sensor validation and hysteresis.


Comments

33

Join the conversation

Reply1

Hi nasir,I would like to do the project in pure C. Can you please give information on how I can upload pure C code to Arduino Uno?

1 reply
Reply3

Hello Msr. Syed Zain Nasir.You have done great work.Congratulation!!!
I want to make a question.Can i replace IR sensors (transmitter + reciever circuits) with IR Obstacle avoidance sensors,which i can buy easily.It will be compatible with other part of the system or not?If it doesn't work,what type of IR sensors,do you advice me to buy?Please,i need your help.Thank you.

1 reply
Reply3.1
Replying to adiono

Hi,

The IR sensor I have used in this project is digital, which gives either 1 or 0, so you can use any digital IR sensor here but if you have analog type then you need to do some changes in it. IF you are having problem with your project, then add me on Skype and we will discuss it in detail.

Thanks.

1 reply
Reply5

Hello.What Circuit is inside IR RX?At first,i thought that was the circuit that is shown below (in the photo that is here) but i am not sure.My question is:If it is the circuit that you have design to replace IR Rx,which terminal can i connect to Arduino?From the terminal of LED?
Thank you.

1 reply
1 reply
1 reply
Reply11

Hey can you help me with some error messages I got when I uploaded my Arduino code. I got the error message as it follows:

fatal error: DallasTemperature.h: No such file or directory

#include

^

compilation terminated.

Using library LiquidCrystal at version 1.0.7 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal
exit status 1
Error compiling for board Arduino/Genuino Uno.

Thank you in advance :)

1 reply
Reply11.1
Replying to adiono

Hi,

You haven't added the Dallas Temperature Library for Arduino. You need to download this library from above tutorial or from Arduino's official site and then place it in the Library folder of your Arduino software. Now restart your software & compile the code. This time, it won't behave ugly. :P

Thanks. :)

1 reply
Reply13

Mostly people leave the public place without turning off lights or fans which are the wastage of energy, in this era of energy crises we need some latest technology to save energy. What system or technology we have to follow in our daily routine for energy saving at public places? How can we utilize this project at public place?

Reply14

Well-done! Good work as always, clear me please which sensors will be more suitable if we talk about automatic energy saving system? I have some more points to ask from you, How these sensors will work in detecting the number of people in the room and where did you fix those sensors for detecting people at front of door or not? Please share a clear image of IR sensor diagram?

Reply15

Could we interface the 21 inch LCD with arduino or not for this project? How the LCD will show the counter of people? My LCD is only showing the number of people entering the room, the number of leaving the room is not displaying on screen? How can I solve this problem? Kindly give me the solution.

Reply16

I am working on energy saving project at public place ,so I need your help. In this article you have mentioned IR sensors as one of its components, tell me how these sensors work in this system, how it senses some one’s position and start counting the number of people at entering and leaving place? How many sensors we must use in designing energy saving system at public place for the correct detection of people?

Reply17

Hi! Very fruitful article and the project you have made is a need of time. There are many types of capacitors in market, you didn’t mention which one will save more energy, do their sizes (large, small) matter or not? One thing more can we use these capacitors to save our money by reducing our electricity bills?

Reply18

Congratulations! your articles are superb. Please share the diagram of 2 relay board too. Can we use any other alternative of relay? Thank you !

Reply19

In energy saving project you have also used buzzer, I want to ask why did you use it in circuit ,what’s its purpose in such kind of project, also clear one thing more how electricity will make it to work?, I want to ask will it give its beep as a signal of warning?

Reply20

Hello! The given codes are not working ,please help me out. Will be thankful for your quick response. Kindly clear it too do some specific fans with specific voltage are required for this system when it comes to automatically turn on or off ,either they are AC or DC? What‘s the limit of people you had set for turning on and turning off the lights and fans automatically? If there are 4 to 5 persons at room and its sleeping time means its night then will the lights turn off automatically or we have to turn them off by ourselves?

Reply21

Brilliant job! Your project is so good for energy saving at home as well as at public areas but there may be some cases which can trigger the system. Suppose if two persons enter into the room or leave the room at same time without any gap then will the sensors detect them one person or two ?One more confusion if any pet enters or leaves the room then will it be detected or not?

Reply22

Hey man! Help me to find out What are the programs I can use in designing
energy saving system in public library, should I follow the same procedure or
there will be some modifications? And also tell me how can I assess the energy is
saving? How can I calculate that how much it is saving?

1 reply