Blog

  • ESP32 Cam For Home Automation

    ESP32 Cam For Home Automation

    Introduction

    The ESP32-CAM is one of the most versatile and affordable boards for building a home automation system. With built-in Wi-Fi and an onboard camera, it allows you to control appliances remotely while also monitoring your home in real time. This project focuses on how to use the ESP32-CAM as the central control unit for home automation—handling switching operations and offering camera surveillance from anywhere.

    Whether you’re turning lights ON/OFF, activating a fan, or checking your home remotely, the ESP32-CAM provides a smart and efficient solution.

    In today’s tutorial, we step into the world of IoT (internet of things) automation and surveillance using Arduino and ESP32 cam for home automation. This tutorial ESP32 Cam for home automation focuses on trying to blink the AC light bulb using the GPIO pin of the esp32-cam. This is on the path that leads to using ESP32 Cam to do home automation and surveillance.

    This will allow us to control home actuators like light bulbs, ventilation fans, AC load-point sockets and still be able to stream video footage remotely from anywhere in the world. Already, we know that we can stream video surveillance using the esp32-cam, the focus now is to also control AC actuator or actuators in other to complete the task in the home automation. Once we can be able to control or blink the AC light bulb on and off, we can as well do home automation using ESP Wi-Fi in IoT. To get started, the following materials are needed.

    Materials/Components for ESP32 Cam for Home Automation

    Breadboard…buy here

    5V solid-state relay…buy here

    PCB socket

    Preformed jumper wires… buy here

    A pair of screwdrivers

    ESP32-Cam development board…buy here

    A pair of  LEDs (red and green color types)… buy here

    ESP32-CAM  programmer… buy here

    AC wireless plug

    AC light bulb (energy-saving type)

    Current limiting resistor 220kOhms

    ESP32 Cam for Home Automation: Circuit Diagram  

    Using ESP32 Cam for home Automation
    Circuit diagram

    The circuit diagram shown above is the schematic for the ESP32 cam LED blinking. The diagram makes use of the Programmer to power the ESP32 Cam development board. The circuit diagram of the ESP32 cam connection depicts two connections of LEDs to its GPIO (general purpose input output) pins. One for turning the red LED. The red LED was used to know when the ESP-32 Cam was powered on whereas the green LED was used to show the blinking state. The red LED was connected to GPIO pin 4. A current limiting resistor was connected in series to the green LED. 

    Connection On the Breadboard

    The schematic of this Arduino home automation was assembled on a breadboard because it was easier to correct any mistake that is made on it than when it was soldered on a Veroboard. To know more about how to use a breadboard, kindly search on Google or leave us a message in the comment section.

    How to breadboard circuit diagram
    How to breadboard circuit diagram of ESP32 cam to LED

    The connection was done by connecting the anode of the green LED to the GPIO pin 4 of the ESP32 Cam dev board and using a current limiting resistor to connect the Cathode of the LED to the ground.  The same procedure was repeated for the red LED. Except that the red LED anode pin was connected to GPIO 2 on the ESP32 Cam. Some preformed jumper wires were used to finish the connection whereas the power rails, 5V, and GND sources were drawn from the ESP32 cam programmer DC power rail pins.

    Alternatively, the onboard LED of the ESP32 cam development board can equally be used. However, care must be taken to change this pin assignment in the Arduino sketch given below. To use this, the sketch below is used. Refer to the YouTube video for this demonstration. 

    The Arduino Source Code And Explanation.

    //define and declare where the LEDs are connected on the ESP32 cam
    #define redLedPin 12
    #define greenLedPin 4
    
    void setup(){
    //make these LEDs as outputs
    pinMode(redLedPin, OUTPUT);
    pinMode(greenLedPin, OUTPUT);
    
    //turn the red LED permanently on
    digitalWrite(redLedPin, HIGH);
    }
    
    void loop(){
    //blink the green LED
    digitalWrite(greenLedPin, HIGH);
    delay(1000);
    digitalWrite(greenLedPin, LOW);
    delay(1000);
    }
    

    For this home automation using ESP32 cam, the pin on is ESP32 Cam, where the green LED, was connected was assigned a variable greenLedPin. And this was declared to be GPIO pin 4 on the ESP32 Cam board. The setup function made these pins outputs. The next line of code calls the red LED to be permanently turned on after this; whereas in the loop function, the green LED was blinked every second.

    Blinking the AC Light Bulb

    Circuit diagram of ESP32 Control of AC light bulb
    circuit diagram of ESP32 Cam with AC bulb

    The circuit diagram of the DIY (Do-It-Yourself) AC bulb blinking light is shown above.  The schematic showed that a 5V solid-state relay was connected to GPIO pin 14. The anode of the 5V solid state relay was connected directly to this GPIO pin on the ESP32 Cam for home automation. This would work since we are trying to cut off AC voltages during the digital LOW state of the ESp32 Cam development board and allow AC voltages to flow through during the digital HIGH of the state of the ESP32 cam.

    The above method of connecting the anode of the 5V solid state relay to the Control GPIO pin of the ESP32 Cam may not always work for some cases. This can be solved by using an NPN transitor. For this demonstration, we used the famous TIP41C transistor. This done according to the Arduino sketch below, would create a blinking bulb with relay.

    The J1 header pin is where the AC light bulb lamp holder is connected and the AC ight bulb is connected or screwed for lighting effect.

    The Arduino Sketch

    //define and declare where the LEDs are connected on the ESP32 cam
    #define redLedPin 12
    #define greenLedPin 4
    //define and declare where the relay anode pin is connected
    #define relayPin 14
    
    void setup(){
    //make these LEDs as outputs
    pinMode(redLedPin, OUTPUT);
    pinMode(greenLedPin, OUTPUT);
    //make the relay pin an output
    pinMode(relayPin, OUTPUT);
    
    //turn the red LED permanently on
    digitalWrite(redLedPin, HIGH);
    }
    
    void loop(){
    //turn on the green LED for 1 sec
    digitalWrite(greenLedPin, HIGH);
    //turn on the AC light bulb for 1 sec
    digitalWrite(relayPin, HIGH);
    delay(1000);
    //turn off the AC light bulb for 1 sec
    digitalWrite(relayPin, LOW);
    digitalWrite(greenLedPin, LOW);
    delay(1000);
    }
    

    The Result:

    Blinking AC light bulb using ESp32 Cam and Arduino
    Blinking AC light bulb using ESp32 Cam and Arduino

    The AC light bulb blinked every second. This means that we have successfully controlled the On-state and the Off-state of the AC light bulb. Thereby making it blink. The next thing is to make this remotely controlled using the Wi-Fi of the ESP32 cam. 

    Conclusion

    So far we have learnt how to use Arduino and ESP32 Cam For Home Automation. Feel free to drop any questions in the comment section. Thank you.

  • How To Generate Electricity using foot-steps with backup charging station (Piezoelectric generator) Project

    How To Generate Electricity using foot-steps with backup charging station (Piezoelectric generator) Project

    In today’s project design, we made a footstep to electricity project that focused on how to generate electricity using foot-steps with a backup charging station (Piezoelectric generator) project. We can use this to charge devices such as smartphones, tablets, and any 5V-rated rechargeable appliance. This foot-step power generation project is a typical example of an electricity generator tile project. And this tutorial goes further than just generating electricity using footsteps but adds a DC-based backup charging station with charging and full charging indicators. Ensure you read until the end to get a full grasp of how it was designed and built. Watch the full video demo here.

    Watch Video tutorial

    Project Materials/Components

    Arduino Nano board Buy here
    Piezoelectric transducer sensors buy here

    Multimeter buy here

    16x4 LCD module buy here

    LCD wire and connector sockets
    10kΩ potentiometer buy here

    USB connector

    Bottle water caps
    Some stranded 1mm wire
    glue sticks buy here

    Glue gun 20W

    3” x 6 “  adaptable box

    Bridge rectifier

    LiPo charging Module

    Wires
    shrink tubes b
    Chat and order for the complete kit of this here

    Introduction

    The piezoelectric sensors, also known as PZT ceramic sensors work on the principle of piezoelectric effect, which means that the sensors can convert mechanical stress (either pressure or stress) into electricity.  Read more about this here.

    The type of PZT ceramic sensors used for this project is shown below. The footstep power generation using piezoelectric sensors project won’t be possible without these PZT ceramic sensors. Each sensor has a pair of wires attached to it. The red-colored wire and the black wire. These should represent the positive and negative polarities of the sensor. However, this isn’t the case when in the piezoelectric generator circuit diagram.

    How To Generate Electricity using foot-steps
    Measuring the voltage generated by each PZT sensor

    When mechanical stress (in the form of applied pressure or impact stress) is applied directly to any of the PZT ceramic sensors, it generates an AC voltage signal. This can be measured by the digital multimeter as shown above. A single piezoelectric sensor of this type can generate up to 6V under the right amount of mechanical stress. This was why this sensor was ideal for our electricity generation from pressure project design.

    Assembling the Piezoelectric Sensors

    The best way to get the most out of the PZT sensors was to assemble or configure the piezoelectric sensors in a node analysis configuration. That is, both series and parallel in configuration. Having a total of 18 PZT ceramic sensors, the connections were made according to the circuit diagram below.

    How To Generate Electricity using foot-steps
    The configuration of the PZT ceramic sensors

    The circuit diagram for the foot step power generation system using piezoelectric sensors showed the connection of the PZT ceramic sensors was connected in both series and parallel modes. There were 3 serially placed PZT sensors, and each of these serial connections (rows) was in turn placed in parallel with 5 other rows of 3 series-connected PZT ceramic sensors. The reason for this mode of configuration was to amplify the voltage output in the series connection and the current in the parallel connection. The series connection of these sensors would increase the overall voltage. A series connection of 3 PZT ceramic sensors can output up to 25V AC when an even force is applied across the sensors. However, the series-connected PZT sensors are susceptible to having an “open circuit” when either of the PZT ceramic sensors breaks or fails during use. Each of these sensors in real life is fragile and can break if the applied pressure is not even around the surface.  This means that the series voltage output won’t be realized because of one damaged sensor in the series connection.
    By using a configuration of both series and parallel, we try to minimize this voltage loss such that, the rows not affected can still output voltage in this how to generate electricity using foot-steps with backup charging station (piezoelectric generator) project or advanced footstep power generation system.

    Rectification and Filtration of the Alternating Current (AC) Voltage.

    How To Generate Electricity using foot-steps
    Adding a Bridge Rectifier Components to the Piezoelectric generator

    The output voltage of the piezoelectric generator is AC-based, and we intend to use it to power DC loads. To achieve this, the bridge rectifier was used to convert the AC signal to DC signal. The bridge rectifier component makes life easier than using the full wave configuration of 4 diodes.  Once the rectification was done, further filtration of AC ripples was done using a 100µF 35V electrolytic capacitor. 

    Piezoelectric sensors naturally generate AC voltage, which must be converted to DC before it can charge a battery or power electronics. This is where the rectification stage comes in.

    A bridge rectifier converts the alternating pulses into a smoothed DC output. However, the rectified voltage still contains ripples, so a large electrolytic capacitor is added as a filter to stabilize the voltage. This filtered DC power becomes the usable output for charging and storage.

    Generate Electricity using foot-steps: Adding Backup battery

    How To Generate Electricity using foot-steps
    3.7V LiPo battery

    The generation of electricity using footstep project design needed a backup battery. This would serve as a backup when the piezoelectric generator was not producing voltage. This backup battery is made up of 3 pieces of 3.7V 3800mA LiPo batteries all connected in series. This battery configuration gave a resultant voltage of 11.1V.

    Recharging Backup Battery.

    To recharge the backup battery, a constant current charging method was used to recharge the backup battery. By practical measurement, the output of this piezoelectric generator circuit diagram was found to range from 10V to 15V. The voltage from the PZT circuit was connected through a current limiting resistor of 1kΩ which was then connected to the now 11.1V LiPo batteries.

    Adding A DC Based Charging Station.

    How To Generate Electricity using foot-steps
    DC-DC Buck converter Module

    The piezoelectric generator has been able to generate DC voltage which can be used to recharge a DC battery that produces 11.1V. To use this voltage level for microcontrollers and DC charging ports; we needed to regulate and stabilize them to 5V. The module used for this job was the DC-DC buck converter. This module allowed us to step down the output of the backup battery to the 5V logic level for the Arduino Nano microcontroller board and the DC charging ports.

    To make the system functional for everyday use, a small DC charging station is added. This station can include USB charging ports or a DC jack for powering portable devices.

    The charging station draws energy from the backup battery, not directly from the piezo sensors. This guarantees stable and consistent output even when no one is stepping on the platform. It effectively turns human motion into a useful energy source for mobile gadgets, LED lights, or small electronics.

    Generate Electricity using Footsteps: Arduino-Based Voltage Monitoring

    The Arduino Nano board was used to measure and display the voltage output by the piezoelectric generator as well as measure and display the voltage level of the backup battery. The circuit diagram was connected as shown below.

    How To Generate Electricity using foot-steps
    Measuring the voltage output of the piezoelectric generator

    The voltage measurement of this how to generate electricity using foot-steps with backup charging station (piezoelectric generator) project was done using the voltage divider rule; this is composed of a pair of known resistor values, R5 and R6, respectively, connected in a series connection. The measurement of the voltage generated by the piezoelectric generator was mostly the voltage drop across R5, as shown in the above circuit diagram. The Vo wire (also called the analog input wire) was connected to the analog pin A0 of the Arduino Nano board. However, because Arduino pins cannot withstand voltage levels above 5V, Caution was taken and a Zener diode of 5V was connected in the reverse direction in parallel to resistor R5. This would ensure that the maximum voltage drop across the Arduino analog pin was 5V.

    Since power from footsteps is intermittent, a backup rechargeable battery is added to store the energy produced by the piezo layer. The battery acts as a reservoir, collecting all incoming power and delivering a stable output whenever needed.

    This storage ensures that even if the walkway is not in continuous use, the system still holds enough energy to power small loads or charge gadgets later. The choice of battery depends on the expected output and usage—Li-ion, NiMH, or sealed lead-acid batteries can all be used.

    To measure the voltage level of the LiPo battery, we used a similar technique. This time, only the values of the resistors connected in series were changed. Since the maximum voltage to be measured and displayed was 12V, Using the series connection of 30k and 7.5k; we formed a voltage sensor. And this is a voltage divider having a ratio of 5 to 1 voltage divider. Hence, there is a reduction by a factor of 5 for any input voltage. The schematic can be drawn below.

    Measurement of Battery Voltage Level Using Arduino
    Measurement of Battery Voltage Level Using Arduino

    The voltage divider rule configuration of resistors that made up the LiPo Battery voltage measurement

    Since we are reading the Arduino analog input pin, which accepts voltages up to 5V. But If the controller had a 3.3V system, the input voltage supplied to it should not be greater than:

      3.3V × 5 = 16.5V

    But Arduino came with AVR chips that have a 10-bit ADC architecture, so this setup simulates a resolution of:

    0.00489V (5V/1023)

    so the minimum voltage of the input voltage detection module is:

                                                                                    0.00489V x 5 = 0.02445V.

    Light Emitting Diodes (LEDs):

    Light Emitting Diode (LED)
    Light Emitting Diode (LED)

    Also called Light Emitting Diodes, LEDs are diodes that convert electrical energy to light energy. The LEDs’ color types used here were Red and Blue LEDs. The Blue LED was to show an indication of charging while the red LED was used to show that the battery was full. However, in the video demonstration, only one LED was used to show when the DC charging port was ready to be used for charging. This red LED would indicate that power has been connected to the system.

    Adding LCD to the Project Design

    LCD circuit diagram connection
    LCD circuit diagram connection

    The LCD module was added to the circuit diagram as shown above; to make the how to generate electricity using foot-steps with backup charging station (Piezoelectric generator) project smarter. The LCD uses the 4-bit communication protocol. This means 4 wires were used for the Data transfer between the Arduino Nano board and the liquid crystal display (LCD) module. These four wire data started from Data wire 7 (D7) of the LCD through D4. The Register Select (RS) and the Enable (E) Pins of the LCD were connected to Digital Pin 2 and 3 respectively. A variable resistor of value 10kΩ was used to adjust the contrast display of the LCD. The variable resistor here was a potentiometer (pot). The wiper pin was connected to the A0 of the LCD. This means the Vcc of the 10 kΩ pot was connected to the 5V, and the ground pin was connected to the GND rail. The voltage drop across the pot is then used to determine the contrast brightness of the display module. Where the Vss and the Vdd pins of the LCD were connected to the 5V and Gnd rails of power respectively. To ensure the LCD came on looking bright, the LED+ and the LED- pins were connected to the power rails using a current limiting resistor of 10kΩ.

    The Complete Circuit Diagram

    How To Generate Electricity using foot-steps
    The breadboard view of the complete circuitry
    The complete circuit diagram (schematic view)
    The complete circuit diagram (schematic view)

    Download clear version of circuit diagram here

    Explanation of the circuit diagram

    The circuit diagram above added a charging indicator using a blue LED, as shown, as well as a full charge red LED indicator. The simple transistor configuration made this possible (although in the video demo, only one LED was used to show the system was ready to connect USB flex).

    The circuit works in stages. The piezo discs form the input layer and feed AC voltage into a bridge rectifier. A capacitor smooths this voltage before delivering it to the battery. The Arduino taps into the battery output for monitoring, while the relay or regulator manages the charging station’s power delivery.

    Each part performs a specific role:

    • Piezo layer generates AC voltage
    • Rectifier converts it
    • Capacitor filters it
    • Battery stores it
    • Arduino, LEDs, and LCD display system activity
    • Charging port outputs usable power

    This layered approach makes the system efficient and easy to understand.

    Assembling the whole Circuitry on A Veroboard

    Using the Veroboard, we soldered the whole components that needed to be soldered on the Veroboard. The Veroboard type used is shown in the picture below. Things like the female header pins were soldered onto it.

    Once the breadboard prototype is tested, the entire design is transferred onto a Veroboard. Components such as the rectifier, capacitors, voltage regulator, and Arduino connectors are soldered neatly into place.

    This final assembly stage ensures durability and prepares the system for real-world use. Proper insulation and spacing are important here, especially where wires connect to the piezo elements or battery terminals.

    Veroboard for soldering
    Veroboard for soldering

    The Perforated Board (strip boards or Veroboard) is a universal permanent circuit board. It is made of one side plastic perforated insulator used to arrange configurations of electronic design to finished work; and underneath, a copper plated line conductor that allows easy soldering. Before using this strip-board, our project was first modeled and tested on a Breadboard, which is a detachable platform, which gives room for error making, removal of components, and reattachment of the components. Unlike the Breadboard, the stripboard is used to solder these components together, and once done, is usually very difficult to remove them without applying heat or destroying the components by the use of force.

    Soldering the Components together
    Soldering the Components together

    The soldering and the attaching of the Arduino Nano development board on the Veroboard. The LCD was connected using the LCD 16-pin wire terminal and female socket. This was then soldered to the Veroboard.

    Soldering and Connecting the LCD
    Soldering and Connecting the LCD

    The Source code for the Design (Arduino Code)

    // include the library code:
    #include <LiquidCrystal.h>
    #include <EEPROM.h>
    #include <BigCrystal.h>
    #include <BigFont.h>
    
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(2, 3, 7, 6, 5, 4);
    BigCrystal bigCrystal(&lcd);
    
    int volt;
    float voltage1;
    float divider = 0.936;
    float piezoDivider = 0.26;
    float multiFactor = 2.423;
    float cell = 11.2;
    float low = 3.2; 
    float full = 10.0;
    
    
    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 4);
       Serial.begin(9600);
    
     //write a welcome msg on lcd
     lcd.setCursor(2,1);
     lcd.print("...WELCOME...");
     lcd.setCursor(3, 2);
     lcd.print("  MR. TOLU ");
     delay(3000);
     lcd.clear();
     lcd.setCursor(4,0);
     lcd.print("FOOT-STEP");
     lcd.setCursor(2, 1);
     lcd.print("PIEZOELECTRIC");
     lcd.setCursor(3, 2);
     lcd.print(" GENERATOR");
     lcd.setCursor(3, 30);
     lcd.print("  PROJECT");
     delay(3000);
     lcd.clear();
       for(int x=0; x<16; x++){
      lcd.setCursor(0,0);
      lcd.print("Checking Battery  ");
      lcd.setCursor(x,1);
      lcd.print("*");
    delay(200);
    }
    lcd.clear();
    }
    
    
    float checkBatVoltage() {
     
       volt = analogRead(A3);// read the input
      float voltage1 = (volt *5.273)/1023.999;
      voltage1 = voltage1/ divider; // divide by 100 to get the decimal values
      voltage1 *= multiFactor;
       
     
     float batPercent = map(voltage1, 3.41, 11.1, 0.0, 100.0);
    Serial.print(batPercent);
    Serial.println();
    batPercent = constrain(batPercent, 0, 99);
    
         char buffer[5]; // buffer to hold the converted variable having a length that is +1 of the variable lentgh
         itoa(batPercent, buffer, 10);
         bigCrystal.printBig(buffer, 0, 0);  
         bigCrystal.print("%");
         int number_count = 1;
        int number_temp = int(batPercent);
        while(number_temp != 0){
          number_count++;
          number_temp /= 10;      
        }
        number_count-=1;
        if(batPercent < 1){number_count = 1;}
        lcd.setCursor(0 + (number_count*4), 0);
        bigCrystal.print(voltage1);
        bigCrystal.print("v  ");
        lcd.setCursor(1 + (number_count*4), 1);
         lcd.print(" BAT   ");
    
       
    Serial.print("  Bat3 = ");
    Serial.print(batPercent);
    Serial.println("%");
    
      Serial.print("Batt Voltage: ");
      Serial.print(voltage1);//print the voltge
      Serial.print("V");
    
      Serial.print(" analogRead: ");
      Serial.println(volt);
      delay(500);
      return voltage1;
    
    
    }
    
    
    float checkPiezoVoltage() {
      int volt = analogRead(A2);// read the input
      float piezoVoltage = (volt *5.273)/1023.999;
      piezoVoltage = piezoVoltage/piezoDivider; // divide by 100 to get the decimal values
      piezoVoltage *= multiFactor;
      piezoVoltage *= 4.76;
      piezoVoltage = int(piezoVoltage);
      Serial.print("Piezo Voltage: ");
      Serial.print(piezoVoltage);//print the voltge
      Serial.print("V");
    
      Serial.print(" analogRead: ");
      Serial.println(volt);
    
     char buffer[5]; // buffer to hold the converted variable having a length that is +1 of the variable lentgh
         itoa(piezoVoltage, buffer, 10);
         bigCrystal.printBig(buffer, 0, 2);  
         bigCrystal.print("V");
         int number_count = 1;
        int number_temp = int(piezoVoltage);
        while(number_temp != 0){
          number_count++;
          number_temp /= 10;      
        }
        number_count-=1;
        if(piezoVoltage < 1){number_count = 1;}
        lcd.setCursor(0 + (number_count*4), 2);
        bigCrystal.print("  Piezo    ");
        lcd.setCursor(1 + (number_count*4), 3);
        lcd.print(" Gen     ");
    
    return piezoVoltage;
      
    }
    
    
    void loop() {
      checkBatVoltage();
      checkPiezoVoltage();
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      
      if(Serial.available())
      {
        char cal = Serial.read();
        if(cal == '+' || cal == 'a')
          divider += multiFactor;
        else if(cal == '-' || cal == 'z')
          divider -= multiFactor;
      }
       delay(50);
    }
    
    long readVcc() {
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA, ADSC));
      result = ADCL;
      result |= ADCH << 8;
      result = 1126400L / result; // Back-calculate AVcc in mV
      return result;
    }
    
    

    Explanation of the code

    Arduino sketch

    The syntax uses special libraries of LCD to display the generated level. Some variables that are universal variables to the code were defined above the setup() function and later used in the function to measure the generated voltage checkPiezoVoltage().

    Arduino sketch to measure piezo generator Voltage Level
    Arduino sketch to measure piezo generator Voltage Level

    In this function, we read the analog voltage from the Vo and then converted it. This is the allowed 5V of the Arduino and the 10bits of the reading. Further calculations were done to adjust and make the reading close to accurate. These readings are then mapped using a map() function. This would allow us to display the voltage at a segmented level. The readings are then printed on the LCD screen using code lines 55 through 59. To make the function repeat itself; we placed the function itself in the loop() function. The loop() function repeatedly executes any code placed inside it.

    Measuring the Battery Level Voltage

    Arduino sketch to measure Battery Voltage Level
    Arduino sketch to measure Battery Voltage Level

    Results

    LCD display of piezoelectric generator output voltage
    LCD display of piezoelectric generator output voltage

    The results obtained are given in the diagram above. Here as seen, before we depressed the voltage generated by the piezoelectric generator was 0V but upon depressing the piezoelectric generator using our feet, we get about 10V DC or above. This voltage is displayed as generated by the piezoelectric generator.

    DC-Based Charging Station

    Charging a mobile phone using the project design
    Charging a mobile phone using the project design

    This was handled by the USB ports shown in the circuit diagram above. Once, any of these ports were connected to a USB charging flex, and connected to a phone. It keeps charging and this result is shown below. As shown in the picture above, the battery level was at 87% and at 10.96V, whereas the piezoelectric generator was at 0V. This was done by the programming sketch written above.

    Conclusion

    And that would be all for this how to generate electricity using foot-steps with backup charging station (Piezoelectric generator) project design. Let us know if you were able to create something similar or better. Don’t forget to leave a comment if you encounter any challenges along the way.

    Thank YOU!!!

  • Fix & Remove Japanese Keyword Hack (Japanese SEO Hack) – Complete Guide

    Fix & Remove Japanese Keyword Hack (Japanese SEO Hack) – Complete Guide

    Have you noticed strange Japanese text appearing on your website in Google search results? If so, your site might be infected with the Japanese Keyword Hack (also known as the Japanese SEO Hack). This malware injects malicious code into your WordPress files, hijacks search rankings, and redirects your visitors to spammy sites.

    fix and remove Japanese keyword hack
    Japanese Spam hack result showing unusual pages

    But don’t worry! In this guide, I’ll walk you through the complete process to fix and remove the Japanese Keyword Hack step by step. Whether you’re a beginner or an experienced website owner, this guide will help you clean up your website for good.

    As shown in the image above with the braces and arrow. The search results produced a Japanese SEO page that isn’t a content we created and yet the domain name (shown  in blue brace) still remain our own. But the infected page has been changed. For our own website (used as illustration) here, this has been backlinked to a Casino webpage in Madrid (the brace shown in red).  These pages like the one shown in the image above points to the hacker’s page.

    Read Also: How to Make Money on Facebook: Your Ultimate Guide

    What Is the Japanese Keyword Hack?

    The Japanese Keyword Hack is a type of SEO spam attack where hackers inject malicious code into a website, usually WordPress sites, to generate spam backlinks to their sites. These links often lead to counterfeit product pages, scams, or phishing websites.

    The Japanese Keyword Hack is a type of SEO hijacking attack where hackers inject Japanese text, spam pages, or fake product listings into your website. These pages are usually designed to promote counterfeit products or redirect visitors to malicious stores. The attack often affects WordPress websites because of outdated plugins, insecure themes, or weak login credentials. Once inside, the hacker creates thousands of hidden pages filled with Japanese characters, making your site appear compromised to both search engines and human visitors.

    The most frustrating part of this hack is that it often goes unnoticed until your traffic drops or Google alerts you. It can harm your search rankings, damage your reputation, and cause long-term SEO issues if not fixed quickly.

    How Does This Hack Work?

    The Japanese Keyword Hack works by infiltrating your website files and database, inserting spam content that search engines can crawl but regular visitors cannot see. This is often achieved by using backdoor scripts placed inside your WordPress theme folders or plugin directories. Once these scripts activate, they automatically generate unwanted pages filled with Japanese keywords.

    Hackers may also modify your sitemap, alter your .htaccess file, or cloak content so only search engines see the spam pages. While the site appears normal to you, Googlebot sees fake content, which leads to unexpected ranking changes and warnings in Google Search Console.

    The attack continues to spread until the malicious scripts are removed completely.

    • Hackers exploit vulnerabilities in WordPress plugins, themes, or outdated software.
    • They inject malicious PHP, JavaScript, or database code.
    • The code displays Japanese text and redirects users to harmful websites.
    • It negatively affects your site’s SEO rankings and credibility.

    Symptoms of the Japanese Keyword Hack

    The most common symptom is discovering Japanese text appearing in search results under your domain name. When you click the result, the page may redirect to another website or show content that does not exist in your WordPress dashboard. You may also notice strange URLs, unfamiliar files inside your hosting account, and sudden ranking drops.

    Google Search Console typically displays warnings about hacked content, unusual spikes in indexed URLs, or manual actions. Another sign is when your sitemap is altered, showing pages you didn’t create. These symptoms often confirm that your site has been compromised and needs immediate cleanup.

    • Strange Japanese text appears in Google search results when you search for site:yourwebsite.com.
    • Your website contains hidden malicious files in cPanel.
    • Unexpected new users appear in WordPress.
    • Spammy URLs are being indexed on Google from your domain.
    • Google Search Console sends a Security Issue Warning.

    Read Also: Healthy Recipes for Busy People

    Step-by-Step Guide to Fix and Remove the Japanese Keyword Hack

    Step 1: Check for Japanese Spam Pages on Google

    The best way to be sure is to use a search engine. If we go to the Google search engine (which is the most popular) using our browser and type site:nameofwebsite.com. An example is shown in the picture below.

    fix Japanese SEO hack
    search content of website

    The results displayed indicated that the site (our website) was under Japanese SEO spam siege. The pages were written in Japanese, and even those written in English were detailed in another language, as shown below.

    Read Also: How to Fix Page Redirects In Google Search Console: Boost Website Traffic

    How to fix/remove Japanese keyword hack/Japanese SEO spam on website for free
    Japanese SEO Spam results on Google search

    These links are not directed to our website but to other foreign webpages that serve the interests of the hacker. And if our website visitors click on it, they get redirected to another website (as indicated by the red arrows above). As an example, clicking on the labelled page link redirects the visitor to this Japanese clothing store shown below.

    Read Also: Top 10 Web Hosts for Your WordPress Website

    SEO spam redirected webpages
    SEO spam redirected webpages

    This is because the hackers have already added themselves as a property owners in the Google Search Console. Some of the reasons they do this is to increase profits by manipulating our own site’s settings.

    In summary, to confirm that your website is infected:

    1. Go to Google and type: site:yourwebsite.com.
    2. Check if there are Japanese characters in the search results.
    3. Click on the spammy URLs and inspect where they lead.

    Step 2: Log Everyone Out of WordPress

    Before making changes:

    • Reset all passwords (admin, database, cPanel, FTP).
    • Go to Users > All Users and remove any suspicious accounts.
    
Log out your login history from all users on all devices
    Log out your login history from all users on all devices

    Your WordPress admin page is the first place hackers use to inject malware codes that would bring the SEO Spam hack to your WordPress website. If your WordPress login password has been compromised, it needs to be changed. And that is a big “IF”. Especially when you are running a WordPress website that enables different admin users. The best thing to do is to use the admin user access and log everyone out.  To do this, go to users, navigate to profile, scroll down to Account Management.  At sessions,  click on log out everywhere else, as shown below.

    Step 3: Change Every Login Passwords

    Change Password for WordPress dashboard

    This means creating new passwords for the Admin, The editor, the contributor of the WordPress website etc.  Go to Account Management and locate New Password and Set New Password.

    Set new password for WordPress site
    Set new password for WordPress site

    Change Password for cPanel Password

    First, we have to go to our admin for our website cPanel. Log in and check the right-hand side of our dashboard.

    Click on our username, then account preferences as shown below. Scroll down to password and security.

    change password in cPanel
    Change password in cPanel
    How to fix/Remove Japanese Keyword Hack/Japanese SEO hack free: Change password on cPanel
    Change password on cPanel

    We changed our password by navigating to the change password page and input our new password inside the input password box.

    Step 4: Scan Your Website for Malicious Code

    Fix & Remove Japanese Keyword Hack: Download and Install Wordfence Security Plugin

    Installing WordFence Security Plugin
    Installing WordFence Security Plugin

    Go to the left-hand side panel of your WordPress admin dashboard, hover over the Plugins tab, then navigate to Install Plugin. Next, click on “Add New.”

    Using the search bar for WordFence plugin
    Using the search bar for WordFence plugin

    Click on the search plugin input box as shown above. And type “Wordfence.” Alternatively, you can follow the link given here to download . We used the free version of the plugin here. We recommend you do too (that is kind of why the how-to was written). Or if you have the money, you can go for the premium version.

    Selecting Wordfence Security plugin
    Selecting Wordfence Security plugin

    Click on Wordfence Security- Firewall & Malware Scan. Install it and activate it.

    Once this is done. Return to your plugins page or click on Wordfence on the left hand side of the dashboard.

    WordFence Plugin Scan options
    Wordfence scan option

    You can opt to go to the Wordfence dashboard before anything else. This would offer you the chance to see your website security stats before proceeding to scan your website for malware. This is a very crucial part in this how to fix/remove Japanese keyword hack/Japanese SEO hack free wiki.

    Scanning for malware on the website server
    Wordfence Security Dashboard

    Click on Scan next from the left hand side of the dashboard, hover over Wordfence and select Scan option.

    Scanning website for malware using Wordfence
    Scanning website for malware using Wordfence
    Wordfence Scan option
    Wordfence Scan option

    Click on Start New Scan and wait until it has finished scanning. As shown with our example website here, There are two issues; one is File Changes and the other is Vulnerability Scan Issues. This means that our files may have been altered by a hacker.

    Scanning website using Wordfence
    Scanning website using Wordfence

    The scan would keep loading until it has finished.

    Malware scan results
    Malware scan results

    From the scan results, we could either delete  or repair the files that are corrupt. I would recommend repairing the repairable files. Then deleting the files that are not repairable.  Click on repair all repairable files and wait for the system to repair the files it can repair. These are the small steps that would lead to a giant leap on our search for how to fix/remove Japanese keyword hack/Japanese SEO hack free.

    View details of each malicious file
    View details of each malicious file

    Next, for the files that are not repairable, you can either delete them or click on the details of each file to view the severity of each infected file. You can check out the difference in each file to see the changes in each file.

    Wordfence File Difference viewer
    Wordfence File Difference viewer

    From the file difference, we can see a lot of things on this .php file. This was the exact file that was corrupted that made it possible for the Japanese keyword hack/Japanese SEO spam. From the left hand side of this comparison, we can see the original .php file versus the file that was modified by the hacker on the right hand side. The solution to this can’t be resolved automatically by Wordfence because the .php file is a file on the cPanel side. The Wordfence plugin doesn’t have access to the file.

    Get the location of the corrupt file by looking at its directory path above on the Wordfence file viewer as shown below.

    cPanel file directory path
    cPanel file directory path

    Using this, we locate the file in the cPanel public_html directory.

    locating the corrupt file on cPanel
    locating the corrupt file on cPanel
    Open with UTF-8 encoding format
    Open with UTF-8 encoding format

    Open this for editing and choose utf-8 as your decoding format.

    utf-8 encoding character selection
    utf-8 encoding character selection

    With the file opened as shown below; we can delete the hackers Japanese SEO spam/Japanese Keyword hack codes. If this step is not judiciously done, there won’t be success in the how to fix/remove Japanese Keyword Hack/Japanese SEO hack free guide.

    malware code isolation
    malware code isolation

    We begin by deleting the codes that were not already in the original file displayed by Wordfence file viewer. After removing the codes, save the file and go back to Wordfence and rescan your website files. Using our demo website example, the file changes result showed that the issue has been resolved.

    Resolving file changes security issues
    Resolving file changes security issues

    The vulnerability scan can be further pursued but this would mean carefully tracking out the files that poses security threats to your website.

    In summary, to find the infected files:

    1. Use Wordfence Plugin
      • Install and activate the Wordfence Security Plugin.
      • Run a full site scan.
      • Wordfence will detect malicious files.
    2. Check Files Manually
      • Go to your cPanel > File Manager.
      • Look for suspicious files in wp-content, wp-includes, or wp-admin.
      • Inspect the .htaccess, wp-config.php, and index.php files for unusual code.

    Step 5: Remove Malicious Code

    Once you’ve found infected files:

    • Open each file in File Manager or FTP.
    • Remove suspicious code (it may look like base64 encoding or unreadable characters).
    • Save the changes.

    Step 6: Use Google Search Console

    The google search console helps you to get your website noticed and discovered on Google search results. IF your contents are already showing up on Google search. The chances are that you are already using the Google search console. To login into your Google Console account, use this link. You may have to log in and verify that you own the domain. If you don’t know how to do this, use Google search or any other search engine to find answers, and if it still confuses you, leave a query regarding this in the comment section. Once you are in your Google search console, the appearance will look something like this picture below.

    Google search console
    Google search console

    Step 7: Checking for Infected Japanese SEO backlinks

    On the left hand side pane (of the image above), hover to reveal the scrolling handle, use this to scroll down until you reach links  at the bottom. This is where you click to find all the website links coming in and going out of your website.

    Links button on Google search console
    Links button on Google search console

    The links would display all your backlinks. You can copy each of the website links and put them on a separate browser to test the links. For the example website used in this tutorial, most of the backlinks were porn sites, casinos, clothing websites etc.

    Google console links result
    Google console links result

    If these websites are allowed for long they could use up your bandwidth rapidly.

    When your website is infected with Japanese keyword hack virus, the search results on Google displays pages that have your domain name but the title of those pages can be very misleading.

    How to fix/Remove Japanese Keyword Hack/Japanese SEO hack free: Keyword Spam pages
    Keyword Spam pages

    The picture above shows the search results of our website infected with the Japanese SEO Spam virus. But looking closely, the pages displayed are numbered 1, 2, and 3.  The number 1 page is the homepage of the website. However, the page it is pointing to was written in a language that can not be understood by English-speaking users, this is also Number 2. The number 3 result was from the shop page, but rather than the electronics components and kits on display at the online shop, it is displaying a Hussein dress shirt. These pages are still linked to our website’s contents. Although it doesn’t display its page content on Google search results correctly, once clicked on, it will take online visitors to our pages.

    How to fix/Remove Japanese Keyword Hack/Japanese SEO hack free
    Heavily infected SEO spam

    On the other hand, majority of the pages are pointing to another SEO page content. As illustrated with the picture of our website above, the pages here drive traffic away from our  website. They are something like “aco136”, “dft353” “zqcum” etc. If a visitor clicks on any of these links, it would take them to the hackers backlinked website pages instead.

    How to fix/Remove Japanese Keyword Hack/Japanese SEO hack free
    Japanese SEO spam page

    Usually, the Japanese SEO hacker pages are non-mobile-friendly and very slow to load, and it could really drive visitors away from your website. Most people don’t have the time to wait until a slow loading page finishes loading. It could also make Google blacklist your website. To tackle this issue, go ahead and log into your WordPress admin page again.

    Step 8: Delete Suspicious Plugins and Themes

    Some plugins or themes may be compromised. To check:

    • Go to WordPress Dashboard > Plugins > Installed Plugins.
    • Delete any unknown or inactive plugins.
    • Switch to a default theme (e.g., Twenty Twenty-Four) and delete suspicious themes.

    Step 9: Clean Your Database

    Hackers may inject malicious scripts into your database. To clean it:

    • Access phpMyAdmin from your hosting panel.
    • Run the following SQL command to find spam entries:
    SELECT * FROM wp_posts WHERE post_content LIKE '%<script%' OR post_content LIKE '%iframe%';

    Delete the infected database entries.

    Step 10: Reset .htaccess File

    • Your .htaccess file may be hijacked. To reset it:
    • Go to File Manager > public_html.
    • Open the .htaccess file and replace its content with:
    # BEGIN WordPress 
    RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] 
    # END WordPress

    Save the file and upload it.

    Step 8: Re-index Your Website on Google

    Once the malware is removed, re-index your website to restore search rankings:

    1. Go to Google Search Console.
    2. Navigate to URL Inspection.
    3. Submit a request for Google to re-crawl and re-index your site.

    Step 9: Improve Security to Prevent Future Hacks

    To prevent the Japanese Keyword Hack from returning:

    • Enable two-factor authentication (2FA).
    • Keep WordPress, themes, and plugins updated.
    • Use a strong password and limit login attempts.
    • Install a security plugin like Wordfence or Sucuri.
    • Regularly scan your site for vulnerabilities.

    Fix & Remove Japanese Keyword Hack: Backup your WordPress Content

    Before attempting to fix anything, you must secure a full backup of your site. This ensures your original content is safe even if the cleanup process removes or damages files. Backing up your WordPress content involves saving your website files and the database that stores all your posts, settings, and user data.

    During cleanup, infected files, spam entries, and suspicious scripts will be deleted. Having a backup prevents irreversible loss. With your content secured, you can confidently proceed to remove the hacker’s changes from your hosting server and WordPress installation.

    The backing up of your contents on your WordPress site is also important. However, most of the backups required you to pay for such server services. There are other ways you can get around this. For example, you can use the UpdraftPlus plugin to backup contents on your Google Drive account, provided you have enough storage space there.  Whether you choose this option or not, you can still proceed to the next step.

    After this is done;  we proceed to check if the back-linked Japanese SEO sites are still functional. We go back to Google search engine and type the same search query: site:nameofwebsite.com. In our own demo example, we used our website name as shown in the picture below.

    site:nameofwebsite.com
    site: nameofwebsite.com

    The results shown would still remain the same on Google search results but we are really after the functionality. This means we want to know if the backlinks still redirects visitors to the hackers page.

    Japanese Keyword Hack results on Google
    Japanese Keyword Hack results on Google

    A click on the page results that has the Japanese links should display error 404, page not found for us to know that the changes we made were working.

    Japanese Keyword Hack
    Error 404 on webpage

    Great. Once you are here. You efforts have finally paid off. The next steps are very easy to finish.

    Re-index Your Web Pages across Google Console and other Search Engines

    After removing the infected files and restoring your original content, the next step is ensuring Google recognizes the cleanup. This requires re-indexing your website through Google Search Console. By requesting re-indexing, you tell Google to recrawl your pages and replace the hacked versions with your legitimate content.

    This process speeds up recovery and helps your search rankings normalize. Other search engines like Bing and Yahoo also provide webmaster tools where you can request a fresh indexing of your pages. Updating your search engine visibility helps remove leftover hacked content from search results.

    Remove Japanese Keyword Hack: Re-indexing on Google.

    Go back to the Google search console and click on URL inspection.

    Japanese Keyword Hack
    Indexing page on Google search console

    Click on request indexing next.

    Japanese Keyword Hack
    Page Indexing on search console

    Ensure that you re-index all your pages on your website using the Google search console, this would ensure you have completed your how to fix/remove Japanese keyword Hack/Japanese SEO hack free. The YouTube video shows more details on how to generate and use Google sitemaps  to re-index your page.

    Remove Japanese Keyword Hack: Re-indexing on Bing Search Console.

    This is achieved by going to the link. The Bing search console is owned by Microsoft and it is popular for search engine results done using the Internet Explorer browser.

    Japanese Keyword Hack
    Bing console dashboard

    Follow the same steps done with Google search console and Click on Submit sitemap. Add the domain URL and click submit.

    Japanese Keyword Hack
    submitting sitemaps on Bing console

    Using Popular Sitemaps

    A clean and accurate sitemap helps search engines understand the correct structure of your website after the hack has been removed. Generating a new sitemap ensures that old spam URLs are no longer submitted to search engines. When the new sitemap is submitted to Google Search Console or other search engines, it provides a clean reference of your real pages.

    Many WordPress plugins can generate updated sitemaps automatically. The important part is making sure the sitemap no longer includes any hacked pages, since search engines rely on it as a guide for indexing your website properly.

    Another fast way to ensure many popular search engines get your website’s content is to use XML sitemaps. You can use this by going to the link. This would direct you to the page shown below.

    Japanese Keyword Hack
    XML sitemaps

    We input our website link and let it do the rest. They required us to sign up before using the free version, but after that, it was able to index the pages across many popular search engines.

    Check the Results on Search Engines

    Once your website has been cleaned, re-indexed, and provided with a new sitemap, the next step is monitoring the results. You may begin checking your domain name on Google to confirm that the Japanese spam pages have disappeared. Sometimes search engines need time to remove old URLs, so regular checking helps you track the recovery progress.

    You can also review your Search Console for updates, especially any warnings that may appear. Over time, you should notice your real pages returning to the search results, and overall site health gradually improving.

    After the above steps have been successfully completed, we have to wait for the search engines to crawl the website again. This may take some time. It may take days or even weeks before Google and the other search engines can recrawl our website pages and display the intended results successfully. But after a period of one week, we came back to check again. The results on Google search when we type the same search query, this time the results have changed. 

    Japanese Keyword Hack
    Google search results

    Also, using the Internet Explorer browser, the results on Bing search too has been updated accordingly.

    Japanese Keyword Hack
    Bing search results

    However, they may still be some few exceptions. The pages on the websites may not be properly crawled by the search engines so all of its results won’t be updated accurately at the same time.

    Japanese Keyword Hack
    Japanese keyword hack pages

    This shouldn’t make you panic if you see this in your own results. The validity of solution can be verified by clicking  on the page result displayed and once it shows an error 404 ; page was not found. We know that we are still good in business.

    These steps explicitly explained above are the summary of how to fix/remove Japanese Keyword Hack/Japanese SEO hack free from your website.

    Things to note and do always to keep your website safe.

    1. Always update your WordPress outdated/expired plugins
    2. Always update outdated/expired themes
    3. Always update outdated/expired WordPress version.

    Failure to update and secure the above mentioned 3 things would give hackers what they need to to gain access to most WordPress websites. An outdated theme gives the hacker easier access to your login details or ways to attack your WordPress site. So does an outdated plugin or theme.

    4. Use a good Antivirus and security plugin like Wordfence. This would continuously run scan and update you on outdate plugins and themes. And it would equally stop web attacks on your website.

    5. Consider going away from using Content Management System (CMS) like WordPress to something better like Bootstrap.

    Conclusion

    The Japanese Keyword Hack is a frustrating and dangerous malware attack that can harm your website’s SEO and reputation. But with the right approach, you can remove it completely and protect your website from future infections.

    By following this step-by-step guide, you can identify infected files, clean malicious code, re-index your site, and implement strong security measures. If you need extra help, consider reaching out to a professional security expert.

    The Japanese Keyword Hack can cause serious damage to your website’s SEO, traffic, and reputation, but it can be completely resolved with the right steps. Understanding how the hack works helps you identify it quickly, while cleaning your files, restoring your content, and re-indexing your site ensures a full recovery. Regular monitoring and updated sitemaps help maintain your search presence and avoid future attacks.

    If you continue maintaining strong security practices, your website will remain protected and continue performing well across all major search engines.

    Take action today to secure your website and keep it safe from future attacks!

    FAQs

    1. How do I know if my site has been hacked?

    You can check for the Japanese Keyword Hack by searching site:yourwebsite.com on Google. If you see spammy Japanese text in the search results, your site is infected.

    2. Can I remove the Japanese Keyword Hack for free?

    Yes! You can remove it manually by scanning files with Wordfence, checking cPanel for malicious scripts, and cleaning your database.

    3. What causes the Japanese Keyword Hack?

    It usually happens due to vulnerable plugins, weak passwords, or outdated software. Hackers exploit these weaknesses to inject malicious code.

    4. How long does it take to remove the malware?

    The cleanup process can take a few hours to a couple of days, depending on the severity of the infection.

    5. How can I prevent my site from being hacked again?

    To prevent future hacks, use strong passwords, install security plugins, update WordPress regularly, and enable two-factor authentication (2FA).

  • Visitor Bidirectional Counter Using IR sensors Arduino, Infrared Bidirectional Counter with AC bulb.

    Visitor Bidirectional Counter Using IR sensors Arduino, Infrared Bidirectional Counter with AC bulb.

    This visitor bidirectional counter using IR (infrared) sensors Arduino project uses two Infrared (IR) obstacle sensors to notice the direction of movement; if the direction is from left to right, otherwise known as the entrance, it will count that the person has moved inside a house. And would keep increasing the number of people moving into the house according to this motion direction. Once the entrance count is above one (1), it will turn on an AC bulb. However, if the direction of movement is reversed, that is, from right to left (exit movement), it will decrement the number of people inside the house and will continue to decrement until the count is zero, at which point it will turn off the AC bulb.

    Components/Materials for Visitor Bidirectional Counter Using IR sensors Arduino Project

    For this project design; we will need the following materials:

    Arduino Pro-Mini Dev. Board

    FTDI programmer

    IR obstacle sensor

    5V DC power supply

    Portable AC switch

    Single channel relay module

    LED…2 pieces

    10k resistor….2 pieces (optional)

    16×2 LCD module

    16×2 LCD flex

    You can chat us and order for the full complete project kit

    Circuit Diagram for Project Design

    The circuit diagram for the project is shown below

    Visitor Bidirectional Counter Using IR sensors Arduino
    circuit diagram for the project

    Circuit Diagram Explanation

    The circuit design of the project design shows that a single channel relay module can be constructed using a 5V relay, an NPN transistor like TIP41C, and a 10Kohm resistor and connected as shown in the diagram.

    The usual 4-bit communication protocol was adopted in connecting the LCD to the Arduino Pro-Mini. A 2.7kohm resistor can be used to replace the 10K potentiometer used to adjust the contrast of the 16×2 LCD module.

    The two IR obstacle sensors used to detect entry and exit have their output pins connected to digital pins 2 and 3 respectively on the Arduino Pro-Mini board. The design is then powered by a 5V DC and the following sketch is uploaded into the Pro-Mini board Using the FTDI ISP Programmer.

    The Source Code (Arduino Sketch)

    //include the LCD lib
    #include <LiquidCrystal.h>
    //define where the lcd pins are connected on the A. Pro Mini
    LiquidCrystal lcd(9, 8, 7, 6, 5, 4);
    //define where the IR sensor outputs are connectd
    int irPin1 = 2;
    int irPin2 = 3;
    //define variables
    int count = 0;
    boolean state1 = true;
    boolean state2 = true;
    boolean insideState = false;
    boolean outsideIr = false;
    boolean isPeopleExiting = false;
    int i=1;
    //define actuator pins
    #define relay 10
    #define LED 13
    
    
    void setup() {
      //begin serial monitor
    Serial.begin(9600);
    //define out input and out pin on pro mini board
    pinMode(irPin1, INPUT);
    pinMode(irPin2, INPUT);
    pinMode(relay, OUTPUT);
    pinMode(LED, OUTPUT);
    //begin the lcd module
    lcd.begin(16, 2);
    
    //print a welcome msg on LCD
    //set the cursor first
    lcd.setCursor(0,0);
    lcd.print(" WELCOME DAVID ");
    lcd.setCursor(0,1);
    for(int i= 0; i <15; i++){
      lcd.print(".");
      delay(100);
    }
    //print title of project on lcd
    lcd.setCursor(0,0);
    lcd.print("  BIDIRECTIONAL ");
    lcd.setCursor(0,1);
    lcd.print("COUNTER  PROJECT");
    lcd.clear();
    
    }
    
    
    //this fxn blinks the Red LED when there is entry or exit motion
    void blinkLED(){
       for(int i= 0; i <5; i++){
          digitalWrite(LED, HIGH);
          delay(50);
          digitalWrite(LED, LOW);
          delay(50);
          
       }
    }
    
    
    void loop() {
      Serial.print(!digitalRead(irPin1));
       Serial.print(" ");
      Serial.print(!digitalRead(irPin2));
        Serial.print(" ");
      Serial.println(count);
      delay(300);
    
    if (!digitalRead(irPin1) && i==1 && state1){
         outsideIr=true;
         delay(100);
         i++;
         state1 = false;
      }
    
       if (!digitalRead(irPin2) && i==2 &&   state2){
        blinkLED();
        lcd.clear();
        lcd.setCursor(0, 0);
         lcd.print("ENTERING ROOM");
         outsideIr=true;
         delay(1000);
         i = 1 ;
         count++;
         lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    CURRENT");
         lcd.setCursor(0, 1);
         lcd.print("Num in room: ");
         lcd.print(count);
         state2 = false;
      }
    
       if (!digitalRead(irPin2) && i==1 && state2 ){
         outsideIr=true;
         delay(100);
         i = 2 ;
         state2 = false;
      }
    
      if (!digitalRead(irPin1) && i==2 && state1 ){
        blinkLED();
        lcd.clear();
        lcd.setCursor(0, 0);
         lcd.print("LEAVING ROOM");
         outsideIr=true;
         delay(1000);
         count--;
         lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    CURRENT");
          lcd.setCursor(0, 1);
           lcd.print("Num In Room: ");
          lcd.println(count);
         i = 1;
         state1 = false;
      }  
    
     
    //condition for AC bulb on
    if(count >= 1){
      digitalWrite(relay, HIGH);
    }
    
    //turn off bulb when nobody is inside
    if(count <= 0){
      digitalWrite(relay, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(" NO ONE IN ROOM");
       lcd.setCursor(0, 1);
      lcd.print("LIGHT TURNED OFF");
      count = 0;
    }
    
    
      if (digitalRead(irPin1)){
         state1 = true;
        }
    
         if (digitalRead(irPin2)){
         state2 = true;
        } 
      
    }
    

    Visitor Bidirectional Counter Using IR sensors Arduino Code Explanation

    Basically, what we did above was to define some variables and Boolean states that took care of the changes in the IR sensors when they detect IR emitting obstacles. but we used the “!digitalRead” to show or invert the IR sensor output on the serial monitor. A conditional if statements resets the Boolean states at the end of the loop function.

    Results

    Watch the video demonstration tutorial for more. Kindly leave us a comment below if you reproduce similar project work or a better one than this.

    Conclusion

    We would love to know what you think about the project and you can put a comment to ask for an upgrade of this project. Our social media handles are at the top navigator bar.

    Thank you. See you next time.

  • Solar-Powered Smart Irrigation System with SMS

    Solar-Powered Smart Irrigation System with SMS

    In this project tutorial, we will design and construct a solar-powered smart irrigation system with SMS notification. The system design is an automatic smart project that has the capacity to detect the relative humidity, optimum temperature, and soil moisture level of a garden or farm using special soil moisture sensors and relay this data to an authorized user phone via short message service (SMS). The project design also uses the level of water in the soil to determine when to turn on a DC power pump to pump water into the farm for irrigation purposes automatically. This means it totally eliminates the human labor part in running the irrigation in both arid and well-watered places.

    Material/Components Needed

    In assembling the components and parts needed for the design of this project; we took into consideration the underlined objectives: materials that are not too expensive, readily available, and we could use them to obtain our desired aims.

    • 12V DC pump………………………………………………………………………….1pcs
    • Soil Moisture sensor……………………………………………………………2pcs (or 1)
    • Single Channel Relay Module………………………………………………………1pcs
    • Temperature and humidity sensor module……………………………………..1pcs
    • Microcontroller Unit (Standalone or Arduino made)………………………….1pcs
    • FTDI ISP programming cable………………………………………………………..1pcs
    • 30W PV panel……………………………………………………………………………..1pcs
    • 30A solar charge controller……………………………………………………………1pcs
    • 12V 7Ah backup battery…………………………………………………………………1pcs
    • SIM800L GSM module………………………………………………………………….1pcs
    • Prepaid SIM card and some airtime.

    Theoretical Calculations

    Solar Based Smart Irrigation System with SMS Notification
    power consumption for DC pump and relay module

    Solar Based Smart Irrigation System with SMS Notification: Design the Framework/Woodwork

    The system design had its backbone on the base which shows off the surface where to lay soil for planting of crops. To design the real model of such garden, we used a compressed wood frame.  The wood was first analyzed for structural defects and when ascertained to be minimal; we set out for the dimensioning.

    Sandpapering the design model
    wood dimensioning, sandpapered and cutting

    The wood for the fence of the building was made with dimension of length of about 65cm, the breath  is about 3cm and the height is 8cm. We used a different wood for this.

    The shape of the model garden was rectangular, with no opening. Once we have gotten the fencing structure ready we proceeded to nailing them together. Before this, we polished the base surface and then applied a wood glue to the surface. After a small while, use used a top wrapper to cover it. This was a Glossy Laminate formaica sheets. And this gave is the impression we were looking for. This better choice since we didn’t want the compressed base wood to be getting wet and decaying very quickly as we are pumping water through sprinkling into the garden fam model.

    Solar powered Smart Irrigation System with SMS Notification
    Formaica wrapping on plain wood surface

    After nailing the barricades we have ourselves a look we were looking for as shown below.

    Solar powered Smart Irrigation System with SMS Notification
    The farm garden barricaded

    Next we used wood filler powder to fill some of the minor openings that were between each joining of the woods.

    The garden model
    running irrigation hose through the model garden walls

    We laid the hose around the wall of the fence to form our sprinkling pattern. The hose was further punched at different locations to allow sprinkles of water when the DC pump is turned on.

    The soil moisture sensor and temperature and humidity sensor module (DHT11) are positioned at the best place to take readings. After this, we wire the inside for our soil moisture sensors. We also included the digital and humidity sensor. Then we proceeded to making an external base where we can place out rechargeable battery, solar charge controller and the microcontroller development unit.

    Solar powered Smart Irrigation System with SMS Notification
    The arrangement of the solar irrigation system
    Connectig the 12V DC Pump
    wiring 12V DC pump
    Solar powered Smart Irrigation System with SMS Notification
    schematic diagram of power connection

    The connection in the picture diagram above is almost what we connected for the solar grid in the project design. We however connected the standalone microcontroller development board to the 5V USB terminal above the charge controller.

    First, the battery was connected to the charge controller. After which, we connect the PV array lastly followed by the load which is the DC pump. But until in the actual design, one of the power rails of the DC pump is connected to the single channel relay module. Which would act as a switch for turning on and turning off of the DC pump by the MCU (This is shown in the schematic diagram below).

    The Microcontroller unit (MCU) was enclosed in the 3×6 adaptable box shown below. From this box we connected every other part to the design.

    Encasing the project desing
    powering up the MCU, relay module and SIM800L

    The GSM module. The soil moisture sensors and the dht11 sensor were all encased in a plastic 3×6 patress box. Which is then screwed unto the base of the partition of the wooded base reserved for the power and controls for the garden model. The battery also alongside the solar charge controller is kept on this partition to avoid water from getting into the power leads. We powered the MCU from one of the two 5V output reserves using a USB female socket. While taking a 12V from the output of the solar charge controller then passing it through a DC-Dc buck converter before stepping it down to 3.3V which we used to power the GSM module.

    Constructing the Stand for the PV array:

    Solar Based Smart Irrigation System with SMS Notification
    Screwing the screws that would hold the solar panel at an angle of 45°.
    Solar Based Smart Irrigation System with SMS Notification
    installing the Solar panel on the stand for its position

    Solar-powered Smart Irrigation System with SMS: Circuit Diagram

    Solar Based Smart Irrigation System with SMS Notification
    Complete circuit diagram of the design

    The SIM800L power supply also came from the 12V load output on the charge controller which could only supply the GSM module the rated current (about 2A) it needs to kick-start itself. But we used a DC-DC buck converter for this to ensure that, we stepped it down to 3.4V. The following below is the syntax that was compiled in the Arduino IDE unto the MCU board.

    #include <SerialGSM.h>
    #include <SoftwareSerial.h>
    SerialGSM cell(10,11);
    // Include DHT library and Adafruit Sensor Library
    #include "DHT.h"
    #include <Adafruit_Sensor.h>
    // Pin DHT is connected to
    #define DHTPIN 7
    // Uncomment whatever type of sensor you're using
    #define DHTTYPE DHT11   // DHT 11 
    //#define DHTTYPE DHT22   // DHT 22  (AM2302)
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)
    // Initialize DHT sensor for normal 16mhz Arduino
    DHT dht(DHTPIN, DHTTYPE);
    
    // Create global varibales to store temperature and humidity
    float t; // temperature in celcius
    float f; // temperature in fahrenheit
    float h; // humidity
    float soil; //soil moisture
    String SMS;
    String Invalid; 
    String stat;
    String Pump_State;
    const int pump = 13;
    boolean sendonce=true;
    
    void setup(){  
    //  sensors.begin();
      dht.begin();
      Serial.begin(9600);
      cell.begin(9600);
      cell.Verbose(true);
     //cell.Boot();
      //cell.DeleteAllSMS();
      cell.FwdSMS2Serial();
      delay(2000);
      Serial.println("AM READY FOR YOU\n");
      pinMode(pump, OUTPUT);
      delay(2000);
       }
    boolean readData() {
      //Read humidity
      h = dht.readHumidity();
      // Read temperature as Celsius
      t = dht.readTemperature();
      // Read temperature as Fahrenheit
      f = dht.readTemperature(true);
    
      // Compute temperature values in Celcius
      t = dht.computeHeatIndex(t,h,false);
    
      // Uncomment to compute temperature values in Fahrenheit
      //f = dht.computeHeatIndex(f,h,false);
      
      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return false;
      }
      Serial.print("Humidity: "); 
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: "); 
      Serial.print(t);
      Serial.print(" *C ");
      //Uncomment to print temperature in Farenheit
      //Serial.print(f);
      //Serial.print(" *F\t");
      return true;
    }
    
    void loop(){
      // Convert the analog reading (which goes from 0 - 1023) to a range (0 - 100):
     soil = analogRead(A2)*100.00/1023.00;
     soil = constrain(soil, 2.00, 100.00);
     soil = map(soil, 100.00, 2.00, 2.00, 100.00);
      
     if (soil <= 65.00)
      {
        digitalWrite(pump, HIGH);
        Pump_State = "ON";
      }
      if ( soil >= 70.00)
      { digitalWrite(pump, LOW);
        Pump_State = "OFF";
      }
      if (cell.ReceiveSMS()){
         Serial.println("NEW SMS ARRIVED");
         delay(100);
         stat = cell.Message();
      if(readData()){
       cell.Rcpt(cell.Sender());
       delay(500);
       Serial.print("Sender: ");
       Serial.println(cell.Sender());
       delay(2000);
       Serial.print("Messsage: ");
       Serial.println(cell.Message());
       delay(2000);
        SMS = ("***SMART FARM DATA***\n__Command Accetped!__\nSee Result Below.\nTEMP: " + String(t) + "*C \nHUM: " + String(h) + "%\nSoil Water: " + String(soil) + "\nPump Status: " + Pump_State + "\nEnd of Report!\nHave a Nice Day.");
        Invalid = "SMS received but I don't recognize your command.\nKindly Contact Mr. Damilare for list of acceptable commands.\nThanks.";
        int m = SMS.length();
        char Send[m + 1];
        strcpy(Send, SMS.c_str()); 
        int i = SMS.length();
        char invalid[i + 1];
        strcpy(invalid, Invalid.c_str()); 
        if(stat == "STATUS"){
            cell.Message(Send);
            }
         else{cell.Message(invalid);} 
        cell.SendSMS();
        delay(2000);
        Serial.println("message sent!\n");
        cell.DeleteAllSMS();
          }
        }
      }
    
    

    Source Code Explanation

    The code began with us importing two libraries that were very important; the GSM library and the software serial library. Next we defined where we connected out receiver and transmitter pin of our SIM800L to the MCU using variable name cell. We culled two more libraries for the DHT11 sensor  and defined where we connected the pin. We defined and told the MCU which type of DHT sensor we were using. Other variable names were define to denote temperature and humidity. We defined a String type of variable to hold the SMS to be sent out size. We defined our pump state and its single channel relay pin.

    In our setup() function, we began the Dht11 sensor, and jump started the SIM800L. Once it was ready, we asked it to print out a message (AM READY FOR YOU) on the serial monitor.

    WE used another function, this time a Boolean function readData that wouild be reading and logging the DHT11 sensor. And once the sensor is reading that means it is true and it can always output the data to our serial communication which in turn communicate with the GSM module.

    In the loop() function, the  String SMS is sent out when the incoming text is ‘STATUS’. When the incoming SMS matches the word; STATUS, the MCU prompts the SIM800L to send out the message.

    The if conditions  that are coded after the constrained and mapped values pf the soil moisture sensor allows for us to set the rate at which we can pump the water into the farm. As stated here, the pumps kicks in when the sensor measure a wetness that is below 65.00 and pumps until the wetness goes above 70.00.

    Results and Analysis

    The project, Solar-powered Smart Irrigation System with SMS worked very well as expected when tested after successful compilation of the code into the MCU. Once the SMS that contains the text ‘STATUS’ is sent to the SIM card inserted into the SIM800L module and it confirms reception; it quickly replies with the status of the farm that contains:

    Serial Monitor dispaly of SMS received and sent

    The syntax is supposed to take care of when the incoming SMS doesn’t match the String ‘STATUS’ and reply the sender by telling it that it doesn’t recognize the command. The design can also be sent a command in SMS format of “TURN PUMP ON” and it will turn on the DC pump and would turn it off by itself on the irrigated water level on the garden is enough to avoid flooding of the whole garden model.

    Conclusion

    Now we have shown you how we achieved this project, Solar-powered Smart Irrigation System with SMS Notification. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram community, Telegram, Facebook page, Instagram and Twitter.

  • Anti-Theft and Burglar System with SMS Notification

    Anti-Theft and Burglar System with SMS Notification

    This project, Anti-Theft and Burglar System with SMS Notification, is programmed with Arduino with GSM module SIM800L, and has PIR motion sensors and laser trip mechanisms. The anti-theft and burglar system design allows specific users to arm it and disarm it by phone call or short message service (SMS). During the armed state; the systems’ motion sensors and laser mechanisms are activated to sense for intruders senses when there is an intruder within the vicinity. When the system is armed, it informs the user via SMS that it is armed and it is alert for any intrusion. The users can also arm or disarm the system at anytime by calling the system design.

    Materials/Components

    The following components were used in designing this project:

    1. Atmega328P MCU
    2. laser diodes
    3. Light dependent resistors (LDRs)
    4. Passive Infrared Sensors
    5. GSM module, SIM800L
    6. A house model

    To design the Atmega328P MCU, we followed the circuit diagram shown below.

    Circuit of Anti-Theft Design
    Circuit of Anti-Theft Design
    Circuit of Anti-Theft Design

    Download full circuit diagram here or Download it here

    Anti-Theft and Burglar System with SMS Notification: Circuit Design Explanation:

    As shown in the circuit diagram, the design used two PIR sensors; with these, we sensed motions or movements around a vicinity. Using the PIR in a timed sequence and adding a laser trip wire (using laser diodes and LDRs) would help us, as would modelling a house model. Around the windows where burglars have high tendencies of prying the glasses or closures. We added two PIR sensors to window view post. The system would be set to enter “armed state”; which  is the state that the burglar(s) can trip the laser wire that is kept at a respected distance between the window and doors. The tripping would be caused by when the thief breaks the continuous light emitted by the laser onto the surface of the LDR. Then this breaking would make the design to go into the “burglary detect state”. This works a great deal with the PIR and the very close of the stranger to the user’s windows or door. Because in this state, the stranger is almost at the window, and once the PIR detects this illegal motion, it gives off loud varying siren tones through a very loud 12V electronic siren buzzer. And it automatically sends an SMS alert to the user, telling him or her that strange movement occurred at his door or window during such a time as possible while they were not aware or asleep; maybe perhaps gone out. The siren dies down after a while when it is no longer sensing movement within its line of sight.

    Circuit Diagram Mode of Operation:

    For this project, Anti-Theft and Burglar System with SMS Notification. The MCU is selected to be a 28-pin Atmel Atmega328P. The atmeag328P chip has four (4) pins for power. Pins 7 and 20 are for VCC power rails, while pins 8 and 22 are for GND power rails. The hardware reset pin, pin 1 is connected to a 10kΩ precision resistor to keep the pin at 5V HIGH. This pin is an ACTIVE LOW pin. This means the pin would reset the MCU when pulled to the ground (GND) hence the 10kΩ is a pullup resistor. The pin 9 and 10 of the MCU is connected to a 16Mhz crystal oscillator that helps with the pulse clocking and synchronization of internal operations of the MCU. We used the pin 2 and 3 of the MCU for programming it. Since these pins are the UART pins. Also known as the Receiver (Rx) and Transmitter (Tx) pins. These pins would form a crucial part in the FTDI pin connection as we would be using them to communicate between the MCU and the programming PC. Two 22pF capacitors are connected from pin 9 and pin 10 to GND, respectively. This would help in sinking the noise generated by the internal switching of the MCU. To ensure that the MCU accepts programs onto its RAM, we soldered two 100nF  ceramic capacitors between pin 20 and pin 22 and then between pin 1 (RST) and the CTR pin of the FTDI header pins.

    Anti-Theft and Burglar System with SMS Notification: Testing the MCU

    To test if the microcontroller is accepting programs burned into it; we plugged the FTDI ISP programmer into the male header pin ISP input. We open the Arduino IDE and uploaded two programs: The Bare Minimum program and the Blink program.

    Bare Minimum Sourcecode
    void setup() {
    }
    void loop() {
    }
    
    Blink Sourcecode:
    #define testLedPin 13
    void setup() {
    pinMode(testLedPin, OUTPUT);
    }
    
    void loop() {
    digitalWrite(testLedPin, HIGH);
    delay(500);
    digitalWrite(testLedPin, LOW);
    delay(500);
    }
    

    After uploading this source code to the MCU, the LED connected to pin 19 on the MCU starts blinking. We were so sure that the MCU is working to specification.

    We needed a smart display to show the status of the alarm and when it is ‘armed’ and when it is ‘disarmed’. For this function, we used a 16×2 LCD module. The configuration to the MCU is done using 4-bit protocol as shown in the circuit diagram. The Vcc and GND pins of the LCD is connected to 5V and 0V power rails. The Vo is connected to the wiper pin of a 10kΩ potentiometer resistor or a 4.7kΩ connected to Vo then to ground. The register select (RS) pin is connected to pin 13 (PCD08) of the MCU while the enable (E) pin is connected to pin 14 (PCD09). These pins are very important to ensure the LCD screen display the characters that we need it to display. The read/write (R/W) pin of the LCD is grounded. And since we are using a 4-bit communication protocol; we connected four wires from D4 through D7 corresponding to pin 15 through 18 (PCD09 through PCD12) on the MCU. These data pins are very essential and cannot be overlooked when communicating microcontrollers. The LED(+) pin is connected to 5V power rail to ensure backlight brightness comes on when powered on. And finally, the LED(-) pin of the LCD, pin 16 is connected to ground or Vss.

    //The following sourcecode is in C/C++ program using Arduino as IDE
    // include the library code:
    #include <LiquidCrystal.h>
    
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    
    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }
    
    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }
    
    

    The SIM800L GSM was interfaced as shown in the circuit above. But since the MCU uses 5V logic and the Sim800L module uses 3.3V, we needed a voltage shifter. We connected a DC-DC buck converter to the output of the two LiPo batteries that were in series connection(This was later replaced with a 5V power supply module). The SIM800L connection to the MCU was software serial connection, which means that it could be altered in the programming syntax.

    The idea was to arm and disarm the system using phone calls. After much tinkering and testing, we were able to send SMS from the GSM module and make it receive calls from authorized callers. Thus using this call times to ‘arm’ or ‘disarm’ the system design.

    Finanly, we interfaced the PIR sensors, laser diodes and the LDRs but then we came across a flaw in the design.

    Limitations  and modification of the circuit diagram:

    The Anti-Theft and Burglar System with SMS Notification circuit diagram shown above was limited in function because it had only two PIR sensor and two laser diode to cover the front view and the back view of the compound model. This left a lot of blind spots for burglars to access and penetrate the vicinity. Also, we were already knowing the status of the security design with SMS alert that is sent to our phone; so the LCD display was overdoing it. We needed to cover more view points in the compound. However, this meant more sensors and more pin allocations from the MCU to the sensors. We added one more PIR to the design and two more laser diodes and LDR. However, this was at the cost of the LCD module. The new circuit diagram was thus:

    Circuit of Anti-Theft Design
    final circuit diagram

    Further adjustment made was to remove the relay for switch the 12V high pitch siren buzzer and use loud piezo buzzer instead and using transistor as a solid state switch to switch from the microcontroller. This reduced the rate of power consumption of the components and since this was a prototype, it was very ideal not to deafen the observers during display.

    CONSTRUCTING THE HOUSE MODEL

    Anti-Theft and Burglar System with SMS Notification
    The compound model

    The design for the Anti-Theft and Burglar System with SMS Notification project was modelled after a bungalow house. The design began with dimensioning and measurement of the house outlook. We envisioned that we needed a compound with four (4) sides. Hence we made a dimension of a wooden rectangular base of length 65cm x 60cm.

    Still modelling off for the Anti-Theft and Burglar System with SMS Notification, The wooden base was cut with a hand saw and it was sand-papered according to ensure smoothness and splinters from entering the hands since hand gloves were not provided in the workshop. After this process, the vertical side braces which would act as the fences were cut out. For the width side of the fences, a pair of soft wood with dimensions: 60cm x 7cm x 2cm. The top of the soft wood is being installed nails and then barb-wired modeling it off from a real fence. Once this was completed; the gating system was also cut of. This has a dimension of 20cm x 2cm.

    Anti-Theft and Burglar System with SMS Notification
    The front view

    A model house is then placed inside this compound where the sensors are attached for this Anti-Theft and Burglar System with SMS Notification project. The roof of the model house is a transparent plastic glass, which helps to view the circuit design from the top view angle.

    Anti-Theft and Burglar System with SMS Notification
    The final outlook model
    #include <EEPROM.h>
    #include <SoftwareSerial.h>
    SoftwareSerial cell(11, 12);
    
    const char number1[] = {"09033827773"};
    const char number2[] = {"07062174135"};
    const char number3[] = {"*********"};
    
    int8_t answer;
    char aux_string[30];
    char phone_number[15];
    char received[15];
    int length = 11;
    String caller;
    int counter = 0;
    boolean Armed = EEPROM.read(0);
    char status = "ACTIVE";
    
    int pirPin1 = 6; 
    int pirPin2 = 9;
    int pirPin3 = 10;
      
    int ldrRoofPin = A0;
    int ldrFrontPin = A1;
    int ldrleftPin = A5;
    int ldrRightPin = A3;
    
    // Output Pins
    int laserActivePin = A4;
    int AlarmPin = 13;
    
    int ldrTopSense, ldrLeftSense, ldrRightSense, ldrFrontSense; 
    
    boolean pir1Sense = true;
    boolean pir2Sense = true;
    boolean pir3Sense = true;
    
    void setup() {
      //tell MCU ur outputs
      pinMode(laserActivePin, OUTPUT);
        pinMode(AlarmPin, OUTPUT);
          
      //tell MCU ur inputs
      pinMode(pirPin1, INPUT);
      pinMode(pirPin2, INPUT);
      pinMode(pirPin3, INPUT);
    
      //off Alarm
      digitalWrite(AlarmPin, LOW);
        //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(4800);
      //Begin serial communication with Arduino and SIM800L
      cell.begin(4800);
      Serial.println("Initializing...");  
      delay(1000);
      while ( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
               sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );
      Serial.println("Connected to Mobile Network...");
      
    
    }
    
    void loop(){
      pir1Sense = digitalRead(pirPin1);
       pir2Sense = digitalRead(pirPin2);
       pir3Sense = digitalRead(pirPin3);
    
     ldrTopSense = analogRead(ldrRoofPin);
     ldrLeftSense = analogRead(ldrleftPin);
     ldrRightSense = analogRead(ldrRightPin);
     ldrFrontSense = analogRead(ldrFrontPin);
    
    Serial.print(pir1Sense);
    Serial.print("  ");
    Serial.print(pir2Sense);
    Serial.print("  ");
    Serial.println(pir3Sense);
    
    Serial.print(ldrTopSense);
    Serial.print("  ");
    Serial.print(ldrFrontSense); 
    Serial.print("  ");
    Serial.print(ldrLeftSense);
    Serial.print("  ");
    Serial.println(ldrRightSense);  
    
    //program is allways waiting for a +CLIP to confirm a call was received
      //it will receive a +CLIP command for every ring the calling phone does
      while (answer = sendATcommand("", "+CLIP", 1000)) {
        //answer is 1 if sendATcommand detects +CLIP
        if (answer == 1)
        {
          counter ++; // INCREMENT THIS VARIABLE FOR EACH RING.
          Serial.println("Incoming call");
          Serial.println(counter);
          for (int i = 0; i < 15; i++) {
            //read the incoming byte:
            while (cell.available() == 0)
            { delay (50); }
            //stores phone number
            received[i] = cell.read();
          }
          cell.flush();
          byte j = 0;
          //phone number comes after quotes (") so discard all bytes until find'em
          while (received[j] != '"') j++;
          j++;
          for (byte i = 0; i < length; i++) {
            phone_number[i] = received[i + j];
          }
        }
        for (int i = 0; i < length; i++) {
          // Print phone number:
          Serial.print(phone_number[i]);
          caller += phone_number[i];
             }
        Serial.println("\n>>>" + caller);
        
        //After 3 RINGs compare the caller ID with the authorized list then take decisions.
        if(counter > 3){
        if(caller != number1 && caller != number2 && caller != number3){
          Serial.println("Unknown Caller"); 
          sendATcommand("ATA", "OK", 500);
          Serial.println("I just picked to HangUp"); 
          sendATcommand("ATH", "OK", 500);
          }
        else {
           Serial.println("Authorized Caller");
           sendATcommand("ATH", "OK", 500);
           Serial.print("I Know You MASTER, no need to pick."); 
           Armed = !Armed;
           EEPROM.update(0, Armed); 
           counter = 0;
       
       if(Armed){
        Serial.print("Armed ");
         sendSMS("07062174135", "Alarm Armed. \nThank You.");
         sendSMS("09033827773", "Alarm Armed. \nThank You.");
         updateSerial();
      delay(500);
        delay(3000);
       }
       else{
        Serial.print("Not Armed");
        sendSMS("07062174135", "Alarm Disarmed. \nThank You.");
        sendSMS("09033827773", "Alarm Disarmed. \nThank You.");
        updateSerial();
      delay(500);
       delay(3000);
       }
      
       }
           }
      } 
    
     if(Armed == 1){
        Serial.println("\nArmed");
    analogWrite(laserActivePin, 225);
    digitalWrite(AlarmPin, LOW);
       Serial.println("LASER ON");
        while(pir1Sense){
                analogWrite(AlarmPin, 255);
                Serial.println("\nALARM now ACTIVE");
                sendSMS("07062174135", "Intrusion Detected At left Window.");
                sendSMS("09033827773", "Intrusion Detected At left Window.");
                updateSerial();
                return;
             }
          while(pir2Sense){
          analogWrite(AlarmPin, 255);
          Serial.println("\nALARM now ACTIVE");
          sendSMS("07062174135", "Intrusion Detected At Front Entrance.");
          sendSMS("09033827773", "Intrusion Detected At Front Entrance.");
          updateSerial();
          return;
         }
       while(pir3Sense){
        analogWrite(AlarmPin, 255);
        Serial.println("\nALARM now ACTIVE");
         sendSMS("07062174135", "Intrusion Detected At Right Window.");
         sendSMS("09033827773", "Intrusion Detected At Right Window.");
         updateSerial();
        return;
       } 
       
       //check when it is dark
           if(ldrLeftSense < 950) {
             digitalWrite(AlarmPin, HIGH);
        Serial.println("\nALARM now ACTIVE");
        sendSMS("07062174135", "Laser Tripped At Right Fence Side.");
        sendSMS("09033827773", "Laser Tripped At Right Fence Side.");
        updateSerial();
        return;    
        }
      if(ldrRightSense < 950){
          digitalWrite(AlarmPin, HIGH);
        Serial.println("\nALARM now ACTIVE");
         sendSMS("07062174135", "Laser Tripped At Left Fence Side.");
         sendSMS("09033827773", "Laser Tripped At Left Fence Side.");
         updateSerial();
         return;
      }
    
      if(ldrFrontSense < 950){
       digitalWrite(AlarmPin, HIGH);
        Serial.println("\nALARM now ACTIVE");
         sendSMS("07062174135", "Laser Tripped At Front Fence Side."); 
         sendSMS("09033827773", "Laser Tripped At Front Fence Side.");
         updateSerial();
         return;   
      } 
      }
       
         if(Armed == 0){
          Serial.println("\n Not Armed");
    analogWrite(laserActivePin, 0);
    digitalWrite(AlarmPin, LOW);
       Serial.println("LASER OFF");
         }
    caller = "";
     }
    
    
     void sendSMS(char receiver[11], char content[140])
     { 
       cell.println("AT+CMGF=1");
       delay(1000);
       cell.print("AT+CMGS=");
       delay(5);
       cell.print(char(34));
       delay(5);
       cell.print(receiver);
       delay(5);
       cell.println(char(34));
       delay(5);
       cell.print(content);
       delay(50);
       cell.println(char(26));
       delay(2000);
       Serial.println("Done");
       delay(3000);   
    }
    
    
    void updateSerial()
    {
      delay(5);
      while (Serial.available()) 
      {
        cell.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(cell.available()) 
      {
     Serial.write(cell.read());//Forward what Software Serial received to Serial Port
      }
    }
    
    
    
    int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout) {
    
      uint8_t x = 0,  answer = 0;
      char response[100];
      unsigned long previous;
    
      memset(response, '\0', 100);    // Initialice the string
    
      delay(100);
    
      while ( cell.available() > 0) cell.read();   // Clean the input buffer
    
      cell.println(ATcommand);    // Send the AT command
    
      x = 0;
      previous = millis();
    
      // this loop waits for the answer
      do {
        // if there are data in the UART input buffer, reads it and checks for the asnwer
        if (cell.available() != 0) {
          response[x] = cell.read();
          x++;
          // check if the desired answer is in the response of the module
          if (strstr(response, expected_answer) != NULL)
          {
            answer = 1;
          }
        }
        // Waits for the asnwer with time out
      } while ((answer == 0) && ((millis() - previous) < timeout));
    
      return answer;
    }
    

    Conclusion

    Now we have shown you how we achieved this project, Anti-Theft and Burglar System with SMS Notification. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram community, Telegram, Facebook page, Instagram and Twitter.

    Read More

  • How to Design IoT Based Air Quality Monitoring For COPD Patients

    How to Design IoT Based Air Quality Monitoring For COPD Patients

    This project tutorial, How to Design IoT Based Air Quality Monitoring For COPD Patient is about how to design an IoT based air quality monitor for Chronic Obstructive Pulmonary Disease (COPD) patients. The system design measures the level of toxicity in the breathable air around people and detects certain high traces of contaminants like hydrogen sulphide (H2S), carbon monoxide (CO), Carbon dioxide gas (CO2), ammonia gas (NH3) and methane gas (CH4) . According to research, these gases comprise some of the heavy contaminant gases that affect COPD patients a lot.

    The Proposed Algorithm

    How to Design IoT Based Air Quality Monitoring For COPD Patients

    The Circuit Diagram

    The microcontroller unit (MCU) is designed using the Atmega328P-P microcontroller chip. Read more project tutorials using Atmega328P. The schematic diagram of this project is shown below.

    How to Design IoT Based Air Quality Monitoring For COPD Patients
    Circuit Diagram of the device

    We will program it using an FTDI flex and Arduino IDE. The circuit diagram above sowed that we connected an external 16Mhz crystal with a pair of 22pF capacitors to suppress noise of MCU internal switching. To enable ISP programming; we connected 100nF capacitor to the RTS pinout for resetting when programing. We also connected another 100nF the power rails. This would make the programming go smoother.

    FTDI cable
    FTDI cable

    The indicator LED is optional and can be added to know when the program was successfully uploaded.

    How to Design IoT Based Air Quality Monitoring For COPD Patients
    Circuit diagram with two gas sensors: MQ135 and MQ136

    The two sensors are connected to he analog pins of the Atmega328P MCU standalone board. We also connected the a buzzer o notify us when the air contamination spikes high and unfit for breathing. The LCD module is connected using 4-bit configuration. The Register Select (RS) is connected to digital pin 7 (D7) of the Atmega328P MCU, Enable Pin (E) is connected to D8, while D4 through D7 of the LCD module is connected to D6 through D3 of the MCU IC.

    The ESP8266-01 (ESP-01) WiFi module is is connected as a Station (STA) tot he MCU using software serial communication protocol. The Transmitter (Tx) pin of the ESp-01 is connected to the D9 of the MCU while the Receiver (Rx) pin is connected to D10 of the MCU. The reset pin of ESP-01 is connected to D11 while the Enable and Vcc pins are connected to 3.3V. The GND is connected to the GND power rail.

    In testing and configuring the ESP-01 module. We connected the the Tx and Rx of the ESP-01 to the Tx and Rx of the MCU, then we changed the baud rate to 115200bps by opening the serial monitor on the Arduino IDE.

    Arduino Source Code

    We opened a blank sketch or Bare Minimum Sketch example and uploaded it to the System.

    bare minimum sketch

    We type in the top pane: AT

    The system would return: OK.

    This would show that the system is communicating with he ESP-01 module. We type: AT+CWJAP=”USERNAME OF WIFI”,”PASSWORD OF WIFI” then hit enter.

    This will display that it is connected to the WiFi and also show that it has been assigned an IP address.

    After this; we can connect the ESP-01 as shown in the circuit diagram above and powered it up. It would reflect on our phones or router that we are using as WiFi access points.

    Before uploading the code below to the design: we have to setup our Thingspeak channel. click here to read about setting a Thingspeak channel and account.

    <!-- wp:code -->
    <pre class="wp-block-code"><code>//Program Code for IoT Based Air Quality for COPD Patient
    //include type of comm lib
    #include &lt;SoftwareSerial.h&gt;
    //type of comm pins connctn
    SoftwareSerial EspSerial(9, 10);
    //include the libs
    #include &lt;LiquidCrystal.h&gt;
    LiquidCrystal lcd(7, 8, 6, 5, 4, 3);
    
    //include write key of thingspeak 
    String statusChWriteKey = "HREVVINHITJ179YP"; 
    
    //define wia ESP-01 pin is connected
    #define HARDWARE_RESET 11
    
    //how many microseconds to write
    long writeTimingSeconds = 17;
    long startWriteTiming = 0;
    long elapsedWriteTime = 0;
    
    boolean error;
    
    //declare the sensor input analog pins
    const int MQ135_PIN = A0;
    const int MQ136_PIN = A1;
    
    int MQ135RL_VAlUE = 20;
    int MQ136RL_VAlUE = 20;                                        
    float MQ135RO_CLEAN_AIR_FACTOR = 3.86;
    float MQ136RO_CLEAN_AIR_FACTOR = 3.78;
    
    #define buzzer 12
    #define LED 13
    
    int MQ135CALIBARAION_SAMPLE_TIMES = 50;                    
    int MQ135CALIBRATION_SAMPLE_INTERVAL = 50;        
    int MQ135READ_SAMPLE_INTERVAL = 50;                       
    int MQ135READ_SAMPLE_TIMES = 5;
    
    int MQ136CALIBARAION_SAMPLE_TIMES = 50;                    
    int MQ136CALIBRATION_SAMPLE_INTERVAL = 50;        
    int MQ136READ_SAMPLE_INTERVAL = 50;                       
    int MQ136READ_SAMPLE_TIMES = 5; 
    
    #define GAS_CH4   0     //our aim is: mq-135 for CO2, Methane &amp; NH3,  mq-136 = H2S,
    #define GAS_CO2    1
    #define GAS_NH3   3
    #define GAS_H2S   4  
    
    float CH4Curve&#91;3]   = {2.3,0.51,-0.39};   //pt.1 (log 200, log3.2), pt.2(log 10000, log.69) and slope m= (y2-y1)/(x2-x1) then we choose pt.1
    float CO2Curve&#91;3]    = {2.3,0.72,-0.34};   //pt.1 (log200, log5.3), pt.2 (log10000, log1.5)
    float NH3Curve&#91;3]   = {1.0,0.23,-0.15};   //pt.1 (log10, log1.7), pt.2(log100, log1.2)
    float H2SCurve&#91;3]   = {1.3,0.11,-0.32};   //pt.1 (log20, log1.3) &amp;&amp; pt.2(log100, log0.78) 
    
    float MQ135Ro = 10; 
    float MQ136Ro = 10;
    
    long iPPM_CH4 = 0;
      long iPPM_CO2 = 0;
      long iPPM_NH3 = 0;
      long iPPM_H2S = 0;
     
    void setup() {
      pinMode(MQ135_PIN, INPUT);
      pinMode(MQ136_PIN, INPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(HARDWARE_RESET, OUTPUT);
      pinMode(LED, OUTPUT);
       //begin serial comm
      EspSerial.begin(9600);
      Serial.begin(9600);
      Serial.begin(115200);
      //begin lcd
      lcd.begin(20, 4);
      //set the ESP-01 reset pin high and call reset functn
      digitalWrite(HARDWARE_RESET, HIGH);
      EspHardwareReset();
      startWriteTiming = millis();
    
     MQ135Ro = MQ135Calibration(MQ135_PIN);
     MQ136Ro = MQ136Calibration(MQ136_PIN);
      
      //print a welcome message
      lcd.setCursor(0, 0);
      lcd.print("    WELCOME TITO    ");
      lcd.setCursor(0, 1);
      lcd.print(" INTERNET OF THINGS ");
      lcd.setCursor(0, 2);
      lcd.print("&lt;&lt;&lt;&lt;  C.O.P.D   &gt;&gt;&gt;&gt;");
      lcd.setCursor(0, 3);
      lcd.print("...PROJECT DESIGN...");
      delay(3000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("&lt;&lt;&lt;PREPING SENSORS&gt;&gt;");
      lcd.setCursor(0, 1);
      lcd.print("PLEASE WAIT");
      lcd.setCursor(11, 1);
      for(int i = 0; i &lt; 29; i++){
      lcd.print("."); 
      delay(90);
      }
      
    }
    
    void loop() {
      
      iPPM_CH4 = MQ135GetGasPercentage(MQ135Read(MQ135_PIN)/MQ135Ro,GAS_CH4);
      iPPM_CO2 = MQ135GetGasPercentage(MQ135Read(MQ135_PIN)/MQ135Ro,GAS_CO2);
      iPPM_NH3 = MQ135GetGasPercentage(MQ135Read(MQ135_PIN)/MQ135Ro,GAS_NH3);
      iPPM_H2S = MQ136GetGasPercentage(MQ136Read(MQ136_PIN)/MQ136Ro,GAS_H2S);
    
     lcd.clear();  
      lcd.setCursor(0, 0);
     lcd.print("CO2:");
     lcd.setCursor(5, 0);
     if(iPPM_CO2 &lt; 100){
          lcd.print(00);
     }
      lcd.print(iPPM_CO2);
      lcd.print("ppm");
      
      
     lcd.setCursor(0, 1);
     lcd.print("H2S:");
    lcd.setCursor(5, 1);
     if(iPPM_H2S &lt; 100){
      lcd.print(00);
     }
      lcd.print(iPPM_H2S); 
      lcd.print("ppm"); 
     
     lcd.setCursor(0, 2);
     lcd.print("NH3:");
    lcd.setCursor(5, 2);
     if(iPPM_NH3 &lt; 100){
      lcd.print(00);
     }
      lcd.print(iPPM_NH3);
      lcd.print("ppm");
     
       
      lcd.setCursor(0, 3);
     lcd.print("CH4:");
     lcd.setCursor(5, 3);
     if(iPPM_CH4 &lt; 100){
      lcd.print(00);
     }
      lcd.print(iPPM_CH4);
       lcd.print("ppm");
    
    lcd.setCursor(14, 0);
    lcd.print("Status");
    lcd.setCursor(15, 2);
    lcd.print("Alarm");
      if((iPPM_CH4 &lt; 40) || (iPPM_NH3 &lt; 40) || (iPPM_H2S &lt; 40) || (iPPM_CO2&lt; 40)){
      digitalWrite(buzzer, LOW);
      lcd.setCursor(16, 3);
      lcd.print("OFF");
     }
    
     if((iPPM_CH4 &gt; 40) || (iPPM_NH3 &gt; 40) || (iPPM_H2S &gt; 40) || (iPPM_CO2 &gt; 40)){
      digitalWrite(buzzer, HIGH);
      lcd.setCursor(16, 3);
      lcd.print(" ON"); 
     }
     
    
    elapsedWriteTime = millis()-startWriteTiming; 
      
      if (elapsedWriteTime &gt; (writeTimingSeconds*1000)) 
      {
           writeThingSpeak();
        startWriteTiming = millis();   
      }
      
      if (error==1) //Resend if transmission is not completed 
      {  
        lcd.setCursor(15, 1);
    lcd.print("ERROR");  
    //lcd.setCursor(0, 1);
    //lcd.print("INTERNET CONNCTN"); */  
        Serial.println(" &lt;&lt;&lt;&lt; ERROR &gt;&gt;&gt;&gt;");
        delay (2000);  
          }
    
          if (error==0)  { 
        lcd.setCursor(14, 1);
        lcd.print("CONCTD"); 
      }
    }
    
    
    float MQ135ResistanceCalculation(int raw_adc){
      return ( ((float)MQ135RL_VAlUE*(1023-raw_adc)/raw_adc));
    }
    float MQ136ResistanceCalculation(int raw_adc){
      return ( ((float)MQ136RL_VAlUE*(1023-raw_adc)/raw_adc));
    }
     
    
    
    float MQ135Calibration(int mq_pin){
      int i;
      float val=0;
    for (i=0;i&lt;MQ135CALIBARAION_SAMPLE_TIMES;i++) {            
        val += MQ135ResistanceCalculation(analogRead(mq_pin));
        Serial.println(val);
        delay(MQ135CALIBRATION_SAMPLE_INTERVAL);
      }
      val = val/MQ135CALIBARAION_SAMPLE_TIMES;                   
      val = val/MQ135RO_CLEAN_AIR_FACTOR;                                                               
      return val;                                            
    }
    
    
    float MQ136Calibration(int mq_pin)
    {
      int i;
      float val=0;
    for(i=0;i&lt;MQ136CALIBARAION_SAMPLE_TIMES;i++) {            
        val += MQ136ResistanceCalculation(analogRead(mq_pin));
        Serial.println(val);
        delay(MQ136CALIBRATION_SAMPLE_INTERVAL);
      }
      val = val/MQ136CALIBARAION_SAMPLE_TIMES;                   
      val = val/MQ136RO_CLEAN_AIR_FACTOR;                                                               
      return val;                                            
    }
    
     
    
    float MQ135Read(int mq_pin){
      int i;
      float rs=0; 
      for (i=0;i&lt;MQ135READ_SAMPLE_TIMES;i++) {
        rs += MQ135ResistanceCalculation(analogRead(mq_pin));
             delay(MQ135READ_SAMPLE_INTERVAL);
      } 
      rs = rs/MQ135READ_SAMPLE_TIMES; 
      return rs;  
    }
    
    
    float MQ136Read(int mq_pin){
      int i;
      float rs=0; 
      for (i=0;i&lt;MQ136READ_SAMPLE_TIMES;i++) {
        rs += MQ136ResistanceCalculation(analogRead(mq_pin));
             delay(MQ136READ_SAMPLE_INTERVAL);
      } 
      rs = rs/MQ136READ_SAMPLE_TIMES; 
      return rs;  
    }
     
     
     long MQ135GetGasPercentage(float rs_ro_ratio, int gas_id){
      if ( gas_id == GAS_NH3 ) {
         return MQ135GetPercentage(rs_ro_ratio,NH3Curve);
      } else if ( gas_id == GAS_CO2 ) {
         return MQ135GetPercentage(rs_ro_ratio,CO2Curve);
      } else if ( gas_id == GAS_CH4 ) {
         return MQ135GetPercentage(rs_ro_ratio,CH4Curve);
      }     
      return 0;
    }
    
    
    long MQ136GetGasPercentage(float rs_ro_ratio, int gas_id){
      if ( gas_id == GAS_H2S ) {
         return MQ136GetPercentage(rs_ro_ratio,H2SCurve);
      }    
      return 0;
    }
    
    
    long  MQ135GetPercentage(float rs_ro_ratio, float *pcurve){
      return (pow(10,( ((log(rs_ro_ratio)-pcurve&#91;1])/pcurve&#91;2]) + pcurve&#91;0])));
    }
    
    long  MQ136GetPercentage(float rs_ro_ratio, float *pcurve){
      return (pow(10,( ((log(rs_ro_ratio)-pcurve&#91;1])/pcurve&#91;2]) + pcurve&#91;0])));
    }
    
    /*this fxn writes to thingspeak*/
     void writeThingSpeak(void){
      startThingSpeakCmd();
      // preparacao da string GET
      String getStr = "GET /update?api_key=";
      getStr += statusChWriteKey;
      getStr +="&amp;field1=";
      getStr += String(iPPM_CO2);  
     getStr +="&amp;field2=";
      getStr += String(iPPM_H2S);
      getStr +="&amp;field3=";
      getStr += String(iPPM_NH3);
      getStr +="&amp;field4=";
      getStr += String(iPPM_CH4);
        getStr += "\r\n\r\n";
      sendThingSpeakGetCmd(getStr);
    }
    
    /* This fxn resets the ESP-01 */
    void EspHardwareReset(void){
      Serial.println("Reseting......."); 
      digitalWrite(HARDWARE_RESET, LOW); 
      delay(500);
      digitalWrite(HARDWARE_RESET, HIGH);
      delay(8000);//Tempo necessário para começar a ler 
      Serial.println("RESET"); 
    }
    
    /********* Start communication with ThingSpeak*************/
    void startThingSpeakCmd(void){
      EspSerial.flush();//limpa o buffer antes de começar a gravar
      
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += "184.106.153.149"; // Endereco IP de api.thingspeak.com
      cmd += "\",80";
      EspSerial.println(cmd);
      Serial.print("enviado ==&gt; Start cmd: ");
      Serial.println(cmd);
      if(EspSerial.find("Error"))
      {
        Serial.println("AT+CIPSTART error");
        return;
      }
    }
    
    /********* send a GET cmd to ThingSpeak *************/
    String sendThingSpeakGetCmd(String getStr){
      String cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      EspSerial.println(cmd);
      Serial.print("enviado ==&gt; lenght cmd: ");
      Serial.println(cmd);
      if(EspSerial.find((char *)"&gt;"))
      {
        EspSerial.print(getStr);
        Serial.print("enviado ==&gt; getStr: ");
        Serial.println(getStr);
        delay(500);//tempo para processar o GET, sem este delay apresenta busy no próximo comando
        String messageBody = "";
        while (EspSerial.available()) 
        {
          String line = EspSerial.readStringUntil('\n');
          if (line.length() == 1) 
          { //actual content starts after empty line (that has length 1)
            messageBody = EspSerial.readStringUntil('\n');
          }
        }
        Serial.print("MessageBody received: ");
        Serial.println(messageBody);
        return messageBody;
      }
      else
      {
        EspSerial.println("AT+CIPCLOSE");     // alert user
        Serial.println("ESP8266 CIPSEND ERROR: RESENDING"); //Resend...
        //spare = spare + 1;
        error=1;
        return "error";
      }
    }</code></pre>
    <!-- /wp:code -->
    

    The Thingspeak Write API has to be changed to the Thingspeak Write API for anyone who wants to use this source code. It is the String named StatusChWriteKey at code line 10. We used some calibration factors to adjust the gas sensor modules. Tis way we could use one sensor to take reading of different constituents of contaminants in air being breathed in by COPD patients.

    We test our design and monitor the changes in the graphs on Thingspeak. A video demonstration is shown here below. Kindly like, subscribe and comment. Thank you.

    Conclusion

    Now we have shown you how we achieved this project, How to Design IoT Based Air Quality Monitoring For COPD Patients. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram community, Telegram, Facebook page, Instagram and Twitter.

    Read More

  • How to Build An Radio Frequency Identification Bus Ticket System

    How to Build An Radio Frequency Identification Bus Ticket System

    Radio Identification (RFID) bus ticket system project help bus drivers to ensure proper fare collection from their passengers and cargo. It is the simplest seamless and hassle-free solution to transport fare payment. Let us take a look at how this was designed and programmed.

    Materials/Components

    The materials needed for RFID based  Bus-ticketing project are divided into four subsystems, namely; the external power supply unit (PSU), the programmable development board (microcontroller unit), the Liquid crystal Display (LCD) unit and the Radio frequency Identification.

    • Header pins
    • LCD connector wires
    • 56OΩ precision resistor
    • 10KΩ potentiometer (trimmer)
    • 16 × 2 Liquid Crystal Display
    • RFID- RC522 Module (with cards and tags)
    • A reset push button.
    • A 10KΩ pull-up resistor
    • 22nF capacitors (2 pieces)
    • 16MHz crystal oscillator (Newark part number 16C8140)
    • Atmeg328P microcontroller
    • Stripboard (perforated or perf  board)
    • LEDs
    • Resistors
    radio identification bus ticket system block diagram
    The block diagram for the project design

    Radio Identification Bus Ticket System: The Circuit Diagram

    The circuit diagram was first designed on the circuit designing IDE, Fritzing. It was also tested  here using the source code since it supports a C/C++ extension called the Arduino programming language.

    radio identification bus ticket system
    The Complete Circuit diagram for the project design

     

    NB: Either Atmega168 or Atmega328P chip can work for this project. Just remember to select which chip you are using from Tools->Boards.

    Bread-boarding Model phase

    Next, the circuit diagram was brought down to the maker’s table and assembled using breadboards and jumper wires. It is breadboarded to test if it is working as specified. All errors encountered are checked and rechecked until the perfect solution is found.

    Radio identification bus ticket system
    breadboard testing of the design

    Soldering/Coupling the Radio Identification (RFID) Bus Ticket System Project

    After the breadboard phase, we simply went to construction of the project design on a more permanent board by soldering the modules and components on strip board.

    Radio identification bus ticket system: coupling the design
    Casing the project in a box

    The casing of the project design was done with an adaptable box. The RFID reader was held onto the cover with a glue gun. The power comes from an external 5V 4A adapter that is connected via a power log.

    RFID bus ticket system
    coupling and casing the project

    Arduino Source Code (Sketch)

    The sketch for this project design is given below. Feel free to modify to your taste,

    //include the RFID libs
    #include <SPI.h>
    #include <MFRC522.h>
    
    //include the LCD lib
    #include <LiquidCrystal.h>
    
     //declear the reset and SDA pins of RFID
    #define SS_PIN 10
    #define RST_PIN 9
    
    // Create MFRC522 instance.
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    //declear what LCD pins u are sending data
    LiquidCrystal lcd(3, 2, 6, 4, 7, 5);
    
    
    
    String pass1 = "CHIBUEZE";
    String acct1 = "6A 2D 67 07";
    String pass2 = "SMART";
    String acct2 = "77 1F 73 63";
    int balance1 = 1000;
    int balance2 = 1000;
    int rate = 200;
    
    
    void setup() 
    {
      Serial.begin(9600);
      // Initiate  SPI bus  
      SPI.begin();
      // Initiate MFRC522      
      mfrc522.PCD_Init();
      //begin the LCD
      lcd.begin(16, 4);
      //state your actuator pins 
      pinMode(A0, OUTPUT);
      pinMode(A1, OUTPUT);
      pinMode(A2, OUTPUT);
      
    //display a welcome note
      lcd.setCursor(0, 0);
      lcd.print("WELCOME CHIBUEZE ");
      delay(4000);
      lcd.setCursor(0, 0);
      lcd.print("   BUS TICKET       ");
        lcd.setCursor(0, 1);
      lcd.print(" PAYMENT SYSTEM  ");
      delay(2000);
        lcd.clear();
    
        //mfrc522.PCD_Init(); // Init MFRC522 
        lcd.setCursor(0, 2);
      lcd.print("                                  ");
      lcd.setCursor(0, 3);
      lcd.print("                                  ");
      
    }
    
    void unregisted(){
       tone(A0, 1000);
    delay(500);
    noTone(A0);
    delay(500);
    
    tone(A0, 1000);
    delay(500);
    noTone(A0);
    delay(500);
    
    tone(A0, 1000);
    delay(500);
    noTone(A0);
    delay(500);
      
      lcd.setCursor(0, 0);
                  lcd.print(" UNREGISTERED              "); 
                  delay(2000);
                  lcd.setCursor(0, 1);
                  lcd.print("PLS GET A VALID CARD");
                                
                      for (int positionCounter = 0; positionCounter < 43; positionCounter++) {
        // scroll one position left:
        lcd.scrollDisplayLeft();
             // wait a bit:
        delay(150);
      }
     
      //lcd.clear();
    }
    
    void loop() { 
      //turn off the actuators
      digitalWrite(A0, LOW);
      analogWrite(A1, 0);
      analogWrite(A2, 0);
      
        lcd.setCursor(0, 0);
      lcd.print("Bus Fare is #");
      lcd.println(rate);
      lcd.println("     ");
      lcd.setCursor(0, 1);
      lcd.print("  Swipe To Pay     ");
      
      
        // Look for new cards  
      if ( ! mfrc522.PICC_IsNewCardPresent()) 
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) 
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content= "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++) 
      {
        
         Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
         Serial.print(mfrc522.uid.uidByte[i], HEX);
         content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
         content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      //this is where u put the UID of the card that you want to give access
         if (content.substring(1) == "6A 2D 67 07") {
          analogWrite(A2, 255);
            delay(250);
            analogWrite(A2, 0);
             delay(250);
            analogWrite(A2, 255); 
              if (balance1 >= rate){
                  balance1 -= rate;
    
                 
            
                  lcd.setCursor(0, 0);
                  lcd.print("   Hi CHIBUEZE   ");
                  lcd.setCursor(0, 1);
                  lcd.print("___Payment O.K___      ");
                  
                 }
                 else{
                  lcd.setCursor(0, 0);
                  lcd.print(" Sorry CHIBUEZE   ");
                  lcd.setCursor(0, 1);
                  lcd.print("Insuficient Fund");
                 
                   }
                  delay(4000);
                  lcd.setCursor(0, 1);
                  lcd.print("_Balance is #"); 
                  lcd.println(balance1);
                  lcd.println(".      .");
                  delay(4000);
                 return;
                }
    
                
         if (content.substring(1) == "77 1F 73 63") {
          analogWrite(A2, 255);
            delay(250);
            analogWrite(A2, 0);
             delay(250);
            analogWrite(A2, 255); 
            
              if (balance2 >= rate){
                  balance2 -= rate;
                  lcd.setCursor(0, 0);
                  lcd.print("     Hi SMART     ");
                  lcd.setCursor(0, 1);
                  lcd.print("___Payment O.K___      ");
                   }
                  else{
                  lcd.setCursor(0, 0);
                  lcd.print("   Sorry SMART   ");
                  lcd.setCursor(0, 1);
                  lcd.print("Insuficient Fund");
                   }
                  delay(4000);
                  lcd.setCursor(0, 1);
                  lcd.print("_Balance is #"); 
                  lcd.println(balance2);
                  lcd.println(".      .");
                  delay(4000);
                 return;
                }
           else{
            lcd.clear();
            analogWrite(A1, 255);
            delay(250);
            analogWrite(A1, 0);
             delay(250);
            analogWrite(A1, 255); 
           unregisted();
            
            
             
           }
           lcd.clear();
                 }
    
     
    

    Source Code Explanation

    From line 2 through 6, we included the libraries we needed for the design. We defined where we connected the Slave Select (SS) and reset (RST) pins on the standalone board. From code line 19 through 25 we declared String type variables where we assigned the name of the account holder in the database, the amount in each account, and the deduction fare rate of the bus transit system. In the setup function, we began the serial peripheral interface communication, which is very necessary for the RFID reader, and also the MFRC was initiated. We printed out a welcome note and then set our outputs for the buzzer and two LEDs using the analog I/O pins. An additional function; ‘unregistered’, was created to loop invalid response message displays and pulsate the buzzer when a user or passenger tries to play funny by using a card or ring tag that doesn’t have money in it. We further used if and else statements to check when a user has maxed out his or her card.

    For video demonstration, you can click on the YouTube clip below and give us a thumbs up.

    Conclusion

    Now we have shown you how we achieved this project, radio identification bus ticket system. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram communityTelegramFacebook pageInstagram and Twitter.

    Read More

  • How to Design Smart Infrared  Remote Controlled Gate System

    How to Design Smart Infrared Remote Controlled Gate System

    In the world of home automation, convenience and security are paramount. Imagine controlling your gate with just the press of a button on your infrared (IR) remote control. A Smart Infrared Remote Controlled Gate System not only enhances security but also adds a layer of sophistication to your property. This project allows you to open or close your gate using an IR remote, ensuring ease of access and peace of mind.

    In this blog post, we’ll walk you through the process of designing a smart infrared-controlled gate system using an Arduino, an IR receiver, and a DC motor. By the end of this tutorial, you’ll be able to control your gate remotely with a simple IR remote, creating a system that’s both practical and fun to build.

    A smart remote controlled gate

    In this project, how to design a smart infrared (IR) remote control gate system, the underlined goal remained unaltered, a smart gate system with the structure with high degree of performance in terms of detecting Infrared signals at the compound entrance and responding automatically to give access entry to specified users that have the remote controller module to the house gate. To demonstrate this, we modeled a home where we constructed a fencing system using wood and made the gating system from retired DVD DC motor driven trays. The design is meant to work thus:

    • Detect Infrared (IR) commands using the IR receiver TSOP1938 (coming in the form of IR signals) from IR transmitter module, known as the remote controller and use these commands to act on the states of the gate model.
    •  The second condition: – i. The system should be smart enough to know when there is a motor vehicle parked at the gate when it is open: at this condition, it wouldn’t close the gate even when asked to. It should then also automatically close the gate when the obstacle is removed.           ii.The system should be able to detect the car is parked inside the house and when it isn’t parked inside the compound. This means that when the user is inside and wants to go out the gate, even if the proximity sensor is detecting the vehicle, it should know that it is going out the compound and needs to open the gate.

    Websites That Will Generate Money For You

    MATERIALS FOR THE DESIGN

    • Atmega328P-PU
    • 16Mhz Crystal oscillator
    • L293D motor driver IC (or Module)
    • Pushbutton
    • 100nF caps (2 pcs)
    • Male and female header pins
    • 22pF caps (ceramic types, 2 pcs)
    • LEDs (red and green colors)
    • 10k ans 1k precision resistors
    • 16×2 LCD module, socket headers and wire
    • 10k potentiometer
    • MP3 car remote control
    • Pair of DVD/CD ROM
    • Infrared Obstacle Avoidance Sensor Module
    • Infrared (IR) Receiver TSOP1838

    Buy All components on our online store

    Motor-Driven Mechanism (Gating system)

    This is made up of CD tray, DC motor and drive belt from an old DVD player machine.

    design a smart infrared (IR) remote control gate system
    The CD ROM and its mechanism

    The low cost nature and its availability made it very useful in its selection. We used two of these devices to control the closing and opening of the gate system. The amazing part of these devices is that each mechanism has a “stopper switch” buried beneath the tray that moves to cut power to the DC motor driving the drive belt that in turns moves the tray. This stopper switch’s state changes in any direction it moves. When it is full forward direction, the stopper switch is LOW and when it is full reverse direction, the switch moves to HIGH. We used these change in states to control our gating system

    design a smart infrared (IR) remote control gate system
    this switch is found underneath the CD ROM mechanism

    Also, the drive belt between the DC motor and the gears that control the CD tray doesn’t maintain a very firm grip on the both gear and DC motor. This is very good so that once the tray has gotten to the marked position and by some reasons unknown, the DC motor is still power, the immovable action on the tray won’t cause the DC motor to get over heated and burn out.

    How to Make Money Online as a Teen 

    Using L293D Motor Driver IC for smart infrared remote control gate system

    This integrated circuitry makes it very possible for us to control the motion of the gating system (which involves two DC motors) simultaneously. The L293D is a device that is quadruple high current half-H drivers. With bidirectional drive currents up to 1A at voltages from 4.5V to 36V. This makes it ideal for relays, solenoids, DC and stepper motors.

    design a smart infrared (IR) remote control gate system
    L293D pinout diagram

    The Power Supply: The power supply used in this project design was a switch mode power supply. The choice was due to its consistency in supply output the required voltage demanded from it at the specified current rating.

    power supply module
    The power supply used here outputs 5V, 4A

    Infrared Obstacle Avoidance Sensor Module: The infrared obstacle avoidance sensor is made up of two infrared LEDs. One is used as the transmitter, while the other is the encapsulated receiver. These two IR sensors are soldered on the same PCD board that has an adjustable potentiometer.

    Read Also Receding Hairline 101: Causes, Solutions, and Tips for Prevention

    smart infrared remote control gate system
    obstacle avoidance sensor

    The two sensor LEDs are controlled by an on-board comparator LM358 which compares the threshold between the inputs of the IR LEDs. The potentiometer used here was to adjust the sensitivity of the IR receiver. The IR obstacle avoidance sensor module works thus: The transmitter (usually the bright encapsulated LED) emits IR signal and once there is no obstacle in its path, the receiver doesn’t get to receive it. But if there is an obstacle in the transmitter’s line of sight, the signal bounces off the obstacle and echoes back to the receiver through diffraction and reflection. Once the receiver LED receives this signal, it activates the signal received active on-board LED to indicate that it has received the signal and it will automatically change the signal output on its  board (which is HIGH, giving 1) to LOW, producing 0).

    IR Receiver TSOP1838:

    vS1838B IR receiver" How to use it with Arduino
    IR receiver 1838

    This IR receiver operates at 38KHz frequency and can decode the IR signals sent to it from the remote controller. The pinout diagram is shown above. The IR receiver, however, when tested with non-programmable chips, shows some inconsistent signal received due to its data pin. The IR receiver runs on a 5V power supply, hence there is no power conversion for it. It was simply plugged into the output of the power supply kit shown above, and we were ready to start receiving specific IR signals from the transmitter(the remote controller) at a 38KHz frequency.

    IR transmitter (remote controller)

    This is a 21 button remote control that is universal. It is very versatile and often low cost as it was meant as a car Mp3 player’s control. The portability of this remote made it very ideal for our project. Hence we used two (2) specific buttons for our selection of opening and closing of the gate. The ‘CH-’ button does the opening of the gate while the ‘CH+’ does the closing of the gate. Of course this was only possible when the IR receiver has decoded the signal each button t transmits and the microcontroller matches the HEX code generated by such signal by the command it prompts

    remote control gate system
    mp3 remote control (IR transmitter module)

    How the System Works

    The Smart Infrared Remote Controlled Gate System uses an IR remote to control a gate’s opening and closing mechanism via an IR receiver. When you press a button on the remote, the IR receiver decodes the signal and sends it to the Arduino. Based on the received signal, the Arduino will either trigger the servo motor to open or close the gate.

    Here’s how the process works:

    1. IR Remote Control: You press a button on the remote, which sends an encoded IR signal.
    2. IR Receiver: The receiver decodes the signal and sends it to the Arduino.
    3. Arduino: Processes the signal and triggers the servo motor accordingly.
    4. Servo Motor: Rotates to open or close the gate latch.

    The system allows for simple gate automation, enabling hands-free control via an easily available IR remote control.

    Smart Infrared Remote Control Gate System: The Complete Circuit Diagram

    Infrared (IR) Remote Control Gate System Schematic
    IR Remote Control Gate System Schematic

    Explanation of the Schematic Diagram

    The circuit diagram uses an Atmega168 microcontroller. The microcontroller is designed with a 16MHz crystal for its synchronous clocking speed. As shown in the circuit diagram. This is connected to pin 9 and pin 10 of the IC. This is marked XTAL1 and XTAL2. To aid with this and to suppress noise generated in the chip, we used a 22pF capacitor connected to the same pin, but to be used as a filter, they were connected with respect to the ground.

    To burn programs into the IC, we used the 6 male header pins for the connection of our FTDI cable. The FTDI programmer has 6 pins for programming: the CTR or chip reset, the receive pin, which is connected to the transmit pin of the microcontroller, the transmit pin Tx, which is connected to the receiver of the microcontroller, the Vcc power pin that is hooked to +5V and the Chip select that is grounded.

    In order to work with the microcontroller and rework with it, there was a need to add a manual reset button. And this is connected to the Active LOW pin (pin 1) of the microcontroller through a 10KΩ precision resistor. This is also called the pull-up resistor that keeps pin 1 of the MCU to see a 5V supply until the reset button is pushed.

    The microcontroller needs 100nF capacitors to be connected across its analog Vcc with respect to the ground. And the other connected from the reset pin to the FTDI pin.

    The LCD connection is done using the 4-bit method of data connection. No I2C modules or connections were needed since the output digital pins of the microcontroller were enough to communicate with the LCD module. The LCD is powered directly at pins 1, 2, 15, and 16 respectively without using a pull-up resistor for the LED+ backlight pin. The wiper of a 10KΩ pot is connected to the Vo pin of the LCD to adjust the screen contrast. The Register Select (RS) is connected to pin 7 and the Enable of the LCD is connected to pin 8. The 4 data pins are connected at pins 9 through 12 of the microcontroller.

    The obstacle avoidance sensor is powered by the 5V power supply while its output pins is connected to digital pin 6 of the microcontroller. This works on HIGH and LOW voltage reverences. Such that the microcontroller uses the HIGH voltage it outputs when it detects an obstacle in its line of sight to set a condition that would allow the gate not to close when it is open and a car is parked between the gates.

    The IR receiver is connected to the analog pin 0 which reads the output pin of the IR receiver for HEX code signals. If there is no response from the microcontroller when the user press remote control to the face of the receiver, this is probably because the output pin of the receiver has disconnected from the A0 pin of the MCU.

    The stopper switches, which were used to detect when the gate has closed or open worked on analog voltage values such that when they are powered from a 5V reference, and the action of the moving gate tray lodges or dislodge them from this supply; the microcontroller notices these changes and know when the gate is open or not.

    The motor driver controls the two DC motors that control the movement of the gate trays. According to the circuit diagram; we connected the inputs of the motor driver to the microcontroller, which in turn outputs a control mechanism depending on which side of the inputs we feed in HIGH and LOW voltages (which is equivalent to 5V and 0V reference). We use the diodes there to prevent reverse feedback mechanisms in terms of voltage back to the MCU or damage to the motor driver chip as a result of electromagnetic energy collapsing when the motor is being cut off from power.

    Arduino Code for Smart Infrared Remote Control Gate System

    The programming of the microcontroller was done using the Arduino IDE. We were able to use the FTDI cable to burn programs into the chip by using the inbuilt complier provided by the Arduino IDE. Below is the code for the project design.

    /* THE FOLLOWING PROGRAM CONTROLS THE OPENING AND CLOSING OF 
     *  A GATING SYSTEM SUING AN INFRARED TRANSMITTER CONTROL> 
     *  ALSO KNOWN AS REMOTE CONTROLLED GATE
     *  Courtesy of Smartech Labs.
     * 
     *///include lcd lib
     #include <LiquidCrystal.h>
    //include IR lib
    #include <IRremote.h>
    //declare the instance Lcd and state where the data pins 
    LiquidCrystal lcd(8, 7, 9, 10, 11, 12);
    
    //declare and state where you connected the IR input pin
    int RECV_PIN = A0;
    
    long gateWaitTime = 30;
    long timeCount;
    long previousMillis = 0;
    
    boolean obstacleRemove = false;
    
    //declare an instance to receive the IR signal
    IRrecv irrecv(RECV_PIN);
    //decode the IR signals 
    decode_results results;
    
    //declare the limit switches
    int swtch1, swtch2, swtch3, swtch4;
    
    //declare the motordiver inputs
    #define motor1Backward 2
    #define motor1Forward 3
    #define motor2Backward 4
    #define motor2Forward 5
    
    
    //declare and define the pin for IR proximity sensor pin
    int proxSensorPin;
    
    void setup()
    {
      //begin serial monitor to comm with MCU and PC
      Serial.begin(9600);
      //begin the lcd screen and state what type of lcd used
      lcd.begin(16, 20);
      // In case the interrupt driver crashes on setup, give a clue
      // to the user what's going on.
      Serial.println("Enabling IRin");
      // Start the receiver
      irrecv.enableIRIn(); 
      Serial.println("Enabled IRin");
    
      //state the I/O pins
      pinMode(swtch1, INPUT);
      pinMode(swtch2, INPUT);
      pinMode(swtch3, INPUT);
      pinMode(swtch4, INPUT);
    
      pinMode(motor1Forward, OUTPUT);
      pinMode(motor1Backward, OUTPUT);
      pinMode(motor2Forward, OUTPUT);
      pinMode(motor2Forward, OUTPUT);
    
      //Print a welcome note
      lcd.setCursor(0, 0);
      lcd.print("WELCOME SMARTECH");
       lcd.setCursor(0, 1);
      lcd.print("     LABS               ");
      delay(2000);
      lcd.setCursor(0, 0);
      lcd.print("REMOTE CONTROLED");
       lcd.setCursor(0, 1);
      lcd.print("  GATE SYSTEM      ");
        delay(2000);
        lcd.setCursor(0, 0);
      lcd.print("  GATE SYSTEM      ");
             lcd.setCursor(0, 1);
      lcd.print("   PROJECT     ");
          delay(2000);
         lcd.setCursor(0, 0);
      lcd.print("  GATE SYSTEM      ");
             lcd.setCursor(0, 1);
      lcd.print("   PROJECT     ");
           lcd.setCursor(0, 0);
      lcd.print("  PLS PRESS A        ");
             lcd.setCursor(0, 1);
      lcd.print(" REMOTE COMMAND     ");
    }
    
    
    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        // Receive the next value
        irrecv.resume(); 
      }
    
      proxSensorPin = digitalRead(6);
      swtch1 = analogRead(A1);
      swtch2 = analogRead(A2);
      swtch3 = analogRead(A3);
      swtch4 = analogRead(A4);
    
    Serial.println(proxSensorPin);
    Serial.print(swtch1);
    Serial.print(" ");
    Serial.print(swtch2);
    Serial.print(" ");
    Serial.print(swtch3);
    Serial.print(" ");
    Serial.println(swtch4);
    
     if((results.value == 0xFFA25D) && (proxSensorPin == HIGH)) {
      if((swtch2 >= 900) && (swtch3 >= 900)){
      lcd.clear();
          lcd.setCursor(0, 0);
      lcd.print("  GATE OPENING      ");
      lcd.setCursor(0, 1);
       for(int i = 0; i < 10; i++){
        lcd.print(".");
        delay(100);
        digitalWrite(motor1Backward, HIGH);
      digitalWrite(motor2Backward, HIGH);
      digitalWrite(motor1Forward, LOW);
      digitalWrite(motor2Forward, LOW);
      }
      }
           lcd.clear();
     lcd.setCursor(0, 1);
     lcd.print("  GATE OPEN          ");
      
    }
    
    
    if((results.value == 0xFFE21D) && (proxSensorPin == HIGH)){
      if((swtch2 <= 90) && (swtch3 <= 90)){
      lcd.clear();
             lcd.setCursor(0, 0);
      lcd.print("  GATE CLOSING       "); 
      lcd.setCursor(0, 1);
      for(int i = 0; i < 10; i++){
        lcd.print(".");
        delay(90);
        digitalWrite(motor1Backward, LOW);
      digitalWrite(motor2Backward, LOW);
      digitalWrite(motor1Forward, HIGH);
      digitalWrite(motor2Forward, HIGH);
      } 
      }
          lcd.clear();
     lcd.setCursor(0, 1);
     lcd.print("  GATE CLOSE         ");
    
    }
    
    
    if(results.value == 0xFFE21D) {
      if(obstacleRemove == false){
       if((swtch2 <= 90) && (swtch3 <= 90)&& (proxSensorPin == LOW)){
        lcd.clear();
        lcd.setCursor(0, 0);
     lcd.print("OBSTACLE AT GATE  ");
     lcd.setCursor(0, 1);
     lcd.print(" PLEASE REMOVE     ");
     
        
       }
    }
    }
    
    if(results.value == 0xFFA25D) {
       if((swtch2 >= 900) && (swtch3 >= 900)&& (proxSensorPin == LOW)){
        lcd.clear();
          lcd.setCursor(0, 0);
      lcd.print("  GATE OPENING      ");
      lcd.setCursor(0, 1);
       for(int i = 0; i < 10; i++){
        lcd.print(".");
        delay(100);
         digitalWrite(motor1Backward, HIGH);
      digitalWrite(motor2Backward, HIGH);
      digitalWrite(motor1Forward, LOW);
      digitalWrite(motor2Forward, LOW);
      }
      }
      lcd.clear();
     lcd.setCursor(0, 1);
     lcd.print("  GATE OPEN          ");
    }
    
     else if(results.value == 0xFFE21D){
       if((swtch2 <= 90) && (swtch3 <= 90)&& (proxSensorPin == HIGH)){
      obstacleRemove = true;
      if(obstacleRemove == true){
      lcd.clear();
             lcd.setCursor(0, 0);
      lcd.print("  GATE CLOSING       "); 
      lcd.setCursor(0, 1);
      for(int i = 0; i < 10; i++){
        lcd.print(".");
        delay(90);
        digitalWrite(motor1Backward, LOW);
      digitalWrite(motor2Backward, LOW);
      digitalWrite(motor1Forward, HIGH);
      digitalWrite(motor2Forward, HIGH);
      } 
      lcd.clear();
     lcd.setCursor(0, 1);
     lcd.print("  GATE CLOSE          ");
    } 
       }
       obstacleRemove = false;
     }
    
    
    
    if(timeCount - previousMillis == gateWaitTime) {
    if((swtch2 <= 90) && (swtch3 <= 90)&& (proxSensorPin == HIGH) ){
         lcd.setCursor(0, 0);
      lcd.print("  GATE CLOSING       "); 
      lcd.setCursor(0, 1);
      for(int i = 0; i < 10; i++){
        lcd.print(".");
        delay(100);
        digitalWrite(motor1Backward, LOW);
      digitalWrite(motor2Backward, LOW);
      digitalWrite(motor1Forward, HIGH);
      digitalWrite(motor2Forward, HIGH);
      } 
      lcd.clear();
     lcd.setCursor(0, 1);
     lcd.print("  GATE CLOSE          ");
    }  
    }
    timeCount= previousMillis;
    timeCount = millis()/1000;
    Serial.println(timeCount);
        delay(500);
    }
    

    Uploading the above syntax into the Arduino IDE, we would find the system working as expected. It should be noted that the HEX codes used for controlling gate movement differs in each remote controls (IR transmitter modules). To learn how to decode your own HEX code, check out our tutorials on that.

    The LCD would display a welcome message and show the title of the project, smart infrared remote control gate system.

    project result display
    LCD display project title

    To view the tutorial video, just click on the youtube clip below to watch

    Applications of the Smart Infrared Remote Controlled Gate

    This smart IR remote-controlled gate system can be applied in various situations to enhance security and convenience. Here are a few use cases:

    • Residential Gates: Automate your home’s entrance gate to open or close with a simple remote control press.
    • Office or Commercial Spaces: Implement the system in office gates to control access for staff and visitors.
    • Garage Doors: Modify the system to automate the opening and closing of garage doors.
    • Parking Lot Gates: Use the system for controlling parking lot barriers or entry gates.

    The possibilities for this project extend far beyond just home use, as it can be adapted for various industries and applications.

    Conclusion

    Building a Smart Infrared Remote Controlled Gate System using Arduino is a fantastic project that merges security, automation, and convenience. This project allows you to easily control your gate’s opening and closing mechanism using an IR remote, making life simpler and more secure. The best part is that it’s a relatively simple system to build, even if you’re new to electronics and programming.

    With the ability to control gates, garage doors, or even other types of doors, this project has numerous practical applications. We hope this guide has inspired you to start building your smart gate system and explore further enhancements, such as adding sensors or timers to the system. Happy building!

    Now we have shown you how we achieved this project, smart infrared remote control gate system. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram communityTelegramFacebook pageInstagram and Twitter.

    Read More

    Frequently Asked Questions

    Can I use a different microcontroller for this project?
    Yes, you can use other microcontrollers like the ESP8266 or ESP32, but you’ll need to modify the wiring and code accordingly.

    How far can the IR remote control the gate?
    The range of the IR remote typically depends on the remote and the IR receiver you’re using. Most IR remotes have a range of about 5-10 meters.

    Can I add additional security features to this system?
    Yes, you can enhance the system by adding a keypad, fingerprint scanner, or RFID module to increase security.

    Can I control the gate using my smartphone instead of an IR remote?
    Yes, you can modify the system to work with Bluetooth or Wi-Fi, allowing you to control the gate with a smartphone app.

    Is it possible to use a motor instead of a servo to open larger gates?
    Absolutely! For larger or heavier gates, you can use a DC motor or an AC motor with a motor driver, depending on the gate’s size and weight.

  • How to build a Smart Hydroponics IoT Project

    How to build a Smart Hydroponics IoT Project

    In this project design, how to build a smart hydroponics IoT project, we designed and constructed a smart system that monitors and controls a hydroponics farm. The scope of the project is to measure pH, TDS value, humidity, air temperature, and water temperature of the nutrient solution. The project also automatically pumps water into the base nutrient bucket when the temperature is somewhat high or when the water level gauge says the water level is too low.

    Smart hydroponics systems use sensors, microcontrollers, and IoT technology to automate plant growth without soil. This project teaches you how to build a fully automated hydroponics system that monitors pH, EC/TDS, temperature, humidity, nutrient levels, water pump control, and real-time data logging to a mobile app.

    Enter the Smart Hydroponics IoT project, which integrates the power of Arduino and the Internet of Things (IoT) to automate the process. With IoT, you can remotely monitor parameters like pH, temperature, and water levels and even control nutrient delivery systems. This blog post will walk you through how to build a smart hydroponics system using Arduino and IoT.

    How the Smart Hydroponics System Works

    How the Smart Hydroponics System Works
    How the Smart Hydroponics System Works

    Here’s the workflow:

    System sends alerts when thresholds are exceeded, Sensors collect data, Atmega328P microcontroller processes inputs, Relay modules activate pumps/lights automatically, ESP-01 sends data to the cloud, Mobile App / Dashboard displays real-time values

    Hydroponics IoT Project: Materials for this Project

    • Arduino Uno standalone: The brain of the project that processes the sensor data.
    • pH Sensor: Measures the pH level of the water solution, essential for plant growth.
    • Temperature and Humidity Sensor (DHT11): Monitors the air temperature and humidity around the plants.
    • Water Level Sensor: Ensures the nutrient solution is at an adequate level.
    • Wi-Fi Module (ESP8266-01): Enables the IoT functionality by connecting the system to a cloud platform.
    • Relay Module: Controls pumps for water and nutrient delivery.
    • Water Pump: Circulates the nutrient solution.
    • LED Display (optional): Displays sensor readings locally.
    • Power Supply: To power the Arduino and sensors.
    • Connecting Wires and Breadboard: For wiring up the circuit.

    To design and develop the Arduino Uno standalone board, we using the following components mentioned here.

    Atmega328P-Pu microcontroller

    Hydroponics IoT Project
    Atmega328P-PU IC

    The Atmega328p-pu microcontroller was the type of 28-pin AVR chip used to program, sense, monitor and control the all the sensors used in the construction of this project. It is the brain of the project because it reads the analog sensors with its analog IO pins, sends serials communications and dislays results also on the display modules.

    16MHz crystal oscillator

    Hydroponics IoT Project: 16Mhz crystal oscillator
    16mHz CRYSTAL OSCILLATOR

    More commonly known as simply a crystal, the crystal oscillator creates an electrical signal with a very accurate frequency. In this case, the frequency is 16 MHz Crystals are not polarized. The schematic symbol is shown in Figure 3.12. The crystal determines the microcontroller’s speed of operation. For example, the microcontroller circuit we’ll be assembling runs at 16 MHz, which means it can execute 16 million processor instructions per second. That doesn’t mean it can execute a line of sketch or a function that rapidly, however, since it takes many processor instructions to interpret a single line of code.

    22pF Capacitors

    Hydroponics IoT Project: the 22pF capacitors used in the Arduino
    16MHz crystal with 22pF capacitors

    Perforated boards

    The Veroboard for permanent soldering design
    strip board for soldering contructed boards

    Dallas temperature sensor DS18B20:

    DS18B20 waterproof temperature sensor
    ds18b20 temperature sensor

    The DS18B20 digital thermometer provides 9-bit to 12-bit Celsius temperature measurements and has an alarm function with nonvolatile user-programmable upper and lower trigger points. The DS18B20 communicates over a 1-Wire bus that, by definition, requires only one data line (and ground) for communication with a central micro­processor. In addition, the DS18B20 can derive power directly from the data line (“parasite power”), eliminating the need for an external power supply.  Each DS18B20 has a unique 64-bit serial code, which allows multiple DS18B20s to function on the same 1-Wire bus. Thus, it is simple to use one microprocessor to control many DS18B20s distributed over a large area. Applications that can benefit from this feature include HVAC environmental controls, temperature monitoring systems inside buildings, equipment, or machinery, and process monitoring and control systems.

    5V Single Channel Relay Module

    hydroponics IoT project desing: the single channel relay module used for the auto pumping of water
    single channel relay module

    A relay is used to turn on and turn off the power supply that energizes the solenoid valve which pumps water into the hydroponic farm. The relay receives control signals from the microcontroller via an SMD transistor. A diode is used in parallel with the coil pin of relay to avoid sparking in the case of back EMF. because the coil is made of inductive material. The selection of the relay depends on the load of our system. For example, for a maximum load of our home devices, say, 10 amps. Another important thing considered while selecting a relay for this project was the switching speed of the relay. The relay speed was noted to be as fast as possible. Because the faster the switching speed of the relay, the more protection it will provide to the load devices when turning them on or off in the minimum possible time.

    pH Sensor

    hydroponics IoT project design: the pH sensor
    pH sensor

    Gravity Analog TDS Sensor

    IoT hydroponics project: TDS sensor
    TDS sensor module and probe

    The Total Dissolved Solid sensor was used in place of the Electrical Conductivity (EC) sensor because of its relatively low cost value compared the EC sensor. Also, because there is  a conversion scale between the EC sensor and the TDS sensor. This means that we could convert the reading of the TDS from its analog value to the reading in part per million(ppm).This  is an AVR microcontroller-compatible TDS sensor/Meter Kit for measuring TDS value of the hydroponic water. Used, in order to reflect the cleanliness of the water; and to conduct our water quality testing for the hydroponic culture.

    The module sensor supports 3.3- 5.5V wide range voltage input and 0 to 2.3V analog voltage output which makes it compatible with 5V or 3.3V control system or dev. boards. The excitation source is Ac signal, which can effectively prevent the probe from polarization and prolong the lifetime of the probe. also,  increase the output signal stability. The TDS probe is waterproof, it can e immersed in water for a long time for measurement. However, the probe should not be used in water with temperatures above 55 degrees centigrade. Again, the probe touching the container affects the reading of the TDS sensor.

    20×4 Liquid Crystal Display (LCD)

    LCD module connection

    An LCD is an electronic display module which uses liquid crystal to produce a visible image. The 20×4 LCD display is a very basic module commonly used in DIYs and circuits. It was used in a 4-bit configuration interfacing with the MCU. The 20×4 translates on a display 20 characters per line in 4 of such lines. In this LCD, each character is displayed in a 5×7-pixel matrix.  This is the visual output where all the commands made and decisions taken by the ‘brain’, the microcontroller unit (MCU) are displayed. It has 16 special pins that are mapped out for special functions.

    The ESP-01 Wi-Fi Module

    esp-01 for hydroponics IoT project
    ESP8266-01 WiFi module

    Relative Humidity and Temperature Sensor (DHT11)

    DHT11 digital humidity and temperature sensor

    The DHT11 is a low cost  digital humidity and temperature (DHT). This sensor is very basic and slow, but is great for some basic data logging. The DHT11 sensor is made of two parts, a capacitive humidity sensor and a thermistor. There is also a very basic chip inside that does some analog to digital conversion and spits out a digital signal with the temperature and humidity. The digital signal is fairly easy to read using any microcontroller.

    THE CIRCUIT DIAGRAM FOR THE DESIGN

    HYDROPONICS IoT Project Circuit diagram
    circuit diagram for the complete design

    Construction of the Circuit Diagram

    soldering IoT hydroponics circuit diagram project
    The microcontroller constructed
    Encasing hydroponics IoT project
    all sensors and power modules connected to the MCU

    Arduino Source Code

    PROGRAMMING THE DESIGN

    #include <SoftwareSerial.h>
    SoftwareSerial EspSerial(2, 3);
    
    String statusChWriteKey = "xxxxxxxxxxxxxxxxx";
    #define HARDWARE_RESET 4
    
    long writeTimingSeconds = 17;
    long startWriteTiming = 0;
    long elapsedWriteTime = 0;
    
    #include <DallasTemperature.h>
    #include <OneWire.h>
    #include "DHT.h"
    // include the library code:
    #include <LiquidCrystal.h>
    
    #define ONE_WIRE_BUS 6
    #define DHTPIN A0
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);
    
    boolean error;
    
    #define SensorPin A3            //pH meter Analog output to Arduino Analog Input 0
    #define Offset 0.00            //deviation compensate
    #define DHTTYPE DHT11   // DHT 11
    #define LED 13
    
    
    
    LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
    
    
    #define TdsSensorPin A1
    #define VREF 5.0      // analog reference voltage(Volt) of the ADC
    #define SCOUNT  30           // sum of sample point
    int analogBuffer[SCOUNT];    // store the analog value in the array, read from ADC
    int analogBufferTemp[SCOUNT];
    int analogBufferIndex = 0,copyIndex = 0;
    float averageVoltage = 0,tdsValue = 0,temperature = 25;
    
    DHT dht(DHTPIN, DHTTYPE);
    #define samplingInterval 20
    #define printInterval 800
    #define ArrayLenth  40    //times of collection
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex=0;
    
     float Celcius=0;
     float Fahrenheit=0;
     float h,t,f;
     static float pHValue,voltage;
     float newPH;
    
    int pumpStatus;
    int waterSense;
    int alarmSense;
     
    void setup(void)
    {
      EspSerial.begin(9600);
      Serial.begin(9600);
      Serial.begin(115200);
      pinMode(HARDWARE_RESET, OUTPUT);
      digitalWrite(HARDWARE_RESET, HIGH);
      EspHardwareReset();
      startWriteTiming = millis();
      pinMode(LED,OUTPUT);
      pinMode(TdsSensorPin,INPUT);
      pinMode(A5, OUTPUT);
      pinMode(A4, OUTPUT);
    
      analogWrite(A4, 255);
      analogWrite(A5, 0);
      
         sensors.begin();
      Serial.println("pH meter experiment!");    //Test the serial monitor
       Serial.println(F("DHTxx test!"));
    dht.begin();
    //begin the lcd sensor
       sensors.begin();
       lcd.begin(20, 4);
       lcd.setCursor(0, 0);
       lcd.print("   WELCOME JALANI");
       lcd.setCursor(0, 1);
       lcd.print("  SMART HYDROPONIC");
       lcd.setCursor(0, 2);
       lcd.print(" INTERNET OF THINGS");
       lcd.setCursor(0, 3);
       lcd.print("      PROJECT");
            delay(3000);
       lcd.clear();
       
       lcd.setCursor(0, 0);
       lcd.print("       PLS ");
       lcd.setCursor(0, 1);
       lcd.print("     GIVE TIME ");
       lcd.setCursor(0, 2);
       lcd.print("  FOR THE SENSORS ");
       lcd.setCursor(0, 3);
       lcd.print("     TO BOOTH ");
       delay(2000);
       lcd.clear();
       
     lcd.setCursor(1, 0);
     lcd.print("TEMP");
     lcd.setCursor(9, 0);
     lcd.print("TDS");
     lcd.setCursor(18, 0);
     lcd.print("pH");
     
     lcd.setCursor(0, 2);
     lcd.print("W.LEVEL");
     lcd.setCursor(9, 2);
     lcd.print("HUM");
     lcd.setCursor(14, 2);
     lcd.print("A.TEMP");
       
    }
    
    
    void waterLevel(){
      waterSense= analogRead(A2);
      Serial.println(waterSense);
      //print out on LCD
     lcd.setCursor(0, 3);
     lcd.print(waterSense);
     //lcd.setCursor(3, 3);
     //lcd.print("cm");  
      delay(500);
      
       if(waterSense > 500){
        analogWrite(A4, 0);
       }
    
       if(waterSense <= 240){
        analogWrite(A4, 255);
       }
       
    }
    
    void humSensor(){
      // Wait a few seconds between measurements.
      delay(2000);
    
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
       f = dht.readTemperature(true);
    
      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println(F("Failed to read from DHT sensor!"));
        return;
      }
    
      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);
    
      lcd.setCursor(8, 3);
      lcd.print(h);
      lcd.setCursor(15, 3);
      lcd.print(t);
    
      if(h <= 10.00){
        analogWrite(A5, 255);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("AIR TOO DRY");
      }
      else {
        
      }
    
      Serial.print(F("Humidity: "));
      Serial.print(h);
      Serial.print(F("%  Temperature: "));
      Serial.print(t);
      Serial.print(F("°C "));
      Serial.print(f);
      Serial.print(F("°F  Heat index: "));
      Serial.print(hic);
      Serial.print(F("°C "));
      Serial.print(hif);
      Serial.println(F("°F"));
    }
    
    void pH(){
      static unsigned long samplingTime = millis();
      static unsigned long printTime = millis();
      if(millis()-samplingTime > samplingInterval)
      {
          pHArray[pHArrayIndex++]=analogRead(SensorPin);
          if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
          voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
          pHValue = 3.5*voltage+Offset;
          samplingTime=millis();
      }
      if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        Serial.print("Voltage:");
            Serial.print(voltage,2);
                    newPH = pHValue + 5.60;
            newPH = map(newPH, 0.00, 14.00, 1.00, 14.00);
            Serial.print("    pH value: ");
        Serial.println(newPH,2);
    
        lcd.setCursor(17, 1);
     lcd.print(newPH);
     
        digitalWrite(LED,digitalRead(LED)^1);
        printTime=millis();
      }
    }
    double avergearray(int* arr, int number){
      int i;
      int max,min;
      double avg;
      long amount=0;
      if(number<=0){
        Serial.println("Error number for the array to avraging!/n");
        return 0;
      }
      if(number<5){   //less than 5, calculated directly statistics
        for(i=0;i<number;i++){
          amount+=arr[i];
        }
        avg = amount/number;
        return avg;
      }else{
        if(arr[0]<arr[1]){
          min = arr[0];max=arr[1];
        }
        else{
          min=arr[1];max=arr[0];
        }
        for(i=2;i<number;i++){
          if(arr[i]<min){
            amount+=min;        //arr<min
            min=arr[i];
          }else {
            if(arr[i]>max){
              amount+=max;    //arr>max
              max=arr[i];
            }else{
              amount+=arr[i]; //min<=arr<=max
            }
          }//if
        }//for
        avg = (double)amount/(number-2);
      }//if
      return avg;
    }
    
    
    void TDS(){
      static unsigned long analogSampleTimepoint = millis();
       if(millis()-analogSampleTimepoint > 40U)     //every 40 milliseconds,read the analog value from the ADC
       {
         analogSampleTimepoint = millis();
         analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin);    //read the analog value and store into the buffer
         analogBufferIndex++;
         if(analogBufferIndex == SCOUNT) 
             analogBufferIndex = 0;
       }   
       static unsigned long printTimepoint = millis();
       if(millis()-printTimepoint > 800U)
       {
          printTimepoint = millis();
          for(copyIndex=0;copyIndex<SCOUNT;copyIndex++)
            analogBufferTemp[copyIndex]= analogBuffer[copyIndex];
          averageVoltage = getMedianNum(analogBufferTemp,SCOUNT) * (float)VREF / 1024.0; // read the analog value more stable by the median filtering algorithm, and convert to voltage value
          float compensationCoefficient=1.0+0.02*(temperature-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
          float compensationVolatge=averageVoltage/compensationCoefficient;  //temperature compensation
          tdsValue=(133.42*compensationVolatge*compensationVolatge*compensationVolatge - 255.86*compensationVolatge*compensationVolatge + 857.39*compensationVolatge)*0.5; //convert voltage value to tds value
          //Serial.print("voltage:");
          //Serial.print(averageVoltage,2);
          //Serial.print("V   ");
          Serial.print("TDS Value:");
          Serial.print(tdsValue,0);
          Serial.println("ppm");
          
          lcd.setCursor(8, 1);
     lcd.print(tdsValue);
     lcd.setCursor(13, 1);
     lcd.print("ppm");
       }
    }
    int getMedianNum(int bArray[], int iFilterLen) 
    {
          int bTab[iFilterLen];
          for (byte i = 0; i<iFilterLen; i++)
          bTab[i] = bArray[i];
          int i, j, bTemp;
          for (j = 0; j < iFilterLen - 1; j++) 
          {
          for (i = 0; i < iFilterLen - j - 1; i++) 
              {
            if (bTab[i] > bTab[i + 1]) 
                {
            bTemp = bTab[i];
                bTab[i] = bTab[i + 1];
            bTab[i + 1] = bTemp;
             }
          }
          }
          if ((iFilterLen & 1) > 0)
        bTemp = bTab[(iFilterLen - 1) / 2];
          else
        bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
          return bTemp;
    }
    
    void loop(void)
    {
      sensors.requestTemperatures(); 
      Celcius=sensors.getTempCByIndex(0);
      Fahrenheit=sensors.toFahrenheit(Celcius);
       Serial.print(Celcius);
        Serial.print(" 'C  ");
    
       if(Celcius >= 85.00){
        analogWrite(alarmSense, 255);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("TEMP TO HIGH!");
       }
       else{
        
       }
         lcd.setCursor(0, 1);
     lcd.print(Celcius);
     lcd.setCursor(5, 1);
     lcd.print("'C");
     Serial.println(Celcius);
     delay(500);
     
      waterLevel();
       pH();
     humSensor();
      TDS(); 
      
    int pumpStatus = analogRead(A4);
    int alarmSense = analogRead(A5);
    
      //start: //label 
      //error=0;
      
      elapsedWriteTime = millis()-startWriteTiming; 
      
      if (elapsedWriteTime > (writeTimingSeconds*1000)) 
      {
           writeThingSpeak();
        startWriteTiming = millis();   
      }
      
      if (error==1) //Resend if transmission is not completed 
      {       
        Serial.println(" <<<< ERROR >>>>");
        delay (2000);  
        //goto start; //go to label "start"
      }
     }
    
     void writeThingSpeak(void)
    {
      startThingSpeakCmd();
      // preparacao da string GET
      String getStr = "GET /update?api_key=";
      getStr += statusChWriteKey;
      getStr +="&field1=";
      getStr += String(t);
     getStr +="&field2=";
      getStr += String(h);
       getStr +="&field3=";
      getStr += String(Celcius);
      getStr +="&field4=";
      getStr += String(newPH);
      getStr +="&field5=";
      getStr += String(tdsValue);
      getStr +="&field6=";
      getStr += String(waterSense);
      getStr +="&field7=";
      //getStr += String(pumpStatus);
      getStr +="&field8=";
      //getStr += String(alarmSense);  
      getStr += "\r\n\r\n";
      sendThingSpeakGetCmd(getStr);
    }
    
    void EspHardwareReset(void)
    {
      Serial.println("Reseting......."); 
      digitalWrite(HARDWARE_RESET, LOW); 
      delay(500);
      digitalWrite(HARDWARE_RESET, HIGH);
      delay(8000);//Tempo necessário para começar a ler 
      Serial.println("RESET"); 
    }
    /********* Start communication with ThingSpeak*************/
    void startThingSpeakCmd(void)
    {
      EspSerial.flush();//limpa o buffer antes de começar a gravar
      
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += "184.106.153.149"; // Endereco IP de api.thingspeak.com
      cmd += "\",80";
      EspSerial.println(cmd);
      Serial.print("enviado ==> Start cmd: ");
      Serial.println(cmd);
      if(EspSerial.find("Error"))
      {
        Serial.println("AT+CIPSTART error");
        return;
      }
    }
    /********* send a GET cmd to ThingSpeak *************/
    String sendThingSpeakGetCmd(String getStr)
    {
      String cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      EspSerial.println(cmd);
      Serial.print("enviado ==> lenght cmd: ");
      Serial.println(cmd);
      if(EspSerial.find((char *)">"))
      {
        EspSerial.print(getStr);
        Serial.print("enviado ==> getStr: ");
        Serial.println(getStr);
        delay(500);//tempo para processar o GET, sem este delay apresenta busy no próximo comando
        String messageBody = "";
        while (EspSerial.available()) 
        {
          String line = EspSerial.readStringUntil('\n');
          if (line.length() == 1) 
          { //actual content starts after empty line (that has length 1)
            messageBody = EspSerial.readStringUntil('\n');
          }
        }
        Serial.print("MessageBody received: ");
        Serial.println(messageBody);
        return messageBody;
      }
      else
      {
        EspSerial.println("AT+CIPCLOSE");     // alert user
        Serial.println("ESP8266 CIPSEND ERROR: RESENDING"); //Resend...
        //spare = spare + 1;
        error=1;
        return "error";
      }
    }
    

    The IoT Dashboard

    The above sketch is to be uploaded into the standalone board using the Arduino IDE and then the next step is to configure Thingspeak DB and create an app using MIT AppInventor.

    IoT dashboard thingspeak
    create a thingspeak account and log in

    To use thingspeak database, we need to create a Matlab account. Simply sign up on their website; www.thingspeak.com. After signing up, verify your email and sign in.

    IoT dashboard thingspeak
    name your project and set up the platform

    Once signed in, create a channel. Name your channel. Copy and safely store the API Write Key and the API Read Key. You can allocate your channel to any number of fields or charts. For us, we used 8 fields: 6 for sensors and 2 for actuators.

    setting the display channels
    The fields showing readings of each sensors assigned to it.

    After changing the API Write Key in your sketch, upload the code to see this working on the thingspeak channel you made.

    Creating the Hydroponics IoT Project Mobile App

    Next go to MIT app inventor website to create your app. After signing in, you can just import our already made .aia file into your project. You can edit any part of it to your taste. Just make sure to change the API write key to your own.

    AppInventor dashboard
    app inventor designer page for the app outlook
    creating the Hydroponics IoT project app on AppInventor
    When completing the designs on the app
    backend of hydroponics IoT Project App
    The block side of the app
    backend code
    checking the API Read Key authenticity

    once the app is done, you could either use the emulator to test it or you build and copy to your android phone for installation. After running the app, you can compare the reading with those updating on thingspeak DB.

    Now the sensor and actuator states can be viewed anywhere around the globe using a web app or a mobile app.

    But also the actuators, the Solenoid pump is meant to automatically pump water into the base bucket when the water level is too low and the alarm is meant to go off when the temperature is too high. The threshold for this state can be adjusted in the sketch above.

    🌿Applications & Use Cases

    This smart hydroponics project can be scaled and adapted for various applications:

    • Urban Farming: With space limitations in cities, this system can help grow plants in small spaces with minimal manual intervention.
    • Research: Scientists can use the system to study the effect of different environmental parameters on plant growth.
    • Commercial Agriculture: Large-scale hydroponic farms can benefit from the automation and remote monitoring provided by this project.
    • Home Gardens: For hobbyists, it’s a great way to grow vegetables or herbs at home without needing constant supervision.

    A visual tutorial is given in the YouTube video below.

    tutorial video

    Benefits of IoT-Based Smart Hydroponics

    Using IoT to automate a hydroponic system offers several key advantages:

    • Real-time Monitoring: You can keep track of your plants’ health from anywhere, ensuring optimal growing conditions.
    • Automation: The system automatically takes care of watering and nutrient delivery, reducing the need for manual intervention.
    • Data-Driven Decisions: By analyzing historical data, you can adjust environmental parameters for better plant growth.
    • Water Efficiency: Hydroponic systems are already water-efficient, and IoT adds another layer of control to minimize water waste.

    Conclusion

    You may use technology to promote sustainable farming by developing a Smart Hydroponics IoT Project. You can automate critical tasks like temperature, pH, and water level monitoring while also enabling remote access and control by utilizing Arduino and the Internet of Things. In addition to saving time, this project helps guarantee that your plants have the optimum growing conditions.

    A smart hydroponics system is a great way to embrace the future of farming, whether you’re an urban farmer, a researcher, or a gardening lover. So why hold off? Utilize the potential of IoT to take charge of your garden by starting to create your system today.

    Now we have shown you how we achieved this project, smart infrared remote control gate system. Kindly let us know if you were able to build such similar project or a better version. We will be very glad to help you the best we we can. Let us know if you have any further questions in the comment section. You can also drop a suggestion too! To join the conversation, join our Telegram communityTelegramFacebook pageInstagram and Twitter.

    Read More

    FAQs on Hydroponics IoT Project

    What is the role of the pH sensor in a hydroponics system? The pH sensor monitors the acidity or alkalinity of the nutrient solution. Maintaining the correct pH is crucial for optimal plant growth, as it affects nutrient absorption.

    Can I use a different Wi-Fi module instead of ESP8266 or ESP32? Yes, you can use other Wi-Fi modules like the ESP01 or NodeMCU, but ESP8266 and ESP32 are preferred due to their reliability and community support.

    Is this system scalable for commercial farming? Absolutely! This system can be scaled by adding more sensors, pumps, and relays. You can also expand the IoT features for more detailed data analysis and control.

    How do I ensure the sensors stay accurate over time? Regularly calibrating the sensors, especially the pH sensor, is essential. Over time, sensors can degrade, so it’s also important to replace them when necessary.

    Can this system work offline if there’s no internet connection? While the IoT features rely on an internet connection, the core system (sensor readings and relay controls) will continue to function offline, ensuring that plant care isn’t interrupted.