Sunday, 25 February 2018

NodeMcu Basics (IoT).


 Basics:


Lets begin with Installing the Esp8266 support for the Arduino and see how to blink an LED ( the hello world in the electronics )
check out the video to know step by step tutorial on how to get started with our favourite chip Esp8266


Firstly open the Arduino IDE

Go to files and click on the preference in the Arduino IDE





copy the below code in the Additional boards Manager

http://arduino.esp8266.com/stable/package_esp8266com_index.json

click OK to close the preference Tab.









After completing the above steps , go to Tools and board, and then select board Manager








Navigate to esp8266 by esp8266 community and install the software for Arduino.

Once all the above process been completed we are read to program our esp8266 with Arduino IDE.























For this example I have used NodeMCU esp8266 and if you are using any other vendor wifi chips or generic wifi module please check with the esp8266 Pin mapping which is very essential to make things works.

The reason why I used D7 pin for this example is , I uploaded the basic blink program that comes with the examples program in the arduino IDE which is connected with 13 pin of arduino. The 13th pin is mapped into D7 pin of NodeMCU.

go to board and select the type of esp8266 you are using. and select the correct COM port to run the program on your esp8266 device.

Code:

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second



}

upload the program and see the results.


Step 1: Control an LED From Web Browser

  Now we will see How to "Turn On and Turn Off" an LED that has connected to the Esp8266, the esp8266 has programmed from Arduino IDE to control the LED.

We will connect the Esp8266 to the Wi-Fi router using SSID and password of our Home network Wifi , where the esp8266 connect to our wifi and create a webserver, which can be accessed by looking through the serial Monitor of the Arduino window or you can also log into your Wifi router and check for the list of clients connected to your Wi-Fi router.

Here's a window which explains the step by step procedure to connect the Esp8266 to the Wi-fi server and How to access the Webpage and control the LED connected to the Esp8266
For the above video I have used NodeMcu, you can use any type of Esp8266 to make this thing work in your web browser.
look for the mapping of pins in with your Esp8266 vendor, if the program not working properly for you , the fault will be with the pin mapping functionalities, Here I used the D7 pin which mapped to 13th pin when program from the Arduino IDE.

 

 Code:

 
#include <ESP8266WiFi.h>
 
const char* ssid = "Magesh";
const char* password = "jayakumar";
 
int ledPin = 13; // GPIO13
WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  delay(10);
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
 
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  // Match the request
 
  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }
 
// Set ledPin according to the request
//digitalWrite(ledPin, value);
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Led pin is now: ");
 
  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");  
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
 
}

 
 
If everything completed you can turn to your serial monitor and check 
for the ip address that your devices has connected to . you will 
presented with an serial monitor that look exactly to the picture below.





 

 

Step 2: Control Electrical Devices From User Web Browser Using Esp8266 Nodemcu

 

Now we will see how to control electrical devices like fan, light, etc., to turn on and off using esp8266 from a web browser. if you are bored with a dedicated device controller like an app or an remote which will be available for only one particular device but using this method all the device which support web browsing will be act as a controller for us.
Make sure all the devices are connected to the same router, this example doesn't include a port forwarding function which will not allow us to control the device from outside the home network.
Components that you need for completing this project are very simple, you need to have an esp8266 wifi module and a relay, make sure you buying a 5v relay which very easy to use with esp chips doesn't require external supply too. we can make use of the Vin pin of the nodemcu or if you are using a generic chip, you need to supply an external 5v to the relay.



For this example project I have used only 2 relay circuit, but the actual program wrote for connecting four relay module.



 




Copy the below arduino code and paste into your Arduino IDE and upload the program to your nodemcu or any other esp devices that you are using, make sure to choose the correct port and device name from the board. also don't forget to change the SSID and password to your Wi-fi settings.
This program for the esp8266 wrote to return the status of the device , which will in turn notify us with the device state in the browser which will also make the user to know which device has currently turned on or off. 

 Code:


 #include <ESP8266WiFi.h>

const char* ssid = "Magesh";
const char* password = "jayakumar";

; //
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(0, OUTPUT);
  pinMode(13, OUTPUT);
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);
  digitalWrite(0, LOW);
  digitalWrite(13, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request


  if (request.indexOf("/light1on") > 0)  {
    digitalWrite(5, HIGH);
 
  }
  if (request.indexOf("/light1off") >0)  {
    digitalWrite(5, LOW);
 
  }

   if (request.indexOf("/light2on") > 0)  {
    digitalWrite(4, HIGH);
 
  }
  if (request.indexOf("/light2off") >0)  {
    digitalWrite(4, LOW);
 
  }
    if (request.indexOf("/light3on") >0)  {
    digitalWrite(0, HIGH);
 
  }
  if (request.indexOf("/light3off") > 0)  {
    digitalWrite(0, LOW);
 
  }
   if (request.indexOf("/light4on") > 0)  {
    digitalWrite(13, HIGH);
 
  }
  if (request.indexOf("/light4off") > 0)  {
    digitalWrite(13, LOW);
 
  }
// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println("<head>");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
 client.println("</head>");
  client.println("<body bgcolor = \"#f7e6ec\">");
  client.println("<hr/><hr>");
  client.println("<h4><center> Esp8266 Electrical Device Control </center></h4>");
  client.println("<hr/><hr>");
  client.println("<br><br>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("Device 1");
  client.println("<a href=\"/light1on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light1off\"\"><button>Turn Off </button></a><br />");
  client.println("</center>"); 
  client.println("<br><br>");
   client.println("<center>");
   client.println("Device 2");
  client.println("<a href=\"/light2on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light2off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
  client.println("<br><br>");
    client.println("<center>");
   client.println("Device 3");
  client.println("<a href=\"/light3on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light3off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
  client.println("<br><br>");
   client.println("<center>");
   client.println("Device 4");
  client.println("<a href=\"/light4on\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/light4off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
  client.println("<br><br>");
  client.println("<center>");
  client.println("<table border=\"5\">");
 client.println("<tr>");
  if (digitalRead(5))
         {
           client.print("<td>Light 1 is ON</td>");
      
         }
          else
          {
            client.print("<td>Light 1 is OFF</td>");
    
        }
   
        client.println("<br />");
           
         if (digitalRead(4))
          {
           client.print("<td>Light 2 is ON</td>");

         }
          else
          {

            client.print("<td>Light 2 is OFF</td>");

          }
          client.println("</tr>");


          client.println("<tr>");

          if (digitalRead(0))

          {
           client.print("<td>Light 3 is ON</td>");

          }

          else

          {
            client.print("<td>Light 3 is OFF</td>");
          }


          if (digitalRead(13))


          {


           client.print("<td>Light 4 is ON</td>");

          }


          else


          {


            client.print("<td>Light 4 is OFF</td>");


          }

          client.println("</tr>");


          client.println("</table>");

          client.println("</center>");
  client.println("</html>");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

 Copy the above code and complete the process.


Step 3: Upload DS18b20 Temperature Sensor Data to Thingspeak From Esp8266 (nodemcu)

Now you will know how to use Ds18b20 Temperature data to thingspeak.com, you can follow above fritzing circuit diagram to control the Ds18b20 temperature sensor, This sensor follows one wire protocol which means you can connect many sensors as you want to the single pin and access temperature data calling the sensor by address.



There is no much work to get work with this sensor, as there are plenty of example library that already available in the internet which anyone can make use and get started to work with this sensor.
Test the below code to know check whether you can get reading from the temperature sensor with ESP8266 or Nodemcu.



NodeMcu Pin mapping: 

Picture of NodeMCU ESP-12E Pin Mapping

Servo motor to Arduino (Basics)




Servo motors are great devices that can turn to a specified position.
Usually, they have a servo arm that can turn 180 degrees. Using the Arduino, we can tell a servo to go to a specified position and it will go there. As simple as that!
Servo motors were first used in the Remote Control (RC) world, usually to control the steering of RC cars or the flaps on a RC plane. With time, they found their uses in robotics, automation, and of course, the Arduino world.
Here we will see how to connect a servo motor and then how to turn it to different positions.
The first motor I ever connected to an Arduino, seven years ago, was a Servo motor. Nostalgic moment over, back to work!
We will need the following things:
  1. An Arduino board connected to a computer via USB
  2. A servo motor
  3. Jumper wires
There are few big names in the servo motor world. Hitec and Futaba are the leading RC servo manufacturers. Good places to buy them are Servocity, Sparkfun, and Hobbyking.

Step 1: How to Connect Them



A servo motor has everything built in: a motor, a feedback circuit, and most important, a motor driver. It just needs one power line, one ground, and one control pin.
Following are the steps to connect a servo motor to the Arduino:
  1. The servo motor has a female connector with three pins. The darkest or even black one is usually the ground. Connect this to the Arduino GND.
  2. Connect the power cable that in all standards should be red to 5V on the Arduino.
  3. Connect the remaining line on the servo connector to a digital pin on the Arduino.
Check the image for a view of the servo connected to the Arduino.

 

Step 2: Code

The following code will turn a servo motor to 0 degrees, wait 1 second, then turn it to 90, wait one more second, turn it to 180, and then go back.


// Include the Servo library 
#include <Servo.h> 
// Declare the Servo pin 
int servoPin = 3; 
// Create a servo object 
Servo Servo1; 
void setup() { 
   // We need to attach the servo to the used pin number 
   Servo1.attach(servoPin); 
}
void loop(){ 
   // Make servo go to 0 degrees 
   Servo1.write(0); 
   delay(1000); 
   // Make servo go to 90 degrees 
   Servo1.write(90); 
   delay(1000); 
   // Make servo go to 180 degrees 
   Servo1.write(180); 
   delay(1000); 
}
 
 
If the servo motor is connected on another digital pin, simply change the value of servoPin to the value of the digital pin that has been used.



 

 

 

Step 3: How It Works




Servos are clever devices. Using just one input pin, they receive the position from the Arduino and they go there. Internally, they have a motor driver and a feedback circuit that makes sure that the servo arm reaches the desired position. But what kind of signal do they receive on the input pin?
It is a square wave similar to PWM. Each cycle in the signal lasts for 20 milliseconds and for most of the time, the value is LOW. At the beginning of each cycle, the signal is HIGH for a time between 1 and 2 milliseconds. At 1 millisecond it represents 0 degrees and at 2 milliseconds it represents 180 degrees. In between, it represents the value from 0–180. This is a very good and reliable method. The graphic makes it a little easier to understand.
Remember that using the Servo library automatically disables PWM functionality on PWM pins 9 and 10 on the Arduino UNO and similar boards.

Code breakdown

The code simply declares the servo object and then initializes the servo by using the servo.attach() function. We shouldn't forget to include the servo library. In the loop(), we set the servo to 0 degrees, wait, then set it to 90, and later to 180 degrees.

 

Step 4: More Things About Servos

Controlling servos is easy, and here are a few more tricks we can use:

Controlling the exact pulse time

Arduino has a built-in function servo.write(degrees) that simplifies the control of servos. However, not all servos respect the same timings for all positions. Usually, 1 millisecond means 0 degrees, 1.5 milliseconds mean 90 degrees, and, of course, 2 milliseconds mean 180 degrees. Some servos have smaller or larger ranges.
For better control, we can use the servo.writeMicroseconds(us) function, which takes the exact number of microseconds as a parameter. Remember, 1 millisecond equals 1,000 microseconds.

More servos

In order to use more than one servo, we need to declare multiple servo objects, attach different pins to each
 one, and address each servo individually. First, we need to declare the servo objects—as many as we need:

// Create servo objects
Servo Servo1, Servo2, Servo3; 
 
Then we need to attach each object to one servo motor. Remember, every servo motor uses an individual pin:

Servo1.attach(servoPin1);
Servo2.attach(servoPin2);
Servo3.attach(servoPin3); 
 
In the end, we just have to address each servo object individually:

Servo1.write(0); // Set Servo 1 to 0 degrees
Servo2.write(90); // Set Servo 2 to 90 degrees 
 
Connection-wise, the grounds from the servos go to GND on the Arduino, the servo power to 5V or VIN (depending on the power input), and in the end, each signal line has to be connected to a different digital pin. Contrary to popular belief, servos don't need to be controlled by PWM pins—any digital pin will work.

Continuous rotation servos

There is a special breed of servos labelled as continuous rotation servos. While a normal servo goes to a specific position depending on the input signal, a continuous rotation servo either rotates clockwise or counter-clockwise at a speed proportional to the signal. For example, the Servo1.write(0) function will make the servomotor spin counter-clockwise at full speed. The Servo1.write(90) function will stop the motor and Servo1.write(180) will turn the motor clockwise at full speed.
There are multiple uses for such servos; however, they are really slow. If you are building a microwave and need a motor to turn the food, this is your choice. But be careful, microwaves are dangerous!

 


Ultrasonic Range Detector Using Arduino and the SR04 Ultrasonic Sensor

 

 

Step 1: Connecting the SR04 Ultrasonic Sensor to the Arduino

Picture of Connecting the SR04  Ultrasonic Sensor to the Arduino
Picture of Connecting the SR04  Ultrasonic Sensor to the Arduino

 

 

 

 

 

 

 

 

 

 

 

Step 2: Parts List

1               Arduino uno R3, or any Arduino for that matter
1               SR04 Ultrasonic Sensor
1               breadboard
4               Jumper Wires

 

 

 

Step 3: Connect Ultrasonic Sensor to Arduino

You Need 4 Jumper wires to conect the SR04 Ultrasonic Sensor to the Arduino:

1  From the SR04  VCC pin to the Arduino 5v
1 From the SR04  GND pin to the Arduino GND
1 From the SR04  TRG pin to the Arduino Digital pin 12
1 From the SR04  ECHO pin to the Arduino Digital pin 11


That's All The wiring you need... Easy,  no?

Next Step, load the Software library and sketches.

 

 

Step 4: Step 4 Download SR04 Library and Install to Arduino IDE



You need to download another Library  to get the Arduino to talk with the SR04 sensor. The sensor I got didn't come with any documentation, so I Googled around until I found a library that works.
I found an optimized library here
Download the library unzip it,  and install it in the Arduino IDE. Place it inside your Arduino libraries folder , and restart the Arduino IDE. For convenience, I included the file  in  the files section below.



You should now be able to see the  library and examples in  select File > Examples > NewPing > NewPingexample sketch.
load the sketch to your Arduino.


If you were successful at installing the libraries, and loading the NewPingexample sketch,  Compile the sketch  by clicking on the verify button and make sure there are no errors.


It's time to connect your Arduino to your PC using the USB cable.  Click on the upload button  to upload the sketch to the Arduino.


Once uploaded to the Arduino, open the serial monitor, and you should see the distance  data stream   coming from the sensor.

Controlling AC Light Using Arduino With Relay Module


 Introduction:


It is a simple project and also very dangerous as we are going to deal with high voltage 220v . Do not attempt if you are a amateur in dealing with high voltage.
I'll answer few basic questions, which hits when you are novice!
Why to use relay for controlling AC light?
AC is alternating current 220v (india) which powers the ac lights. Arduino cannot control high volt n amp, but a relay can do this job, which is the sole design of it. so we are using relay as switch to control high power devices.


What is NO NC and COM in relay?

C = Common Connection

NC = Normally Closed Connection

NO = Normally Open Connection

I have explained NO NC COM elaborately in step 3, refer it -if you feel it bit confusing.
I'm going to use NO Normally Open Connection.

 

 

Step 1: Components Needed




1) Arduino UNO
2)5V Relay module 220v
3)Ac light

 

 

Step 2: Connections




Connect pin 7 arduino to IN 1 relay module
5v to vcc of relay module
gnd to gnd of relay module

 

 

 Step 3: NC COM NO of Relay



COM - Common connection--> it is the center terminal, It is hot as power to the load is connected at this terminal.
NO Normally open ---> It acts like a switch,since it is open - there will be no contact between COM and NO, When we trigger the relay module, it connects to COM by the electromagnet inside the relay and supply to the load is provided,which powers up the light.Thus the circuit is closed until we trigger the state to low in relay.
NC Normally closed---->It is always in contact with COM, even when relay is not powered.when we trigger the relay it opens the circuit, so the connection is lost. it behaves just opposite to NO.

im using NO connection,but here in this type of relay "HIGH" state in code turns off the relay(opens the circuit).  "LOW" state in code turns on the relay.

 

 

 Step 4: Relay Connections



We are using Normally open connection in relay. so that we can trigger on and off the light .
Hot line from supply is connected to COM
Supply line to the Ac light is connected to NO
Gnd or - or other terminal in light is connected directly.

 

Step 5: Circuit Diagram



                        

 Code:



digitalWrite(RELAY1,LOW); // Turns ON Relays 1
Serial.println("Light ON");
delay(2000); // Wait 2 seconds
digitalWrite(RELAY1,HIGH); // Turns Relay Off
Serial.println("Light OFF");
delay(2000);

Note: You can attach various sensors to Control your light.

Interfacing Humidity and Temperature (DHT11) Sensor to Arduino




DTH11 includes both Humidity and Temperature sensor.

Hardware Components required:-
1) DTH11 Humidity and Temperature Sensor
2) Arduino UNO
3)Connecting Wires
4) DTH library
You can get the sensor DTH11 Data Sheet from the below link
http://www.micro4you.com/files/sensor/DHT11.pdf



Hardware Connections

DTH11 To Arduino
Vcc --- 5v
GND --- GND
Data Pin --- 3rd Pin of Arduino


Step 1: How to Include DHT Library
















Picture of How to Include DHT Library






























 

 

 

 

 

Please download the DHT library from the below link.
https://drive.google.com/file/d/0B1paTI5fzcHodno5azFOSVVDT0E/view?usp=sharing
Go to Sketch--> Include Library --> Add Zip File
As shown in the above screen shot please browse the ZIP file and include the library after including the library.
Close the Arduino IDE and open it again then you will find the library included.

 

 

 

 Step 2: Program and Results

 










Picture of Program and Results





 

 

 

Code:


#include<dht.h>
dht DHT;
// if you require to change the pin number, Edit the pin with your arduino pin.
#define DHT11_PIN 3
void setup() {
Serial.begin(9600);
Serial.println("welcome to TechPonder Humidity and temperature Detector"); }
void loop() { // READ DATA
int chk = DHT.read11(DHT11_PIN);
Serial.println(" Humidity " );
Serial.println(DHT.humidity, 1);
Serial.println(" Temparature ");
Serial.println(DHT.temperature, 1);
delay(2000);
}


LDR with Arduino

Step 1: Hardware Required :


  • Arduino Uno
  • LED
  • LDR (photoresistor)
  • 220 and 10k ohm resistors
  • Wires
  • Breadboard

 Step 2: LED Connection

 

Picture of LED Connection


  1. LED attach to board
  2. Resistor (220 ohm) one leg attach to LED long leg
  3. The green wire attach to resistor's empty leg
  4. The brown wire attach o LED short leg

 

 

Step 3: LDR Connection

 

  1. LDR attach to board
  2. Resistor (10k ohm) attach to LDR one leg
  3. The purple wire attach to LDR other (empty) leg
  4. The yellow wire attach to LDR and resistor same column
  5. The white wire attach to resistor empty leg

 

 

 Step 4: Arduino Connections

 




  1. The green wire connect to digital 13 from resistor leg
  2. The brown wire connect to GND from LED short leg
  3. The purple wire connect to +5V from LDR
  4. The yellow wire connect to A0
  5. The white wire connect to GND

 

Step 5: Code

 


 Code:


const int ledPin = 13;
const int ldrPin = A0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldrPin);
if (ldrStatus <=300) {
digitalWrite(ledPin, HIGH);
Serial.println("LDR is DARK, LED is ON");
}
else {
digitalWrite(ledPin, LOW);
Serial.println("---------------");
}
}

Using a PIR with Arduino

Connecting to a PIR



Most PIR modules have a 3-pin connection at the side or bottom. The pinout may vary between modules so triple-check the pinout! It's often silkscreened on right next to the connection (at least, ours is!) One pin will be ground, another will be signal and the final one will be power. Power is usually 3-5VDC input but may be as high as 12V. Sometimes larger modules don't have direct output and instead just operate a relay in which case there is ground, power and the two switch connections.
The output of some relays may be 'open collector' - that means it requires a pullup resistor. If you're not getting a variable output be sure to try attaching a 10K pullup between the signal and power pins.
An easy way of prototyping with PIR sensors is to connect it to a breadboard since the connection port is 0.1" spacing. Some PIRs come with header on them already, the one's from adafruit have a straight 3-pin header on them for connecting a cable


For our PIR's the red cable is + voltage power, black cable is - ground power and yellow is the signal out. Just make sure you plug the cable in as shown above! If you get it backwards you won't damage the PIR but it won't work.
 

Reading PIR Sensors

Connecting PIR sensors to a microcontroller is really simple. The PIR acts as a digital output so all you need to do is listen for the pin to flip high (detected) or low (not detected).Its likely that you'll want reriggering, so be sure to put the jumper in the H position!
Power the PIR with 5V and connect ground to ground. Then connect the output to a digital pin. In this example we'll use pin 2.
The code is very simple, and is basically just keeps track of whether the input to pin 2 is high or low. It also tracks the state of the pin, so that it prints out a message when motion has started and stopped.


The Code:


  1. /*
  2. * PIR sensor tester
  3. */
  4. int ledPin = 13; // choose the pin for the LED
  5. int inputPin = 2; // choose the input pin (for PIR sensor)
  6. int pirState = LOW; // we start, assuming no motion detected
  7. int val = 0; // variable for reading the pin status
  8. void setup() {
  9. pinMode(ledPin, OUTPUT); // declare LED as output
  10. pinMode(inputPin, INPUT); // declare sensor as input
  11. Serial.begin(9600);
  12. }
  13. void loop(){
  14. val = digitalRead(inputPin); // read input value
  15. if (val == HIGH) { // check if the input is HIGH
  16. digitalWrite(ledPin, HIGH); // turn LED ON
  17. if (pirState == LOW) {
  18. // we have just turned on
  19. Serial.println("Motion detected!");
  20. // We only want to print on the output change, not state
  21. pirState = HIGH;
  22. }
  23. } else {
  24. digitalWrite(ledPin, LOW); // turn LED OFF
  25. if (pirState == HIGH){
  26. // we have just turned of
  27. Serial.println("Motion ended!");
  28. // We only want to print on the output change, not state
  29. pirState = LOW;
  30. }
  31. }
  32. }
 
 
 
Don't forget that there are some times when you don't need a microcontroller. A PIR sensor can be connected to a relay (perhaps with a transistor buffer) without a micro!

Arduino Soil Moisture Sensor

Arduino Soil Moisture Sensor

Picture of Arduino Soil Moisture Sensor

When you hear the word Smart Garden, one of the things that pop up to your mind is the automatic measurement of the moisture content of the soil. If you're building a Smart Garden that waters plants automatically and give you the readings of the wetness of the soil, then you will definitely need a Soil Moisture Sensor.
In this Instructable, I'll show you how to interface the Soil Moisture Sensor to an Arduino Uno and read the values on a Serial Monitor.




 Picture of Components Required
For this project, you will need :
  • Arduino Uno
  • Soil Moisture Sensor
  • Hook up Wires
  • Bread Borad.

Step 2: About the Soil Moisture Sensor

Picture of About the Soil Moisture Sensor 

Picture of About the Soil Moisture Sensor

A typical Soil Moisture Sensor consist of two components. A two legged Lead, that goes into the soil or anywhere else where water content has to be measured. This has two header pins which connect to an Amplifier/ A-D circuit which is in turn connected to the Arduino.
The Amplifier has a Vin, Gnd, Analog and Digital Data Pins. This means that you can get the values in both Analog and Digital forms.



Step 3: How Does the Sensor Work

 Picture of How Does the Sensor Work
 Most soil moisture sensors are designed to estimate soil volumetric water content based on the dielectric constant (soil bulk permittivity) of the soil. The dielectric constant can be thought of as the soil's ability to transmit electricity. The dielectric constant of soil increases as the water content of the soil increases. This response is due to the fact that the dielectric constant of water is much larger than the other soil components, including air. Thus, measurement of the dielectric constant gives a predictable estimation of water content.

 

Step 4: Connections

  • Connect the two pins from the Sensor to the two pins on the Amplifier circuit via hook up wires.
  • Connect the Vcc from the Amplifier to the 3.3V pin on the Arduino and the Gnd pin to the Gnd pin on the Arduino.
  • Now connect the Analog Data Pin to the A0 pin on the Arduino (Since I'm interested in Analog Data). 

Step 5: Code

For simply reading the values I'll be using the AnalogRead sketch from the Examples menu. You can modify the code as per your requirements.
 
 
 
void setup() {  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}
// the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // print out the value you read: Serial.println(sensorValue); delay(1); // delay in between reads for stability }




After verifying the code, upload it to the board and open the serial monitor. You will see the sensor data on the monitor being changed when you dip the sensor leads in water and when dry. 
You can use these values as threshold if you intend to trigger an
action bases on these values.