Thursday 29 January 2015

11)Detecting the Distance using a Ultra-Sonic sensor


Ultrasonic sensors works similar to a radar which gets the presence of  target by interpreting the echoes from radio or sound waves . Active ultrasonic sensors generate high frequency sound waves and detects the echo which is received back by the sensor and then measures the time interval between sending resumption of  the echo to determine the distance to an object.

Working


The working of Ultrasonic sensor is just based on how the bat flies, It sends out a ultrasonic wave and waits for its echo to return back if it returns back then it takes a either turn or it continues path.

Now mathematically we define speed = (distance) / (Time);

So this would imply distance=speed * Time;

Parameters known

1)speed of ultrasonic sensor.
2)Time taken for it to strkte an object and echo.  ie  (observed Time /2 ) will be the time to strike the object and return to its original origin.
3)Distance can be found by the desired form.

check the following site to know the speed of ultrasonic sensor in various medium http://www.classltd.com/sound_velocity_table.html

Diagram


Pins on a US sensor

                              1) Vcc
                              2)Gnd
                              3)Trigger ( provide Vcc to send a ultrasonic signal)
                              4)echo      (Rx)


Sketch

//The following program prints the distance in the serial monitor and blinks an LED when distance is less than 10Meters

#define trigger 2
#define echo 3
void setup()
{
   pinMode(trigger,OUTPUT);
   pinMode(echo,INPUT);
   pinMode(13,OUTPUT);
   Serial.begin(9600);
}
void loop()
{
   int time,distance;
   
// Now send out a ultrasonic wave for one second

digitalWrite(trigger,HIGH);
delay(1000); // transmitting a wave for 1 second
digitalWrite(trigger,LOW);

time=pulseIn(echo,HIGH);  // Returns the length of pulse in Micro-seconds  check http://arduino.cc/en/Reference/pulseIn for more info
distance=(time/2)/29.1;        //

Serial.println(distance);

if(distance<10)
{
   digitalWrite(13,HIGH);
}
else
{
  digitalWrite(13,LOW);
}
}

   

Wednesday 28 January 2015

10 . Using vibration sensor in Ardunio


How much ever secure we keep our house there always exist some vulnerability to break into.This post explains how to use a vibration sensor with use of Arduino.
The Sensor detects any type of vibrations and returns Vcc as output. Its interface to Arduino is very simple in a way that the output of the sensor is fed to any of the I/O pins of the Arduino and is stored in some variable. If the IO pin of the Arduino returns a HIGH then there is a vibration on the sensor else the state of arduino will be in monitoring mode.

Calibration

There is a small potentiometer on the sensor which measures the depth of vibration to detect and act accordingly.Based on the value of the potentiometer the sensitivity of the sensor decreases or increases.


Diagram:


Program

// The following program blinks an LED when the sensor detects vibration
void setup()
{
   pinMode(3,INPUT);
   pinMode(13,OUTPUT);
}
void loop()
{
  int sensorinput=digitalRead(3);
  if (sensorinput==HIGH)
  {
            digialWrite(13,HIGH);
  }
  else
  {
           digitalWrite(13,LOW);
 }
}

Tuesday 27 January 2015

DOOR SENSORS WITH ARDUINO


Using door sensors are very basic prerequisites in electronics. Door sensors are just a Reed Switch where the Switch gets activated when subjected to electromagnetic waves.When in normal condition it gets deactivated.

 


Both single and dual contact reed switch is very simple . In single contact switch only one connection can be made while in dual contact is just an exact replica of a Relay which i have explained in your session on "HOW TO MAKE A AUTOMATIC EVENING LAMP".

Diagram


Working & Arduino Sketch


The above circuit is very simple in fact it is just a continuity check in an arduino.The ground of the Arduino is connected to a Reed switch and +5V of Arduino is connected to the other end of the Arduino with a LOAD.LOAD is connected in order to prevent the frying of Arduino.Arduino would be jammed if its Vcc and gnd are connected . Now to check whether the circuit is close the line is tapped and is given to any of the I/O pins in Arduino.

Program

//The following sketch blinks a LED when a magnet is brought near the sensor.

setup()
{
  pinMode(13,OUTPUT);
  pinMode(2,INPUT);  //change the pin number based on IO pin you connect
}
void loop()
{
  int sensorinput=digitalRead(2);
  if(sensorinput==HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }
}


Reed switch as a Door Sensor

Place the reed switch on one side of the door and a magnet on other side of the door. When the door is open the Circuit is broken and when the door is closed the circuit is inturn closed.


Monday 26 January 2015

8.ARDUINO BASED MOTION DETECTOR

PIR sensors are those which scans its environment and fixes its reference value.When there is any movement in the scanned region it sends out a analog signal.The analog signal is converted to a digital signal for convenience using a comparator and the digital signal is analysed using an Arduino.

DIAGRAM

PIR motion sensor connectivity with Arudino

Sketch

// THE FOLLOWING SKETCH BLINKS AN LED IF THERE IS A MOTION IN THE RANGE OF THE SENSOR

void setup()
{
  pinMode(2,INPUT);           //sensor input
  pinMode(13,OUTPUT);    // on board LED 
}
void loop()
{
  int sensorinput=digitalRead(2);
  if(sensorinput==HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }
}

PIR CALLIBRATION


You will notice two potentiometer  on the PIR sensors one would be to adjust the sensitivity of the sensor and other would be for the delay time of the sensor.

1st potentiometer is used for sensitivity ie it controles the scan ranging ratio for fixing the referance value.
2nd potentiometer is used for the time adjustment ie when the PIR is triggered with a motion it sends out an analog output ( digital output if the analog value is sent to an comparator) and waits for a particulat time for rescanning for the referance value again. Adjusting this would be to increase or decrease the delay time of the sensor.

Sunday 25 January 2015

PID based line follower with L293D MOTOR DRIVER

1) 2 DC motors with required wheels
              -Its better to have a metal gear micro motors for higher speed But if not available you can use normal DC motors.
2)Arduino Micro-controllers
               --Arduino or a clone of it can be used.
3)L293D motor driver (or) any other motor driver to run two motors
4)Batteries
5)6 IR Sensors or a QTR-RC arrays
6)Connecting wires
7)control system-PID

This is a line follower which implements PID to calculate its deviations from the line and act accordingly. This gives the robot with high speed and less oscillations.


·         The proportional value is approximately proportional to your robot’s position with respect to the line. That is, if your robot is precisely centered on the line, we expect a proportional value of exactly 0. If it is to the left of the line, the proportional term will be a positive number, and to the right of the line, it will be negative. This is computed from the result returned by read_line() simply by subtracting 2000.
·         The integral value records the history of your robot’s motion: it is a sum of all of the values of the proportional term that were recorded since the robot started running.
·         The derivative is the rate of change of the proportional value. We compute it in this example as the difference of the last two proportional values.


Diagram


 
Program

#include <QTRSensors.h>

#define Kp  0.5// experiment to determine this, start by something small that just makes your bot follow the line at a slow speed
#define Kd  2// experiment to determine this, slowly increase the speeds and adjust this value. ( Note: Kp < Kd) 

#define rightMaxSpeed 150 // max speed of the robot
#define leftMaxSpeed 150 // max speed of the robot

#define rightBaseSpeed 150 // this is the speed at which the motors should spin when the robot is perfectly on the line
#define leftBaseSpeed 150  // this is the speed at which the motors should spin when the robot is perfectly on the line


#define NUM_SENSORS  6     // number of sensors used
#define TIMEOUT       2500  // waits for 2500 us for sensor outputs to go low
#define EMITTER_PIN   2     // emitter is controlled by digital pin 2


#define rightMotor2 4
#define rightMotorPWM 5


#define leftMotor2 11
#define leftMotorPWM 10



QTRSensorsRC qtrrc((unsigned char[]) {A0,A1,A2,A3,A4,A5} ,NUM_SENSORS, TIMEOUT, EMITTER_PIN); //analog sensor connected through analog pins A0 - A5

unsigned int sensorValues[NUM_SENSORS];

void setup()
{
  Serial.begin(9600);
  Serial.print("start");
  pinMode(rightMotor2, OUTPUT);
  pinMode(rightMotorPWM, OUTPUT);
  
  pinMode(leftMotor2, OUTPUT);
  pinMode(leftMotorPWM, OUTPUT);
  
  
digitalWrite(13,HIGH); 
for (int i = 0; i < 300; i++) // calibrate for sometime by sliding the sensors across the line, or you may use auto-calibration instead
{
     qtrrc.calibrate();    
        
}    
digitalWrite(13,LOW);     
     
     
  // comment out for serial printing
    
    for (int i = 0; i < NUM_SENSORS; i++)
    {
      Serial.print(qtrrc.calibratedMinimumOn[i]);
      Serial.print(' ');
    }
    Serial.println();

    for (int i = 0; i < NUM_SENSORS; i++)
    {
      Serial.print(qtrrc.calibratedMaximumOn[i]);
      Serial.print(' ');
    }
    Serial.println();
    Serial.println();
    
  } 

int lastError = 0;

void loop()
{
  unsigned int sensors[6];
  
int position = qtrrc.readLine(sensors); // get calibrated readings along with the line position, refer to the QTR Sensors Arduino Library for more details on line position.
 
 int error = position - 2500;
 
Serial.println(position);   //returns the current position of the robot to calculate the error.

  int motorSpeed = Kp * error + Kd * (error - lastError);
  lastError = error;

  int rightMotorSpeed = rightBaseSpeed + motorSpeed;
  int leftMotorSpeed = leftBaseSpeed - motorSpeed;
  
 if (rightMotorSpeed > rightMaxSpeed ) 
       rightMotorSpeed = rightMaxSpeed; // prevent the motor from going beyond max speed
 if (leftMotorSpeed > leftMaxSpeed ) 
       leftMotorSpeed = leftMaxSpeed; // prevent the motor from going beyond max speed
 if (rightMotorSpeed < 0) 
       rightMotorSpeed = 0; // keep the motor speed positive
 if (leftMotorSpeed < 0) leftMotorSpeed = 0; // keep the motor speed positive
   {
  
  
  analogWrite(rightMotorPWM, rightMotorSpeed);
  digitalWrite(rightMotor2, LOW);

  
  analogWrite(leftMotorPWM, leftMotorSpeed);
  digitalWrite(leftMotor2, LOW);
 
}
}
void turn_left()
{
 digitalWrite(5,HIGH);
  digitalWrite(4,LOW);
}
void turn_right()
{
  digitalWrite(10,LOW);
  digitalWrite(11,HIGH);
}

Working

The Robot instantaneously checks the position of the robot and corrects accordingly. The robot is calibrated initially   by exposing all the 6 six sensors to the black line so that the robot judges the dark and light bands with respective to its thickness.
The robot makes a reference position of the line and the robot and if the robot deviates it calculates the error and multiplies with a constant Kp and Kd and the result is fed to the speed of the motors.

PID calibration

Kp and Kd must be found out only by expt. Initially keep the Kp value as .5 and increase it slowly in order to make the robot follow the line. However after the robot starts to follow the line the deviations can be reduced to .1% error by slowly increasing the Kd value till the robot goes without oscillations .

#WEEK 1 :SIMPLE PROJECT ON HOW TO MAKE A AUTOMATIC EVENING LAMP WITH ARDUINO FOR YOUR HOUSE


Total cost and Materials

 LDR                               -  35 Rs max.
An Arduino UNO           -  1300 Rs.
(or)
An Arduino clone           - 500 Min and 900 Max.
1Amp 5v input relay               -50 MAX.
230 v lamp                       - Depends on type of lamp you use.

Total Min cost :Rs 585

Working

Aim

To make a lamp which can detect the external light and turn off automatically and turns on when there is no external light.

Diagram




Program

boolean flag;  //CHECKS WHETHER THE LIGHT IS ON OR OFF.
void setup()
{
  pinMode(8,OUTPUT);  // connected to the Trigger of the Relay
  pinMode(A0,INPUT);  //To read the sensor Readings
  Serial.begin(9600); //Start serial monitor to troubleshoot during the project
}
void loop()
{
  int sensorinput;
  sensorinput=analogRead(A0); //Reads the value of the sensor
  Serial.println(sensorinput);
  
  // NOW CHECK THE READING OF THE SENSOR BY EXPOSING IT TO BRIGHT LIGHT AND DARK ATMOSPHERE
  // TO KNOW THE THRESHOLD VALUE OF THE LIGHT FOR EXAMPLE WHEN THE SENSOR RECEIVES A BRIGHT LIGHT IT GIVES A MAX VALUE ASSUME IT TO BE 500 AND IN DARK CONDITIONS IT GIVES 0.AS THE LIGHT GETS DIMMER TO THE SENSOR THE READINGS DECREASE FROM 500
  // CHECK THE MAX VALUE OF THE SENSOR AND MAKE A TRIAL AND ERROR AND FIND THE THRESHOLD FOR WHICH THE LAMP HAS TO TURN ON .
  // I HAVE TAKEN 200 FOR THE POST
  
  int threshold=200;
  if(sensorinput<threshold)         //LESS ENVIRONMENT LIGHT
  {
    Serial.println("LIGHTS ON");
    flag=true;
    pinMode(8,HIGH);
  }
  else
  {
    Serial.println("LIGHTS OFF");
    flag=false;
    pinMode(8,LOW);
  }
}

WORKING

In order to understand this project you need to know what is a Relay.

What is a relay?  (FROM http://www.circuitstoday.com/working-of-relays)

We know that most of the high end industrial application devices have relays for their effective working. Relays are simple switches which are operated both electrically and mechanically. Relays consist of a n electromagnet and also a set of contacts. The switching mechanism is carried out with the help of the electromagnet. There are also other operating principles for its working. But they differ according to their applications. Most of the devices have the application of relays.

Why is a relay used?

The main operation of a relay comes in places where only a low-power signal can be used to control a circuit. It is also used in places where only one signal can be used to control a lot of circuits. The application of relays started during the invention of telephones. They played an important role in switching calls in telephone exchanges. They were also used in long distance telegraphy. They were used to switch the signal coming from one source to another destination. After the invention of computers they were also used to perform Boolean and other logical operations. The high end applications of relays require high power to be driven by electric motors and so on. Such relays are called contacts.
Relay generally has 5 terminals . NORMALLY CLOSED,NORMALLY OPEN,COMMON,GROUND,TRIGGER.
IN THE ABOVE DIAGRAM LIVE WIRE OF THE SOCKET IS CONNECTED TO A LAMP AND THE NEUTRAL CONNECTION OF THE LAMP COMES FROM THE Relay's NORMALLY OPEN.WHEN A TRIGGER OF 5V IS SUPPLIED TO THE COIL OF THE RELAY (SAY SENSOR RETURNS A VALUE LESS THAN 200 ).THE COIL MAGNETISES AND THE COMMON GETS CONNECTED TO NORMALLY OPEN INTERNALLY. NOW THE LAMP HAS A CLOSED CIRCUIT AND LIGHT GLOWS AGAIN WHEN THERE IS A HIGH RESPONSE FROM THE SENSOR AND PIN 8 ON ARDUINO GOES LOW  AND THE COIL OF THE RELAY DE-MAGNETISES AND THE CIRCUIT FOR THE LAMP IS BROKEN  AND HENCE THE LIGHT GOES OFF.
LOGIC

SENSOR STATE
ARDUINO DIGITAL PIN STATE
RELAY STATE
LIGHT STATE
threshold> 200
Else part executes
Digital pin goes LOW
Breaks the lamp’s circuit
OFF
<200
If part executes digital pin goes HIGH
Closes the lamp’s circuit
ON


7. Serial communication from a computer or external device from an Arduino


PC to Arduino communication


This post describes on how a PC or any other wireless or wired device is going to send a message to a Arduino.This will explain a serial communication of a PC-Arduino & a Bluetooth-Arduino.


PC communication with a Arduino (Receiving serial data in Arduino)

It is easy to receive 8-bit values ,because at Serial functions use 8 bit values.The following sketch receives a digit from the computer and blinks the LED based on the number which is pressed on the computer's keyboard.


int ledpin=13;
int blinkRate=0;

void setup()
{
  Serial.begin(9600);   //STARTS THE SERIAL COMMUNICATION
  pinMode(13,OUTPUT);   //ACTIVATES THE ONBOARD LED
}
void loop()
{
  if(Serial.available())
  {
    char ch=Serial.read();
    if(isDigit(ch))   //if it is a number bw 0 to 9 (checks the ascii value
    {
      blinkRate(ch-'0');  //entered number's ASCII value is converted to number
      blinkRate=blinkRate*100;
    }
    digitalWrite(13,HIGH);
    delay(blinkRate);
    digitalWrite(13,LOW);
    delay(blinkRate);
  }
}
      

Descriptoin

The above sketch gets an input from the serial communication and converts it to no of seconds to blink.

Step 1:  check whether Serial connection is avail by Serial.available().
Step 2:  Read the input .
Step 3: The read input will be in ASCII so convert it to numeric value.
Step 4: Convert the numeric value to seconds to notice the blink( if we dont convert then the blinks will be soo fast that it wont be visible with our eyes instead we need a high frame rate camera to see it).
Step 5:Use the blink sketch and blink the LED with respect to the BlinkRate of number.




Friday 23 January 2015


6. Serial communications in Arduino

Introduction

Serial communication provides a easy way for Arduino to communicate with the computer and several other devices. The serial communication enables the computer to upload the programs to the computer as well as to send a data to computer.

Arduino IDE provides a serial monitor to display the data which is sent to the computer from the Arduino.


Data can be sent from the computer to the Arduino using the Text box avail on top of the serial monitor.
Baud Rate is selected using the drop down box on the bottom-right.You can use the drop down labelled "NO LINE ENDING"to automatically send a carriage return or a combination of a carriage return and a line at the end of each message sent when clicking the sent button by changing "No line ending"

Sending Information from your computer to your Arduino

Statement

You want to send text or data to be displayed on the PC using the Arduino IDE or the serial terminal program of your choice

Solution


void setup()
{
Serial.begin(9600); //begins a serial communication with the PC with the baud rate as 9600
}
void loop
{
int a;
Serial.print("The number is ");
Serial.print(a);
delay(600);
a=a+1;
}

OUTPUT

  The number is 0
  The number is 1
  The number is 2

// Number keeps on adding '1' and displays the output infinite times


Thursday 22 January 2015

Data-types used on Arduino


Except in situations where maximum performance or memory efficiency is required,Variables declared using int will be suitable for numeric values if the values do not exceed the range and if you dont need to work with fractional values.Most of the official Arduino example code declares numeric variables as int.But sometimes you do not need to choose a type that specifically suite your application.

UNSIGNED AND SIGNED

Sometimes you need negative numbers and sometimes you don't, so numeric types come in two varities:signed and unsigned.unsigned values are always positive.
variables without keyword unsigned in front are signed so that they can represent negative and positive values.one reason to use unsigned values is when the range of signed values will not fit in the range of the variable .

BOOLEAN

They have two values namely : True or false. They are commonly used in situations in order to check the state of the switch to know whether it is ON or OFF.

Example for boolean

int Switch=10;
void setup()
{
  pinMode(Switch,INPUT);
  Serial.begin(9600);
}
void loop()
{
     boolean switchstat;
     int switch1=digitalRead(Switch);
     if(switch1==HIGH)
    {
         switchstat=true;
     }
     else
    {
        switchstat=false;
    }
   if(switchstat==true)
   {
              Serial.println("LIGHTS ON");
   }
   else
   {
              Serial.println("LIGHTS OFF");
    }
}


Next post on using FLOATING-POINT NUMBERS

Wednesday 21 January 2015

Using a LDR with Arduino


To know about LDR check wikipedia


The sketch of the above schemetic is based on LED blinking code,but instead of using a fixed delay the rate is determined by the light sensitive sensor called LDR.

So now the following sketch will help you how to read the value of the LDR based on the sensitivity of light.

// Sketch to get the input from the LDR

int inputLDR=A0;
void setup()
{
  pinMode(inputLDR,INPUT);
 Serial.begin(9600);  // starts a serial connection with your computer to display the input of LDR with Baud rate of 9600
}
void loop()
{
   int a;    // to store the values which we received from the LDR
   a=analogRead(inputLDR); // Gets input from the LDR
   Serial.println(a);
}

 








Tuesday 20 January 2015

Blinking an External LED with an Arduino



The above Schematic will guide you on how an External LED must be interfaced with an Arduino.
In the above case Two LED's red and yellow are connected.

you can use the same blink code which i have given in the previous  post.Instead of using the pin number as 13 you can use the pin 9 and 10;
Any range of resistors between 1K and 10k can be used .

Code to use the above Schematic for blink as well as fading the LED's

int redled=9;
int yellowled=10;
void Setup()
{
   pinMode(redled,OUTPUT);
   pinMode(yellowled,OUTPUT);
}
void loop()
{
// For the blink of both the led

digitalWrite(redled,HIGH);
digitalWrite(yellowled,HIGH);
delay(1000);
digitalWrite(redled,LOW);
digitalWrite(yellowled,LOW);
delay(1000);

// For fading the LED

for(int i=0;i<250;i++)
{
 analogWrite(redled,i);
 analogWrite(yellowled,i);
 }
for(int i=250;i<0;i--)
{
 analogWrite(redled,i);
 analogWrite(yellowled,i);
 }


}//end of loop


Comment either use of code to test the fading and blink



Monday 19 January 2015

Blink code in Arduino ( Blink LED ON and OFF using Arduino)


/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
 
  This example code is in the public domain.
 */
 
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

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




The following code is available by default in Arduino in File---->Examples---->basics----->blink

Working of the code

The pin 13 avail in the Arduino UNO has a On-board LED with a internal resistance with it .
so in order to activate the internal resistance the code " pinMode(led,OUTPUT) "(in void setup) is used.
The variable led is initialized with 13 and the pin 13 is said to be a output.
So the resistance of the on board LED is activated.


Now in void loop()  the code

digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 
supplies 5v(ie Vcc) to the LED and hence it glows up..!! :D
now it has a delay(1000) which waits for one second and again it switches off the LED and waits for 1 sec.

This process repeats for ever in void loop()..!!



Getting Started with Arduino


The Arduino environment has been designed to be esy to use for beginners who have no software or electronics Xp's unlike me..!!With Arduino you can build objects that can respond to and/or control lights,sound,touch and movement..(What else do you probably need???)
So you can use Arduino to create your own musical instruments,Robots,light sculptures,games,interactive furniture and even interactive clothing .

Arduino is used in many educational programs around the world,particularly by designers and artists who want ot easily create prototypes but do not need a deep understanding of the technical detailes behind their creations.Because it is designed to be used by non-tech people the software includes plenty of example code to demonstrate how to use the Arduino board .

Arduino Software

Software programs called sketches are created on a computer using the Arduino IDE . The IDE enables you to write and edit code and convert this code into instructions that Arduino hardware understands.The IDE also transfers those instructions to the Arduino board.

Arduino Hardware Spec

 https://h4ckr-naren.blogspot.com/b/post-preview?token=g0a3BEsBAAA.hbmbliLvBIZwcMUU5Tb13A.wnqBlh_p3a-9M-dhxu5rRw&postId=7426553885776567980&type=POST