Smartech Labs https://smartechmolabs.com Evolve With Technology Wed, 28 Oct 2020 20:31:12 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.5 https://smartechmolabs.com/wp-content/uploads/2019/07/cropped-logo-1-2-32x32.png Smartech Labs https://smartechmolabs.com 32 32 Infrared Bidirectional Counter with AC bulb https://smartechmolabs.com/infrared-bidirectional-counter-with-ac-bulb/?utm_source=rss&utm_medium=rss&utm_campaign=infrared-bidirectional-counter-with-ac-bulb https://smartechmolabs.com/infrared-bidirectional-counter-with-ac-bulb/#respond Wed, 28 Oct 2020 11:20:20 +0000 https://smartechmolabs.com/?p=2121 This project uses two Infrared (IR) obstacle sensors o 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 person moving into the house direction according to this motion, Once the entrance count is above one (1), it will turn on an AC bulb. But if the direction of movement was from ight to left (Exit movement) it will decrement the number of count of people inside the house and will keep decrementing according to this directional motion until the count is zero and it will turn off the AC bulb.

The post Infrared Bidirectional Counter with AC bulb appeared first on Smartech Labs.

]]>
This 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 person moving into the house direction according to this motion, Once the entrance count is above one (1), it will turn on an AC bulb. But if the direction of movement was from ight to left (Exit movement) it will decrement the number of count of people inside the house and will keep decrementing according to this directional motion until the count is zero and it will turn off the AC bulb.

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

The circuit diagram for the project is shown below

circuit diagram for the project

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

The usual 4-bit communication protocol was adopted in connected the LCD to the Arduino Pro-Mini. A 2.7k 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 pin 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.

//iclude 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;
    } 
  
}

Basically, what we did above was to define some variables and Boolean states which took care for the change 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. Conditional if statements resets the Boolean states at the end of the loop function.

Watch video demonstration tutorial for more. Kindly leave us a comment and like. Thank you.

The post Infrared Bidirectional Counter with AC bulb appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/infrared-bidirectional-counter-with-ac-bulb/feed/ 0
Solar Based Smart Irrigation System with SMS Notification https://smartechmolabs.com/solar-based-smart-irrigation-system-with-sms-notification/?utm_source=rss&utm_medium=rss&utm_campaign=solar-based-smart-irrigation-system-with-sms-notification https://smartechmolabs.com/solar-based-smart-irrigation-system-with-sms-notification/#respond Tue, 20 Oct 2020 20:29:39 +0000 https://smartechmolabs.com/?p=2070 The design is an automated smart project that has the capacity of detecting the relative humidity, optimum temperature and soil moisture level of a garden or farm using special soil moiture sensors and relay this data to 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 water into the farm for irrigation purposes automatically. This means it totally eliminates the human labor part in running the successful irrigation in both arid and well rainfall places.

The post Solar Based Smart Irrigation System with SMS Notification appeared first on Smartech Labs.

]]>
In this project design, we will design a smart solar powered irrigation farm model with SMS alert. The system design is an automated smart project that has the capacity of detecting the relative humidity, optimum temperature and soil moisture level of a garden or farm using special soil moiture sensors and relay this data to 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 water into the farm for irrigation purposes automatically. This means it totally eliminates the human labor part in running the successful irrigation in both arid and well rainfall places.

MATERIALS

In assembling the components and parts needed for the design of this project; we took into consideration the underlined objectives: materials that are not so expensive, readily available and we could use 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.

Theoritical calculations

power consumption for DC pump and relay module

Designing 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.

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.

Formaica wrapping on plain wood surface

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

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.

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.

The arrangement of the solar irrigation system
wiring 12V DC pump
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.

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:

Screwing the screws that would hold the solar panel at an angle of 45°.
installing the Solar panel on the stand for its position

Circuit diagram for the Design

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();
      }
    }
  }

  SOURCECODE 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 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.

The post Solar Based Smart Irrigation System with SMS Notification appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/solar-based-smart-irrigation-system-with-sms-notification/feed/ 0
Anti-Theft and Burglar System with SMS Notification https://smartechmolabs.com/how-to-design-anti-theft-and-burglar-system-with-sms-notification/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-design-anti-theft-and-burglar-system-with-sms-notification https://smartechmolabs.com/how-to-design-anti-theft-and-burglar-system-with-sms-notification/#respond Mon, 12 Oct 2020 19:00:03 +0000 https://smartechmolabs.com/?p=2010 This is a security system design with SMS notification; programmed with Arduino with GSM module SIM800L, having PIR motion sensors and laser trip mechanisms. The Anti-theft and burglar system allows specific users to arm it and disarm it by phone call. During the armed state; the systems motion and laser...

The post Anti-Theft and Burglar System with SMS Notification appeared first on Smartech Labs.

]]>
This is a security system design with SMS notification; programmed with Arduino with GSM module SIM800L, having PIR motion sensors and laser trip mechanisms. The Anti-theft and burglar system allows specific users to arm it and disarm it by phone call. During the armed state; the systems motion and laser mechanisms are activated to sense for intruders senses when there is an intruder within the vicinity. When the system is armed and it informed the user via SMS that is is armed and it is alert for any intrusion. The users can also armed or disarm by calling the system design anytime.

In designing this project, the following components were used:

  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 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 since 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 detect this illegal motion, it gives off loud vary siren tones by 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 time possible while they were not aware or sleeping; maybe perhaps gone out. The siren dies down after a while when it is no longer sensing the movement within its line of sights.

Circuit Diagram Mode of Operation:

The MCU is selected to be 28 pin Atmel Atmega328P. The atmeag328P chip has four (4) pins for power. Pin 7 and pin 20 for Vcc and pin 8 and pin 22 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 know as the Receiver (Rx) and Transmitter (Tx) pins. This pins would form a crucial part in the FTDI pins connection as we would be using them to communicate between the MCU and the programming PC. 22pF capacitors are connected from pjn 9 and pin10 to GND respectively. This would help in sinking the noise generated by the internal switchings  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 CTR pin of the FTDI header pins.

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 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:

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

The compound model

The design for the Anti-theft burglary detection system 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.

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.

The front view

A model house s then placed inside this compound where the sensors are attached. The roof of the model house is a transparent plastic glass, which helps to view the circuit design from the top view angle.

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;
}

The post Anti-Theft and Burglar System with SMS Notification appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/how-to-design-anti-theft-and-burglar-system-with-sms-notification/feed/ 0
How to design IoT Based Air Quality Monitor For COPD Patients https://smartechmolabs.com/how-to-design-iot-based-air-quality-monitor-for-copd-patients/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-design-iot-based-air-quality-monitor-for-copd-patients https://smartechmolabs.com/how-to-design-iot-based-air-quality-monitor-for-copd-patients/#respond Tue, 15 Sep 2020 12:37:22 +0000 https://smartechmolabs.com/?p=1948 This project tutorial is about how to design an IoT based air quality monitor for Chronic Obstructive Pulmonary Disease (COPD) patients. The system design measure 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...

The post How to design IoT Based Air Quality Monitor For COPD Patients appeared first on Smartech Labs.

]]>
This project tutorial is about how to design an IoT based air quality monitor for Chronic Obstructive Pulmonary Disease (COPD) patients. The system design measure 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 reaserch, these gases comprises of the heavy contaminant gases that affect COPD patients a lot. The proposed algorithm is shown below:

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.

IoT based COPD schematic diagram
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

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

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.

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.

//Program Code for IoT Based Air Quality for COPD Patient
//include type of comm lib
#include <SoftwareSerial.h>
//type of comm pins connctn
SoftwareSerial EspSerial(9, 10);
//include the libs
#include <LiquidCrystal.h>
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 & NH3,  mq-136 = H2S,
#define GAS_CO2    1
#define GAS_NH3   3
#define GAS_H2S   4  

float CH4Curve[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[3]    = {2.3,0.72,-0.34};   //pt.1 (log200, log5.3), pt.2 (log10000, log1.5)
float NH3Curve[3]   = {1.0,0.23,-0.15};   //pt.1 (log10, log1.7), pt.2(log100, log1.2)
float H2SCurve[3]   = {1.3,0.11,-0.32};   //pt.1 (log20, log1.3) && 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("<<<<  C.O.P.D   >>>>");
  lcd.setCursor(0, 3);
  lcd.print("...PROJECT DESIGN...");
  delay(3000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("<<<PREPING SENSORS>>");
  lcd.setCursor(0, 1);
  lcd.print("PLEASE WAIT");
  lcd.setCursor(11, 1);
  for(int i = 0; i < 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 < 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 < 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 < 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 < 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 < 40) || (iPPM_NH3 < 40) || (iPPM_H2S < 40) || (iPPM_CO2< 40)){
  digitalWrite(buzzer, LOW);
  lcd.setCursor(16, 3);
  lcd.print("OFF");
 }

 if((iPPM_CH4 > 40) || (iPPM_NH3 > 40) || (iPPM_H2S > 40) || (iPPM_CO2 > 40)){
  digitalWrite(buzzer, HIGH);
  lcd.setCursor(16, 3);
  lcd.print(" ON"); 
 }
 

elapsedWriteTime = millis()-startWriteTiming; 
  
  if (elapsedWriteTime > (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(" <<<< ERROR >>>>");
    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<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<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<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<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[1])/pcurve[2]) + pcurve[0])));
}

long  MQ136GetPercentage(float rs_ro_ratio, float *pcurve){
  return (pow(10,( ((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0])));
}

/*this fxn writes to thingspeak*/
 void writeThingSpeak(void){
  startThingSpeakCmd();
  // preparacao da string GET
  String getStr = "GET /update?api_key=";
  getStr += statusChWriteKey;
  getStr +="&field1=";
  getStr += String(iPPM_CO2);  
 getStr +="&field2=";
  getStr += String(iPPM_H2S);
  getStr +="&field3=";
  getStr += String(iPPM_NH3);
  getStr +="&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 ==> 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 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.

The post How to design IoT Based Air Quality Monitor For COPD Patients appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/how-to-design-iot-based-air-quality-monitor-for-copd-patients/feed/ 0
How To Build An Radio Frequency IDentification (RFID) Based Bus Ticketing System https://smartechmolabs.com/how-to-build-an-radio-frequency-identification-rfid-based-bus-ticketing-system/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-an-radio-frequency-identification-rfid-based-bus-ticketing-system https://smartechmolabs.com/how-to-build-an-radio-frequency-identification-rfid-based-bus-ticketing-system/#respond Sun, 22 Mar 2020 21:02:18 +0000 https://smartechmolabs.com/?p=1896 Hi everyone, today we would be making an RFID based bus ticketing system that can be used for transport systems. This design would help bus drivers in ensuring proper fare collection from their passengers and cargoes. The system makes use of low cost RFID reader and cards and tags which...

The post How To Build An Radio Frequency IDentification (RFID) Based Bus Ticketing System appeared first on Smartech Labs.

]]>
Hi everyone, today we would be making an RFID based bus ticketing system that can be used for transport systems. This design would help bus drivers in ensuring proper fare collection from their passengers and cargoes. The system makes use of low cost RFID reader and cards and tags which are assigned a particular user and payment bundle amount. All the passenger needs to do is to just swipe his RFID card across the device to pay and gain bus transit access. For third world countries, this would save the passengers a lot of hassle and stress. Below are the steps followed to designing the project.

Materials For the Design:

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.

  • Resistors
  • LEDs
  • Stripboard (perforated or perf  board)
  • Atmeg328P microcontroller
  • 16MHz crystal oscillator (Newark part number 16C8140)
  • 22nF capacitors (2 pieces)
  • A 10KΩ pull-up resistor
  • A reset push button.
  • RFID- RC522 Module (with cards and tags)

  • 16 × 2 Liquid Crystal Display
  • 10KΩ potentiometer (trimmer)
  • 56OΩ precision resistor
  • LCD connector wires’
  • Header pins
  •  
The block diagram for the project design

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

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 bought down to the maker’s table and using breadboards and jumper wires. It is bread-boarded to test if it is working as specified. All errors encountered are checked and rechecked until the perfect solution is found.

breadboard testing of the design

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.

Casing the project in a box

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

coupling and casing the project

The Source code: 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();
             }

 

From line 2 through 6, we included the libraries we need 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 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.

The post How To Build An Radio Frequency IDentification (RFID) Based Bus Ticketing System appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/how-to-build-an-radio-frequency-identification-rfid-based-bus-ticketing-system/feed/ 0
How to Design Smart IR Remote Controlled Gate System https://smartechmolabs.com/smart-ir-remote-controlled-gate-system/?utm_source=rss&utm_medium=rss&utm_campaign=smart-ir-remote-controlled-gate-system https://smartechmolabs.com/smart-ir-remote-controlled-gate-system/#respond Thu, 05 Mar 2020 08:06:51 +0000 https://smartechmolabs.com/?p=1859 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.

The post How to Design Smart IR Remote Controlled Gate System appeared first on Smartech Labs.

]]>
In designing this project, 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.

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

Motor-Driven Mechanism (Gating system): This is made up of CD tray, DC motor and drive belt from an old DVD player machine.

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. The states of this stopper switch changes in any direction it makes. When it is full forward direction, the stopper switch is LOW and when it is full backward direction, the switch moves to HIGH. We used these change in states to control our gating 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.

L293D Motor Driver IC: 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.

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.

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 sensor are soldered on the same PCD board that has an adjustable potentiometer.

obstacle avoidance sensor

The two sensor LED are being 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 part the receiver doesn’t get to receive it. But if there is an obstacle in the transmitter 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 would automatically change the signal output on its  board (which is HIGH giving 1)  to LOW ( producing 0).

IR Receiver TSOP1838:

IR receiver 1838

This IR receiver operastws at 38KHz frequency and could decode the IR signals sent to it from the remote controller. The pinout diagram is shown above. The IR receiver however when test with non-programmable chips, shows some inconsistent signal received due to other its data pin.The IR receiver runs on 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 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

mp3 remote control (IR transmitter module)

The Complete Circuit Diagram:

IR Remote Control Gate System Schematic

The circuit diagram uses Atmega168 microcontroller. The microcontroller is design with 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 22pF capacitor connected to these same pin but to be used as 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 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 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 the 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 connection was needed since the output digital pins of the microcontroller was enough to communicate with the LCD module. The LCD is powered directly at the pin 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 Enable of the LCD connected to pin 8. The 4 data pins are connected at pin 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 microntroller. This works on HIGH and LOW voltage reverences. Such that the microcontroller uses the HIGH voltage it outputs when it detects obstacle in its line of sight to put 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 the two DC motors that controls the movement of the gate trays. According to the circuit diagram; we connected the inputs of the motor driver from 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 mechanism in terms of voltage back to the MCU or damaging of the motor driver chip as a result of electromagnetic energy collapsing when the motor is being cut off from power.

Programming the Microcontroler:

Theprogramming 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.

LCD display project title

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

https://youtu.be/vLYObmJQz0Q

The post How to Design Smart IR Remote Controlled Gate System appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/smart-ir-remote-controlled-gate-system/feed/ 0
How to build a Smart IoT Hydroponics Monitoring And Control Project Design https://smartechmolabs.com/smart-iot-hydroponics-monitoring-and-control-project-design/?utm_source=rss&utm_medium=rss&utm_campaign=smart-iot-hydroponics-monitoring-and-control-project-design https://smartechmolabs.com/smart-iot-hydroponics-monitoring-and-control-project-design/#respond Tue, 25 Feb 2020 10:09:53 +0000 https://smartechmolabs.com/?p=1814 This project design was made to monitor and control a hydroponics farm. The scope of the project is to measure pH, TDS value, humidity and 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 guage is saying water level is too low.

The post How to build a Smart IoT Hydroponics Monitoring And Control Project Design appeared first on Smartech Labs.

]]>
This project design was made to monitor and control a hydroponics farm. The scope of the project is to measure pH, TDS value, humidity and 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 guage is saying water level is too low.

Materials for this Project:

Atmega328P-Pu microcontroller:

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:

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:

16MHz crystal with 22pF capacitors

Perforated boards:

strip board for soldering contructed boards

Dallas temperature sensor DS18B20:

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:

single channel relay module

Relay is used to turn on and turn off the power supply that energize the solenoid valve which pumps water into the hydroponic farm. Relay get control signal from microcontroller through a transistor( an SMD type). Diode is use in parallel with coil pin of relay to avoid sparking in case of back EMF. Because coil is made of inductive material. The selection of the relay depended on load of our system. For example, for a maximum load of our home devices say, 10 Amperes. Another important thing considered while selecting relay for this project was switching speed of relay. The relay speed was noticed to be as fast as possible. Because the more the switching speed of relay, the more protection it will provide to the load devices when turning them on or off in minimum possible time.

pH Sensor :

pH sensor

Gravity Analog 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):

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:

ESP8266-01 WiFi module

Relative Humidity and Temperature Sensor (DHT11):

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

SMART HYDROPONICS CONTROL AND MONITORING
circuit diagram for the complete design

Construction of the circuit:

The microcontroller constructed
all sensors and power modules connected tot he MCu

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 above sketch is to be uploaded into the standalone board using the Arduino IDE and then the next is to configure thingspeak DB and create an app using MIT appinventor.

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.

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 any number of fields or charts. For us, we used 8 fields: 6 for sensors and 2 for actuators.

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.

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.

app inventor designer page for the app outlook
When completing the designs on the app
The block side of the app
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 states can be adjusted int he sketch above.

A visual tutorial is given in the youtube video below.

tutorial video

I hope this project tutoral helps you. Thank you.

The post How to build a Smart IoT Hydroponics Monitoring And Control Project Design appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/smart-iot-hydroponics-monitoring-and-control-project-design/feed/ 0
How to Design A Power Management System (Smart Fan Project) https://smartechmolabs.com/power-management-system-smart-fan-project/?utm_source=rss&utm_medium=rss&utm_campaign=power-management-system-smart-fan-project https://smartechmolabs.com/power-management-system-smart-fan-project/#respond Thu, 13 Feb 2020 18:04:21 +0000 https://smartechmolabs.com/?p=1787 This project redesigns a standing AC fan to a smart automated version that uses a passive Infrared (PIR) sensor to detect human presence then with the help of an real time clock (RTC) sets two different time modes. Namely, the "Remote Active Mode" and the "Auto Sense Mode". During the " Remote Active Mode " also known as the working hour, the user could the remote control to access the type of speed selection he/she wants. During the Auto Sensing mode the fan controls itself automatically. With the RTC sensor, the fan could tell when it is time for auto mode. And then using the PIR sensor, it could detect human motion and know when there is somebody around needing cool air ventilation. IF the fan senses motion, it would turn itself on and runs on a constant speed which is the speed two but if after some time, it couldn't detect any motion, it would turn itself off.

The post How to Design A Power Management System (Smart Fan Project) appeared first on Smartech Labs.

]]>
This project redesigns a standing AC fan to a smart automated version that uses a passive Infrared (PIR) sensor to detect human presence then with the help of an real time clock (RTC) sets two different time modes. Namely, the “Remote Active Mode” and the “Auto Sense Mode”. During the ” Remote Active Mode ” also known as the working hour, the user could the remote control to access the type of speed selection he/she wants. During the Auto Sensing mode the fan controls itself automatically. With the RTC sensor, the fan could tell when it is time for auto mode. And then using the PIR sensor, it could detect human motion and know when there is somebody around needing cool air ventilation. IF the fan senses motion, it would turn itself on and runs on a constant speed which is the speed two but if after some time, it couldn’t detect any motion, it would turn itself off.

The project design started with us designing the circuit diagram using the Fritzing circuit IDE. As shown in the picture below.

Circuit Diagram for the project design

Following the circuit diagram, we built the standalone development board aroung the Atmega328P-U microcontroller. For other projects that used Atmega328P-PU microcntroller, check out: Atmega328P-U projects

So here, the atmega328P-U microcontroller unit (MCU) is programmed using the FTDI ISP programmer as shown above. We used a DS3231 type of RTC to keep and set our time. We used a PIR sensor to detect the motion also. The connection is set such that the the serial clock pin (SCL) and the serial data pin (SDA) of the RTC are connected to the analog pin 5 (A5) and analog pin 4 (A4) of the MCU respectively. The PIR output is connected to the the digital pin 10 of the Atmega328P-U.

Next that takes our interest is the 16×4 LCD connection. As shown in the circuit diagram, we are using 4-bit connection mode (4 wire type connection). We connected out Register select (RS) to D3 of the MCU, Enable pin (E) to D4 and the four data pins to digital pin 8 through down to 5.

Note: If you are using a power supply that has DC output above 5V, you have to use a voltage regulator as shown in the circuit diagram to buck it down to 5V since the MCU uses 5V DC output. but ensure that your 5V meets up to 3A. Otherwise, during relay switch, the LCD screen may scatter and start misbehaving. Also, if you don’t use 5V DC supply, the whole system would end up getting fried.

Now to switch the states of the AC standing fan, we need 3-channel relay module to change the speed controls automatically.

Speed regulator switch

Here we disconnected the normal speed selector switch found on the standing fan and extended out with more wires. Then the AC live wire is connected to the common of the relays while the respective speed lines are connected to the other three as shown in the picture above. The neutral line of the AC is connected to the neutral of the Fan induction coil.

After the connection has been made, the PIR sensor and the RTC is connected too to the MCU board. The LCD module is connected to its headerpin. Next is to program the MCU. Copy the code below into your Arduino IDE.

#include <Wire.h>

#include <RTClib.h>

#include <EEPROM.h>

#include <IRremote.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd(3, 4, 8, 7, 6, 5);

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

#define speed1 A0
#define speed2 A1
#define speed3 A2
int RECV_PIN = 2;
const int PIR = 10;
unsigned long count = 0;
int state = LOW;
int currentState = 0;
int previousState = 0;
int sensor_count = 0;
int timer = 0;
int ts = 50;
int tc = ts;
int sc = 10;
int fail = 0;
int ms = 50;
unsigned long pm = 0;
const long interval = ms;
boolean logic;

byte val0 = EEPROM.read(0);
byte val1 = EEPROM.read(1);
byte val2 = EEPROM.read(2);

int ontime = val1;
int offtime = val2;
int menu = 0;
int pause = 50;
int rtcDAY, rtcMONTH, rtcYEAR, rtcHOUR, rtcMIN, rtcSEC;
int minus = 0;
int plus = 0;
int fan = 0;
String remote;
String stat = ""; 
String SPEED = "";

IRrecv irrecv(RECV_PIN);
decode_results results;

void page(){
    DateTime now = rtc.now();
    lcd.setCursor(0, 0);
    lcd.print("RUKE's SMART FAN");
    lcd.setCursor(0, 1);
    lcd.print(SPEED);
    lcd.setCursor(0, 2);
    lcd.print(stat); 
    lcd.setCursor(0, 3);
    lcd.print(now.day(), DEC);
    lcd.print('/');
    lcd.print(now.month(), DEC);
    lcd.print('/');
    lcd.print(now.year(), DEC);
    lcd.print("  ");
    lcd.print(now.hour(), DEC);
    lcd.print(':');
    lcd.print(now.minute(), DEC);
           }
void fanOff(){
   //turn the fan off
   analogWrite(speed1, 255);
   analogWrite(speed2, 255);
   analogWrite(speed3, 255);
   SPEED = "     FAN OFF      ";
}
void spd1(){
   //turn the fan off
   analogWrite(speed1, 0);
   analogWrite(speed2, 255);
   analogWrite(speed3, 255);
   SPEED = "     speed 1      ";
}
void spd2(){
   //turn the fan off
   analogWrite(speed1, 255);
   analogWrite(speed2, 0);
   analogWrite(speed3, 255);
   SPEED = "     speed 2      ";
}
void spd3(){
   //turn the fan off
   analogWrite(speed1, 255);
   analogWrite(speed2, 255);
   analogWrite(speed3, 0);
   SPEED = "     speed 2      ";
}
void SenSe(){
  unsigned long cm = millis();
unsigned long rr = cm - pm;
if(rr > interval){
   if(digitalRead(PIR)==HIGH){
    sensor_count = sensor_count + 1;
       }
timer = timer + 1;
pm = cm;
 if(timer >= tc){
  if((sensor_count >= sc) && (tc >= ts)){    
    spd2();
    tc = 0;
    fail = 0;
  }
  else{
    fail = fail + 1;
    tc = ts;
    //interval = ms;
  }
  timer = 0;
  sensor_count = 0;
    }
}
if(fail > 20){
  fail = 0;
  fanOff();
  }
}

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
lcd.begin(16, 4);

pinMode(speed1, OUTPUT);
pinMode(speed2, OUTPUT);
pinMode(speed3, OUTPUT);
pinMode(PIR,INPUT);

if (! rtc.begin()) {
  lcd.setCursor(0, 0);
    lcd.print("Can't find RTC");
    delay(3000);
    while (1);
  }

  if (rtc.lostPower()) {
    lcd.setCursor(0, 0);
    lcd.print("RTC lost power!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    
    delay(3000);
  }

// In case the interrupt driver crashes on setup, give a clue
  // to the user what's going on.
  Serial.println("Enabling IRin");
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("Enabled IRin");

  fanOff();
}

void loop() {
  // put your main code here, to run repeatedly:
  DateTime now = rtc.now();
  rtcHOUR = now.hour(), DEC;
  if (irrecv.decode(&results)){
  remote = String(results.value, HEX);
    if(remote == "511dbb"){
   menu = 1;
  }
    Serial.println(menu);
    Serial.println(fan);
    Serial.println(remote);
    irrecv.resume(); // Receive the next value
  }
 
  if((rtcHOUR >= ontime) && (rtcHOUR <offtime))//Comparing the current time with the Alarm time
    { 
      stat = "    Auto Mode      ";
      SenSe();
    
    }
    else{
      if(remote == "c101e57b"){
        fanOff();
    }
    if(remote == "9716be3f"){
        spd1();
    }
    if(remote == "3d9ae3f7"){
        spd2();
    }
    if(remote == "6182021b"){
        spd3();
    }
     stat = "  Remote Active     ";
    
     
    }
if(menu < 1){
page();
}
    menu = constrain(menu, 0, 5);
    switch(menu){
  case 1:
    lcd.setCursor(0, 0);
    lcd.print("**Control MENU**  ");
    lcd.setCursor(0, 1);
    lcd.print(">1. FAN ON Time  ");
    lcd.setCursor(0, 2);  
    lcd.print(" 2. FAN OFF Time  ");
    lcd.setCursor(0, 3);  
    lcd.print(" 3. EXIT MENU      ");
      if(remote == "a3c8eddb"){
      menu++;
       if(menu > 3){
      menu = 1; }
          }
      if(remote == "f076c13b"){
      menu--;
       if(menu < 1){
      menu = 3; }
           }
      if(remote == "e5cfbd7f" && menu == 1){
      menu = 4;      
      }   
      break;
  
 case 2:
    lcd.setCursor(0, 0);
    lcd.print("**Control MENU**  ");
    lcd.setCursor(0, 1);
    lcd.print(" 1. FAN ON Time     ");
    lcd.setCursor(0, 2);  
    lcd.print(">2. FAN OFF Time   ");
    lcd.setCursor(0, 3);  
    lcd.print(" 3. EXIT MENU    ");
      if(remote == "a3c8eddb"){
      menu++;
       if(menu > 3){
      menu = 1;}
            }
      if(remote == "f076c13b"){
      menu--;
       if(menu < 1){
      menu = 3; }
          }
      if(remote == "e5cfbd7f" && menu == 2){
      menu = 5;      
      }   
    break;

   case 3:
    lcd.setCursor(0, 0);
    lcd.print("**Control MENU**  ");
    lcd.setCursor(0, 1);
    lcd.print(" 1. FAN ON Time");
    lcd.setCursor(0, 2);  
    lcd.print(" 2. FAN OFF Time");
    lcd.setCursor(0, 3);  
    lcd.print(">3. EXIT MENU    ");
      if(remote == "a3c8eddb"){
      menu++;
       if(menu > 3){
      menu = 1;}
        }
      if(remote == "f076c13b"){
      menu--;
       if(menu < 1){
      menu = 3;
      }
            }
    if(remote == "e5cfbd7f" && menu == 3){
      menu = 0; }
    break; 

  case 5:
    lcd.clear();
    offtime = constrain(offtime, 0, 23);
    lcd.setCursor(0, 0);
    lcd.print(" SET AC OFF Time:   ");
    lcd.setCursor(0, 2);  
    lcd.print("New Time = ");
    lcd.print(offtime);
    lcd.print(":00      ");
    if(remote == "a3c8eddb"){
      offtime++;
       if(offtime > 23){
      offtime = 0;
      }
          }
    if(remote == "f076c13b"){
    offtime--;
    if(offtime < 0){
      offtime = 23;
      }
       }
    if(remote == "e5cfbd7f" && menu == 5){
      EEPROM.update(2, offtime);
      menu = 2;
    }
    break;

  case 4:
    lcd.clear();
    ontime = constrain(ontime, 0, 23);
    lcd.setCursor(0, 0);
    lcd.print(" Set FAN ON Time   ");
    lcd.setCursor(0, 2);  
    lcd.print("New Time = ");
    lcd.print(ontime);
    lcd.print(":00      ");
    if(remote == "a3c8eddb"){
      ontime++;
       if(ontime > 23){
      ontime = 0;}
          }
    if(remote == "f076c13b"){
      ontime--;
       if(ontime < 0){
      ontime = 23;}
          }
    if(remote == "e5cfbd7f" && menu == 4){
      EEPROM.update(1, ontime);
      menu = 1;
    }
    break;
      }
      remote = "";
      delay(50);
    }

As shown from above, four libraries are needed in this sketch: the RTC library, the lcd library, the IR receiver library and the EEPROM lib. Although some of these libraries are already in the Arduino IDE.

You can change the time for the Remote active mode and the Auto mode in the design after successful uploading the code and using your remote controller to adjust it. To design which of the button does your bidding, you have to run the IR receiver test and map out the received IR HEX values. Then you would in turn use these HEX codes, to assign a specific command in the IF statement you coded.

We used Analog pins for your relay module inputs which in turn controls the AC fan speeds and we defined in the code lines above. The page function greeting message could be altered to any of the programmer’s choice. functions like fanOff(), spd1(), spd2() and spd3() were used to control the state of each relay on the relay module and which in turn regulate the fan speed. As seen in the sketch, function fanOff() turns off all the inputs of the relay module by gving them 8-bit -1 (255) voltage level (which is a HIGH). Since the relay module is active LOW, this would turn off all the inputs.

function SenSe() controls the PIR sensor and its count mechanism. Virtually, we just increased the delay time to 10 seconds (int sc =10). After 20 seconds in the auto mode and it doesn’t sense any motion it automatically turns off.

A visual tutorial is giving below for more explanation.

Smart Fan Project

The post How to Design A Power Management System (Smart Fan Project) appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/power-management-system-smart-fan-project/feed/ 0
How to Build an SMS based Metal detector https://smartechmolabs.com/sms-based-metal-detector/?utm_source=rss&utm_medium=rss&utm_campaign=sms-based-metal-detector https://smartechmolabs.com/sms-based-metal-detector/#respond Sat, 28 Sep 2019 23:30:40 +0000 https://smartechmolabs.com/?p=1728 The SMS based metal detector detects metals and electronics devices and sends out SMS notifications to defined user or users

The post How to Build an SMS based Metal detector appeared first on Smartech Labs.

]]>
The metal detector with SMS alert system design is a project design that incorporates a metal detector sensor to detect metallic objects in close proximity. It comes with an SMS enabled notifying upgrade that would instantaneously send out an SMS to a predefined personnel’s phone number once a metal or electronic device(s) was detected. The design has features like its portable size and runs on rechargeable batteries. In designing this project, we had to calculate the feasibility of the needed materials cost in order to make sure that we were undertaking an exorbitant project. This SMS based metal detector project is about metal detector design with SMS notification. Below is a description of the components used for the implementation of the Metal Detector with SMS Alert system design.

MATERIALS:

3.7V 1800mAh Li-ion Rechargeable Battery

3.7V 1800mAh Casing

3.7 Lipo 1A Battery Charging Board Charger Module Mini USB Interface

LM323T Voltage Regulator

The 1k resistor

330-ohm resistor

LED

1N4148 diode

Perforated board (stripped line type)

Connecting jumper wire

10nF capacitor

GSM Module (SIM900L)

5V Passive Buzzer

3.7V 1800mAh Li-ion Rechargeable Battery:

The Power Unit for the design depended mainly on DC supply from rechargeable batteries, each rated 3.7V 1800mAh. And 3 pieces of 3.7V 1800mAh Li-ion batteries gave us the needed Voltage for GSM module. Also, these were rechargeable batteries so we used Lipo battery charging board.

3.7V 1800mA LiPo Battery
3.7V 1800mA LiPo Battery

The 3.7V rechargeable battery that can output current of 1.8A in one hour. It is durable and can be charged very fast. It is also portable and as such was ideal for using as a power source for the project design.

3.7V 1800mAh Casing:

The above pictured batteries needed a casing so we used One 3.6V-3.7V Battery Charging Discharging Control Holder Case  Li-ion w/1S3P PCM.

3.6V-3.7V Battery Charging Discharging Control Holder Case  Li-ion w/1S3P PCM
3.6V-3.7V Battery Charging Discharging Control Holder Case  Li-ion w/1S3P PCM

This is a plastic DIY Lithium battery box battery holder with pin suitable for 2×18650 (3.7V-7.4V) Lipo battery. The casing is of high quality and can withstand temperatures of about 95°C. It maintains firm hold with the batteries inside it and offers safety from short circuiting and wire burn out. A total of 3 battery were connected in series to give us a 12V approximately 5A output for the GSM module.

3.7 Lipo 1A Battery Charging Board Charger Module Mini USB Interface:

3.7 Lipo Charger
3.7 Lipo Charger board

The Lipo charging board module uses mature charging chip TP4056, simple peripheral circuits that has good protection performance and high charging accuracy. It comes with full machinery automated processing and has high reliability. Its output charging current can be adjusted by just changing the circuit board fixed resistors, this would in turn change the output current to the 100mA-1000mA. The Input reverse connection has no effect on the chip, but the output (battery end) reverse connection will burn out the chip. When measuring with an Ampere meter, it is best in series connected to the 5V input end. The charging current is best to be 0.37 times of the battery capacity,
It is very convenient for portability an size conservation.   Below is a summary of its datasheet.

Datasheet Specificatiuon:

Item Name: Lipo battery charging board
Item NO. : TP4056
Charging Method: linear charge
Charging Current: 1A Adjustable
Charge Accuracy: 1.5 pct
Input Voltage: 4.5V – 5.5V
Full Charge Voltage: 4.2V
Charging Indicator: Blue light lit charge,red light lit full charge
Charging Input Interface: Mini USB
Working Temperature: -10 Degree to +85 Degree
Reverse: NO
Usage: Used for single lipo or multi-section lipo parallel charging, can take power from the USB port.
Current Regulation: Can auto regulate current charging.

LM323T Voltage Regulator:

LM323T voltage regulator IC and pinout







LM323T voltage regulator IC and pinout

The voltage regulator IC, L232T is used to provide a regulated 5V DC output. Input voltage fed into the input pin (pin 1) was 2 volts more than the rated output voltage (in our own case 12V) for proper working of Integrated Circuit (IC). For better results, a filter ripple capacitor of 1uF was connected to the output of the IC L323T to eliminate the noise, produced by transient changes in voltage.

Datasheet Specifications:

Output Voltage: +5V, up to 3A with peak current of 4.5A

Current Output: up to 3.5A

Input Voltage: 7V Minimum, 35V Maximum

Package : TO-220

Pin Spacing Pitch : 2.54mm (0.1in)

Hole Diameter : 3.8mm (0.15in)

STMicroelectronics Part Number:  L323T

Metal Detector Unit:

This unit is mainly composed of the resistor, the inductor and the capacitor used to for the EMF pulsating device. In our design resistor-inductor-capacitive (RLC) circuit, we made us of a hand-made 150 coil turns of size wire gauge 30 wound about a diameter of 6cm to form the EMF emitting part of our design.

The whole SMS based Metal detector design depends on us building an LC high pass filter with the help of a coil and a capacitor. According to the equation of Mutual inductance;

Where,

L is Inductance in Henry

μo   is permeability, its 4π*10-7 for Air

N is number of turns of wire coil

A is inner Core Area (πr2) in m2

L is length of the Coil in meters

Whenever a current passes through a coil, it generates a magnetic field around it. And the change in the magnetic field generates an electric field. Now according to Faraday’s law, because of this Electric field, a voltage develops across the coil which opposes the change in magnetic field and that’s how our coil develops the Inductance, means the generated voltage opposes the increase in the current.

When we place a metal near the coil then coil changes its inductance. This change in inductance depends upon the metal type. And  for a ferromagnetic material like iron it increases. Although, it decreases for non-magnetic materials.

The medium of flow of magnetic field generated by the inductor is nothing or air. Depending on the core of the coil, inductance value changes drastically.

The coil wound here is an air cored one, so when we bring a metal piece near the coil, the metal piece acts as a core for the air cored inductor. Hence,  the inductance of the coil changes or increases considerably. With this sudden increase in inductance of coil the overall reactance or impedance of the LC circuit changes by a considerable amount when compared without the metal piece.

 

5cm diameter Coil:

10nF 100VDC Polyester Capacitor:

10nF polyester capacitor used in the design






10nF polyester capacitor used in the design

Polyester capacitors offer good stability, a large range of values at low cost, and it is used for charging and discharging the inductor in the circuit.

330Ω RESISTOR:






330Ω 1/4W Metal Film Precision Resistor

Specifications:

  • Resistance: 330 Ohms
  • Wattage Rating: 0.25 Watt
  • Tolerance: 1%
  • Metal Film
  • Lead Free
  • ROHS compliant
  • Diameter of Leads: 0.43mm (0.02in)
  • Length of Leads: ~28mm (1.1in)

IN4148 DIODE:

IN4148 diode
IN4148 diode

The 1N4148 is a standard silicon switching signal diode. This diode, 1N4148 can switch within applications of up to about 100 MHz with a reverse-recovery time of no more than 4 ns. It was fabricated in planar technology, and encapsulated in a hermetically sealed leaded glass DO-35 package.

SIM900L GSM module:

SIM900L GSM shield module






SIM900L GSM shield module

SIM900L GSM/GPRS shield is a GSM modem. It allows  what a normal cell phone can do: Make or receive phone calls, connecting to internet through GPRS, TCP/IP, and more. It supports quad-band GSM/GPRS network, meaning it works pretty much anywhere in the world. The shield itself was designed to surround the SIM900L chip.

pin diagram of SIM900L from lastminute engineers






pin diagram of SIM900L from lastminuteengineers.com

900L Shield LED Status Indicators:

900L Shield LED Status Indicators:
900L Shield LED Status Indicators

The LEDs blinking statuses on the SIM900L board has different interpretation. The LEDs on the board is two, namely:

PWR: This LED is connected to the shield’s power supply line. If this LED is on, the shield is receiving power.

Status: This LED indicates SIM900’s working status. If this LED is on, the chip is in working mode.

Netlight: This LED indicates the status of our cellular network. It blinks at various rates to show what state it’s in.

  • off: The SIM900 chip is not running
  • 64ms on, 800ms off: The SIM900L chip is running but not registered to the cellular network yet.
  • 64ms on, 3 seconds off: The SIM900 chip is registered to the cellular network & can send/receive voice and SMS.
  • 64ms on, 300ms off: The GPRS data connection we requested is active.

Powering the SIM900L:

Depending on which state it’s in, the SIM900 can be a relatively power-hungry device. The maximum current draw of the chip is around 2A during transmission burst. It usually won’t pull that much, but may require around 216mA during phone calls or 80mA during network transmissions.

 The PWRKEY button of the Sim900L
The PWRKEY button of the Sim900L

To use the SIM900L, we hard to turn on the chip. To do this we had to press and hold (for a few seconds) the ON button by the side as shown in the figure above. But we needed to turn on the GSM module every time we power on the design. To do this we had to use the software trigger version of turn on the GSM  module. We first connected the D9 of the SIM900L to D9 of the MCU. Next we soldered the SMD jumper as shown in the figure below:

.







the solder jumper to be joined together.

Interfacing GSM module Sim900L with MCU:

Using the UART Communication:

The SIM900 GSM/GPRS shield uses universal asynchronous receiver-transmitter (UART) protocol to communicate with the MCU. The chip supports baud rate from 1200bps to 115200bps with Auto-Baud detection.

Two options of connections: software serial and hardware serial select pins

Afer ensuring that the jumper cap is placed on the software serial port select, we connected the MCU according to the circuit diagram shown in figure below.

Although the GSM module could also work on 5V DC but we connected the sim900L to an external power of source of not less than 7V 2A supply. The module adjustable voltage regulator makes it possible for it to handle the voltage at this level.

We used a 2G full sized SIM card and inserted it at the back of the module in its SIM socket. We were careful enough to unlock the latch, push the top part of the assembly, and then lift it up.  We Placed the SIM card into the bottom part of the socket. Then fold the arm back into the body of the socket, and gently push it forward towards the LOCK position.

Hence, the new circuit diagram would be thus:

5V Passive Buzzer:







passive buzzer type used in the design

Generating pulse from the Microcontroller:

circuit diagram of the MCU pulse generator

We send a pulse from our microcontroller to the RL high pass filter, as such, short spikes will be generated by the coil in every transition. The pulse length of the generated spikes is proportional to the inductance of the coil. So with the help of these spike pulses we can measure the inductance of Coil. But here it is difficult to measure inductance precisely with that spikes because that spikes are of very short duration. We used a capacitor to solve this problem which is charged by the rising pulse or spike. And it required few pulses to charge the capacitor to the point where its voltage can be read by analog pin ADC0. And the microcontroller reads the voltage of this capacitor by using ADC syntax. After reading voltage, capacitor quickly discharged since we made it an output and setting it to LOW. This whole process takes around 200 microseconds to complete. For better result, we repeat measurement and took an average of the results. That’s how we can measure the approximate inductance of Coil. After getting the result we transfer the results to the LED and buzzer to detect the presence of metal.

In our program to be uploaded into the MCU, we created a function where we can turn on the sim900L using software trigger. The syntax for the program was:

Testing Attention (AT) Commands:
For sending AT commands void SIM900power()
{
  pinMode(9, OUTPUT); 
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH)

Testing Attention (AT) Commands:

For sending AT commands and communicating with the SIM900 shield, we will use the serial monitor. Below codes are the the syntax that will enable the MCU to communicate with the SIM900 shield on serial monitor window.

//since we were using the software serial, we added the library
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
//SIM900 Tx & Rx is connected to MCU #7 & #8
SoftwareSerial mySerial(7, 8); 

void setup()
{
  //Begin serial communication 
  Serial.begin(9600);
  
  //Begin serial communication with MCU and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

//Handshaking with SIM900
  mySerial.println("AT");   
updateSerial();
//Signal quality test, value range is 0-31 , 31 is the best
  mySerial.println("AT+CSQ"); 
  updateSerial();
//Read SIM information to confirm whether the SIM is plugged
  mySerial.println("AT+CCID"); 
  updateSerial();
//Check whether it has registered in the network
  mySerial.println("AT+CREG?");
  updateSerial();
}


void loop()
{
  updateSerial();
}


void updateSerial()
{
  delay(500);
  while (Serial.available()) 
  {
//Forward what Serial received to Software Serial Port
    mySerial.write(Serial.read());
  }
  while(mySerial.available()) 
  {
//Forward what Software Serial received to Serial Port
    Serial.write(mySerial.read());
  }
}

Code explanation:

AT – It is the most basic AT command. It initializes Auto-baud’er.  When this command worked, we saw its characters echo, telling us that it understood us correctly. This paved way for us to use some other commands to query the GSM module and get information like:

AT+CSQ – meaning check signal strength query; it checks the ‘signal strength’ – the first number is dB strength, it should be higher than around 5. For us, being higher is better. This our length and type of antenna and location played a very vital role in that.

AT+CCID –  this command gets the SIM card number – it tests that the SIM card is found OK and using it we verified the number written on the card.

AT+CREG? This command checks if the SIM is on a registered network    Check that you’re registered on the network. The second number should be 1 or 5.  If 1, it showed that our SIM was on a registered home network and 5 indicates roaming network. Any other number than these two numbers showed our SIM was not registered to any network.

Internally Charging the LiPo Batteries:






The circuit diagram for the internal batteries charging

The Power Supply for the design consist of two LiPo 4.2V 3800mAH batteries connected in series. In order to recharge these batteries we had to use a single 4.2 1A charger and connected the outputs in parallel the batteries terminals. But the series connection posed a problem so we had to add two switches that would open the series connection when it is time for charging and close it when we are not charging the batteries as shown above.

The microcontroller uses 5V DC supply and the 8.4V formed by the series connection of the two batteries would only fry it. So we used a step-down converter of a 78xx series family viz; LM323T. It regulated the input voltage to a steady 5V output at 2A current for the Vcc of the MCU.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(7, 8);

int Seven = 10;
#define capPin A1
#define buz 11
#define pulsePin A0
#define led 12
#define ledRead 6
#define led2 5

long sumExpect=0; //running sum of 64 sums
long ignor=0; //number of ignored sums
long diff=0; //difference between sum and avgsum
long pTime=0;
long buzPeriod=0;

 
void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module  
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  pinMode(Seven, INPUT);
  delay(100);
pinMode(pulsePin, OUTPUT);
digitalWrite(pulsePin, LOW);
pinMode(capPin, INPUT);
pinMode(buz, OUTPUT);
pinMode(ledRead, INPUT);
pinMode(led2, OUTPUT);
digitalWrite(buz, LOW);
pinMode(led, OUTPUT);

pinMode(9, OUTPUT); 
//this turns on the sim900 automatcally
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  //wait for 3sec
  delay(3000);
}

void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+2347062174135\"\r"); // Replace this with mobile number
  delay(1000);
  mySerial.println("A METAL HAS BEEN DETECTED,SEARCH VERY WELL ");// The SMS text we sent out
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}


 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }
 

void applyPulses()
{
for (int i=0;i<3;i++)
{
digitalWrite(pulsePin,HIGH); //take 3.5 uS
delayMicroseconds(3);
digitalWrite(pulsePin,LOW); //take 3.5 uS
delayMicroseconds(3);
}
}


void loop(){
int pinSeven = digitalRead(Seven);

if (Serial.available()>0)  { 
    
    }
    
 if(pinSeven == HIGH){
  
  int minval=1023;
int maxval=0;
long unsigned int sum=0;
     
  for (int i=0; i<256; i++)
{
//reset the capacitor
pinMode(capPin,OUTPUT);
digitalWrite(capPin,LOW);
delayMicroseconds(20);
pinMode(capPin,INPUT);
applyPulses();
//read the charge of capacitor
int val = analogRead(capPin); //takes 13x8=104 microseconds
minval = min(val,minval);
maxval = max(val,maxval);
sum+=val;
long unsigned int cTime=millis();
char buzState=0;
if (cTime<pTime+10)
{
if (diff>0)
buzState=1;
else if(diff<0)
buzState=2;
}
if (cTime>pTime+buzPeriod)
{
if (diff>0)
buzState=1;
else if (diff<0)
buzState=2;
pTime=cTime;
}
if (buzPeriod>300)
buzState=0;
if (buzState==0)
{
digitalWrite(led, LOW);
noTone(buz);
}
else if (buzState==1)
{
tone(buz,2000);
digitalWrite(led, HIGH);

}
else if (buzState==2)
{
tone(buz,500);
digitalWrite(led, HIGH);

}

}
//subtract minimum and maximum value to remove spikes
sum-=minval;
sum-=maxval;
if (sumExpect==0)
sumExpect=sum<<6; //set sumExpect to expected value
long int avgsum=(sumExpect+32)>>6;
diff=sum-avgsum;
if (abs(diff)<avgsum>>10)
{
sumExpect=sumExpect+sum-avgsum;
ignor=0;
}
else
ignor++;
if (ignor>64)
{
sumExpect=sum<<6;
ignor=0;
}
if (diff==0)
buzPeriod=1000000;
else
buzPeriod=avgsum/(2*abs(diff));
}

if((digitalRead(ledRead) ==HIGH) && (pinSeven == HIGH)){
  SendMessage();
  
}



 else{
      
  }

  if (mySerial.available()>0)
   Serial.write(mySerial.read());

}

The post How to Build an SMS based Metal detector appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/sms-based-metal-detector/feed/ 0
How to design Motion Detector Smart Street Lights System. https://smartechmolabs.com/how-to-design-motion-detector-smart-street-lights-system/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-design-motion-detector-smart-street-lights-system https://smartechmolabs.com/how-to-design-motion-detector-smart-street-lights-system/#respond Mon, 23 Sep 2019 12:26:33 +0000 https://smartechmolabs.com/?p=1714 The Motion Detector Smart Street Lights System project makes use of the Atmega328P-PU microcontroller, a motion detector sensor like PIR sensor, and some AC light bulbs to sense the presence of pedestrians and illuminate their paths for them when it is night time.

The post How to design Motion Detector Smart Street Lights System. appeared first on Smartech Labs.

]]>
The purpose of Motion Detector Smart Street Lights System project is to control the amount of energy utilized when illuminating the pathways for motorist and pedestrians alike during night time. At night, a lot of energy is usually used to keep the street lights on all through the night. Most of these times, the illumination on these paths are not necessarily needed as there will be nobody using the roads. The Motion Detector Smart Street Lights System project thus; is smart enough   to notice the movement of objects around it and lights up the path so that people could see properly.

This Motion Detector Smart Street Lights System project makes use of the Atmega328P-PU microcontroller, a motion detector sensor like PIR sensor, and some AC light bulbs to sense the presence of pedestrians and illuminate their paths for them. For this project, we are going to be needing the following materials:

12v solid state relays………………………………………………………3pcs

Atmega328P-PU microcontroller…………………………………….1pcs

AC light bulbs 220/240V 200W………………………………………3pcs

12V power adapter………………………………………………………1pcs

5V or 12V 3-channel relay module……………………………………………….1pcs

To begin, we need to construct our MCU board, read this previous post of ours to know how to build your own working standalone Arduino board. It would be very wise however, to make sure that the power supply unit or DC supply adapter outputs enough current to power all the parts that runs on DC.

Circuit diagram of the Project.

Motion detector smart street lights circuit diagram
Motion detector smart street lights circuit diagram

From the circuit above, the power supply is producing 5V 1A to the MCU, PIR sensors and the 5V 3-channel relay module.

The MCU board is configured to control the 3-channel relay module through input/output (IO) pins 5, 6 and 7 respectively. While the PIR sensors are controlled via IO pins 8, 9 and 10 respectively.

The Light dependent resistor (LDR) which we used here as optical sensor to differentiate when it is dark and when it is daytime is connected to analog input pin 0 (A0) but voltage divider theorem (since the LDR is connected in series with a 10kΩ fixed resistor. The whole idea for this connection is to measure the rate of change analog voltage as the resistance of the LDR changes due to amount of Light on its surface. The type of LDR used in this Motion Detector Smart Street Light System project has negative coefficient of resistance; which means that as the amount of light on its flat surface increases, the resistance across it decreases.

The Motion Detector Smart Street Light System project would achieve its objective only when it is dark and when there is motion around it that needs to use the illumination it would give out. Hence, we write our program on the Arduino platform again as:

//Arduino source-code for Motion Detector Smart Street Light System project//
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;    

//the time when the sensor outputs a low impulse
long unsigned int lowIn;        
//the amount of milliseconds the sensor has to be low 
//before we assume all motion has stopped
long unsigned int pause = 200;  

boolean lockLow = true;
boolean takeLowTime; 

//the digital pin connected to the PIR sensor's output
int pirPin1 = 10; 
int pirPin2 = 11;
int pirPin3 = 12;
int relay1 = 7;
int relay2 = 8;
int relay3 = 9;
int LDRVcc = 6;


void setup() {
/*we declare the input and output pins of the sensors 
and actuators connected to d MCU */

  pinMode(pirPin1, INPUT);
  pinMode(pirPin2, INPUT);
  pinMode(pirPin3, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
pinMode(LDRVcc, OUTPUT);

//we wanted the LDR to kick start when the MCU is up and running, 
//hence, we energized with one of the IO pins of the MCU.
//using a HIGH command
 digitalWrite(LDRVcc, HIGH);
//we start the serial monitor to see the readings of the sensors
 Serial.begin(9600); 
 //give the PIR sensor some time to calibrate
  Serial.print("calibrating sensor ");
//for the calibration sequence that is displaying, we used a for loop
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(50);
}
}

 
 void loop(){
  //We start reading signals from the LDR connected to analog pin 0.
  int lightSense = analogRead(0);
//we print these readings on the serial monitor
  Serial.println(lightSense);
//with a delay of 0.5s between each value displayed
  delay(500);
//Using a simple if-statement we 
  if(lightSense <= 300) {
    if(digitalRead(pirPin1) == HIGH){
//the led visualizes the sensors output pin state
       digitalWrite(relay1, HIGH);   
       if(lockLow){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;            
        
         }         
         takeLowTime = true;
    }

else if(digitalRead(pirPin1) == LOW){       
       digitalWrite(relay1, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           
           }
       }

       if(digitalRead(pirPin2) == HIGH){
       digitalWrite(relay2, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;            
        
         }         
         takeLowTime = true;

    }
else if(digitalRead(pirPin2) == LOW){  
//the led visualizes the sensors output pin state
       digitalWrite(relay2, LOW);  
       if(takeLowTime){
//save the time of the transition from high to LOW
        lowIn = millis();      
//make sure this is only done at the start of a LOW phase    
        takeLowTime = false;               }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           
           }
       }

if(digitalRead(pirPin3) == HIGH){
       digitalWrite(relay3, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){  
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;            
        Serial.println("---");
        Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
         delay(50);
         }         
         takeLowTime = true;

    }

else if(digitalRead(pirPin3) == LOW){  
//the led visualizes the sensors output pin state     
       digitalWrite(relay3, LOW);  

       if(takeLowTime){
//save the time of the transition from high to LOW
        lowIn = millis();   
//make sure this is only done at the start of a LOW phase       
        takeLowTime = false;       
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           
           }
       }
    delay(50);
  }
   
  
  if (lightSense >= 301 ) {
    digitalWrite(relay1, LOW);
    digitalWrite(relay2, LOW);
    digitalWrite(relay3, LOW);
    if(takeLowTime){
//save the time of the transition from high to LOW
        lowIn = millis(); 
//make sure this is only done at the start of a LOW phase         
        takeLowTime = false;       
        }
       //if the sensor is low for more than the given pause, 
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){  
           //makes sure this block of code is only executed again after 
           //a new motion sequence has been detected
           lockLow = true;                        
           

  }

  }
 }

Further explanation of Sketch:

We declared all our variables from line 3 through line 21, the calibration time  for the PIR sensors was to 10 seconds according to the datasheet of the product. But the sensor emits a pulse and waits for an obstacle to reflect it by cutting into its line of projection. So we used a long variable unsigned to denote this. In the loop function, we have already noticed that during dark, the LDR displays values that are below 300 and when it experiences sufficient amount across its surface, its values rises way above 300. Using the if-statement we made a comparison as regards to when the latter following lines would be executed. The rest of the algorithm used for the Motion Detector Smart Street Lights System project are explained using comment line. And notice there is a repeated pattern for the three PIRs.

Connecting the AC lamps:

The AC bulbs are connected as shown in the circuit diagram. The relays: relay1, relay2 and relay3 acts as the bridge between the DC and the AC voltage. In other words for the AC bulbs to be turned on, the relays must be energized. The relay energizing voltages were rated 5V but 12V solid state relays are recommended to avoid arching between switching poles of the relays and burning out the filaments of the tungsten bulbs.  A better choice would to go for energy saving lamps that uses AC to DC converters.

The working video is shown in the embed youTube below.

The working video of the Motion Detector Smart Street Lights System project

The post How to design Motion Detector Smart Street Lights System. appeared first on Smartech Labs.

]]>
https://smartechmolabs.com/how-to-design-motion-detector-smart-street-lights-system/feed/ 0