Freeduino Sample Programs
  1. Interfacing LED's


Components Required: 

  • Arduino Uno             1 No
  • LED                          1 No
  • Connecting wires      2 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right LED connected to pin 2 of Arduino Uno.

Arduino-Sketch:

Now using the Processing IDE we will make a program for controlling the Arduino. Here’s the source code.

int LED = 2;
int LED2 = 13;
void setup()
{ 
Serial.begin(9600);
pinMode(LED,OUTPUT);
pinMode(LED2,OUTPUT);
}
void loop()
{
digitalWrite(LED,HIGH);
digitalWrite(LED2,HIGH);
Serial.println("ON");
delay(1000);
digitalWrite(LED,LOW);
digitalWrite(LED2,LOW);
Serial.println("OFF");
delay(1000);
}

Source Code For Interfacing_Led


2. Interfacing LED with Key’s

Components Required: 

  1. ARDUINO Uno                 1 No
  2. LED                                 1 No
  3. Connecting wires             4 No
  4. Tic-Tac Switch                  1 No

 Procedure:

  1. Connections are made as per the circuit diagram.
  2. Connect your ARDUINO uno to your computer.
  3. Enter the program given below.
  4. Now upload the program.
  5.  If all goes right LED connected to pin 2 will ON when key is pressed & goes OFF when key is released.

Arduino-Sketch:

Now using the Processing IDE we will make a program for controlling the Arduino. Here’s the source code.

int LED = 2;
int KEY = 3;
int state;
void setup()
{
Serial.begin(9600);
pinMode(LED,OUTPUT);
pinMode(KEY,INPUT_PULLUP);
pulseIn(KEY,HIGH);
}
void loop()
{
state=digitalRead(KEY);
if(state==LOW)
{
digitalWrite(LED,HIGH);
Serial.println("ON");
}
if(state==HIGH)
{
digitalWrite(LED,LOW);
Serial.println("OFF");
}
}

Source Code for Interfacing_LED_with_Key


3. Interfacing 7 Segment Display


Components Required: 

  • ARDUINO Uno                  1 No
  • 7 Seg C-Cathode             1 No
  • Connecting wires             10 No
  • Tic-Tac Switch                  1 No

 Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right for each time key press the count on 7 seg display will increase starts from zero.
/* * Arduino 4x7 LED Display * Displays numbers ranging from 0 through 1023 * Test Code displays the value of a sensor connected to the analog input A0 * Inspired by a code found in the Arduino Cookbook * Tested at TechNode Protolabz/July 2014 */
// bits representing segments A through G (and decimal point) for numerals 0-9
const int numeral[10] = {   //ABCDEFG /dp   B11111100, // 0   B01100000, // 1   B11011010, // 2   B11110010, // 3   B01100110, // 4   B10110110, // 5   B00111110, // 6   B11100000, // 7   B11111110, // 8   B11100110, // 9
};
// pins for decimal point and each segment
// DP,G,F,E,D,C,B,A
const int segmentPins[] = { 13,8,7,6,5,4,3,2 };
const int nbrDigits= 4; // the number of digits in the LED display
//dig 0 1 2 3
const int digitPins[nbrDigits] = { 9,10,11,12 };
void setup()
{   for(int i=0; i < 8; i++) {      pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output   }   for(int i=0; i < nbrDigits; i++) {      pinMode(digitPins[i], OUTPUT);   }
} 
void loop()
{   int value = analogRead(0);   showNumber(value);
} 
void showNumber( int number)
{   if(number == 0) {      showDigit( 0, nbrDigits-1) ; // display 0 in the rightmost digit   } else {      // display the value corresponding to each digit      // leftmost digit is 0, rightmost is one less than the number of places      for( int digit = nbrDigits-1; digit >= 0; digit--)  {         if(number > 0)  {            showDigit( number % 10, digit) ;            number = number / 10;         }      }   }
} 
// Displays given number on a 7-segment display at the given digit position
void showDigit( int number, int digit)
{   digitalWrite( digitPins[digit], HIGH );   for(int segment = 1; segment < 8; segment++)  {      boolean isBitSet = bitRead(numeral[number], segment);      // isBitSet will be true if given bit is 1      // isBitSet = ! isBitSet; // Code Option*      // uncomment the above Code Option line for common anode display      digitalWrite( segmentPins[segment], isBitSet);   }   delay(5);   digitalWrite( digitPins[digit], LOW );
}

Source Code For 7_Segment Display 


4. Interfacing LCD Keypad

Components Required: 

  • ARDUINO Uno                 1 No
  • 16x2 Display                   1 No
  • Connecting wires            9 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • observe the LCD display which is displaying welcome to Aakaarlab and seconds elapsed

Arduino-Sketch:

// include the library code:
#include 
// initialize the library with the numbers of the interface pins
LiquidCrystallcd(7, 6, 5, 4, 3, 2);
void setup() {
  // set up the LCD's number of columns and rows:
lcd.begin(16, 2);
  // Print a message to the LCD.
lcd.print("Welcome to IBANTAM");
}
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);
}

Source Code For Interfacing_LCD


5. Interfacing 4 Wire Resistivity Touch Screen

Components Required: 

  • ARDUINO Uno                 1 No
  • Touch Screen                  1 No
  • Connecting wires             9 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • Observe the Serial port on Computer which is displaying the Touch screen coordinates.

Arduino-Sketch:

#include 
TouchScreents(3, 1, 0, 2);
void setup()
{
Serial.begin(9600);
}
void loop()
{
intcoords[2];
ts.read(coords);
Serial.print(coords[0]);
Serial.print(",");
Serial.println(coords[1]);
delay (1000);
}

Source Code for Interfacing_Touch_Screen


6. Interfacing ADXL335 Accelerometer 

An Accelerometer is an electro mechanical device used to measure acceleration forces. Such forces may be static, like the continuous force of gravity or, as is the case with many mobile devices, dynamic to sense movement or vibrations. Acceleration is the measurement of the change in velocity, or speed divided by time.

Components Required: 

  • ARDUINO Uno                 1 No
  • ADXL335                         1 No
  • Connecting wires             5 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • Observe the Serial port on Computer which is displaying the Value of each axis in x , y , z.

Arduino-Sketch:

/* The circuit:
analog 0: x-axis
analog 1: y-axis
analog 2: z-axis
*/
// these constants describe the pins. They won't change:
constintxpin = A0;                  // x-axis of the accelerometer
constintypin = A1;                  // y-axis
constintzpin = A2;                  // z-axis (only on 3-axis models)
void setup()
{
  // initialize the serial communications:
Serial.begin(9600);
}
void loop()
{
  // print the sensor values:
Serial.print(analogRead(xpin));
  // print a tab between values:
Serial.print("\t");
Serial.print(analogRead(ypin));
  // print a tab between values:
Serial.print("\t");
Serial.print(analogRead(zpin));
Serial.println();
  // delay before next reading:
delay(100);
}

Source Code for Interfacing_Accelerometer


7. Interfacing RFID Reader (EM18)

A Radio Frequency Identification Reader (RFID Reader) is a device used to gather information from an RFID tag, which is used to track individual objects. Radio waves are used to transfer data from the tag to a reader.

RFID is a technology similar in theory to bar codes. However, the RFID tag does not have to be scanned directly, nor does it require line-of-sight to a reader. The RFID tag it must be within the range of an RFID reader, which ranges from 3 to 300 feet, in order to be read. RFID technology allows several items to be quickly scanned and enables fast identification of a particular product, even when it is surrounded by several other items.RFID tags have not replaced bar codes because of their cost and the need to individually identify every item.

Components Required: 

  • ARDUINO Uno                    1 No
  • EM18 RFID Reader            1 No
  • Connecting wires                3 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • Observe the characters read on serial port of Computer.

Arduino-Sketch:

int count = 0;
void setup()
    {
Serial.begin(9600);
    }
void loop()
    {
if(Serial.available())
    {
count = 0; // Reset count to zero// Keep reading Byte by Byte from the Buffer till the Buffer is empty
    {
char input = Serial.read();
Serial.print(input);
count++; //
delay(5); //
    }
Serial.println();
Serial.print("Tag Length : ");
Serial.print(count);
Serial.println(" Bytes");
    }
    }

Source Code for Interfacing_RFID_Reader


8. Interfacing Serial Port

serial port is a serial communication interface through which information transfers in or out one bit at a time. While such interfaces as Ethernet, FireWire, and USB all send data as a serial stream, the term "serial port" usually identifies hardware more or less compliant to the RS-232 standard, intended to interface with a modem or with a similar communication device.

Components Required: 

  • Arduino Uno                      1 No

Procedure

  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right see on your serial port letters will received from Arduino & Send character to Arduino then they received data will show on LCD

Arduino-Sketch:

// include the library code:
#include 
// initialize the library with the numbers of the interface pins
LiquidCrystallcd(7, 6, 5, 4, 3, 2);
void setup() {
Serial.begin(9600);
  // set up the LCD's number of columns and rows:
lcd.begin(16, 2);
  // Print a message to the LCD.
lcd.print("Serial Interface");
}
void loop()
{
Serial.println("I");
delay(1000);
Serial.println("B");
delay(1000);
Serial.println("A");
delay(1000);
Serial.println("N");
delay(1000);
Serial.println("T");
delay(1000);
Serial.println("A");
delay(1000);
Serial.println("M");
delay(1000);
}

Source Code for Interfacing_Serial_Port


9. Interfacing DC Motor

A DC motor is any of a class of rotary electrical machines that converts direct current electrical energy into mechanical energy. The most common types rely on the forces produced by magnetic fields. Nearly all types of DC motors have some internal mechanism, either electromechanical or electronic, to periodically change the direction of current flow in part of the motor. 

DC motors were the first type widely used, since they could be powered from existing direct-current lighting power distribution systems. A DC motor's speed can be controlled over a wide range, using either a variable supply voltage or by changing the strength of current in its field winding. Small DC motors are used in tools, toys, and appliances. The universal motor can operate on direct current but is a lightweight brushed motor used for portable power tools and appliances. Larger DC motors are used in propulsion of electric vehicles, elevator and hoists, or in drives for steel rolling  mills.  The advent of power electronics has made replacement of DC motors with AC motors possible in many applications.

Components Required: 

  • Arduino Uno                    1 No
  • DC Motor                         2 No
  • Connecting wires             8 No
  • Tic Tac Key                      1 No
  • L293D Motor                   1 No

Procedure

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right Motor Starts rotate when key is pressed the motor start rotate in opposite direction until the key is released. When key is released the motor starts rotate in the direction as in the beginning.

Arduino-Sketch:

int motorA1 = 3;
int motorA2 = 4;
intenableA = 2;
int motorB1 = 6;
int motorB2 = 7;
intenableB = 5;
int key = 8;
int state;
void setup() {
pinMode(motorA1, OUTPUT);
pinMode(motorA2, OUTPUT);
pinMode(motorB1, OUTPUT);
pinMode(motorB2, OUTPUT);
pinMode(enableA, OUTPUT);
pinMode(enableB, OUTPUT);
digitalWrite(enableA, HIGH);
digitalWrite(enableB, HIGH);
pinMode(key,INPUT_PULLUP);
pulseIn(key,HIGH);
}
void loop() {
state=digitalRead(key);
if(state==LOW)
{digitalWrite(motorA1, LOW);
digitalWrite(motorA2, HIGH);
digitalWrite(motorB1, LOW);
digitalWrite(motorB2, HIGH);
}
else  {digitalWrite(motorA2, LOW);
digitalWrite(motorA1, HIGH);
digitalWrite(motorB2, LOW);
digitalWrite(motorB1, HIGH);
  }
}

Source Code for Interfacing_DC_Motor


10. Interfacing Stepper Motor

A stepper motor or step motor or stepping motor is a brush-less DC electric motor that divides a full rotation into a number of equal steps. The motor's position can then be commanded to move and hold at one of these steps without any position sensor for feedback (an open-loop controller), as long as the motor is carefully sized to the application in respect to torque and speed.

Switched reluctance motors are very large stepping motors with a reduced pole count, and generally are closed-loop communicated.

Brushed DC motors rotate continuously when DC voltage is applied to their terminals. The stepper motor is known by its property to convert a train of input pulses (typically square wave pulses) into a precisely defined increment in the shaft position. Each pulse moves the shaft through a fixed angle.

Stepper motors effectively have multiple "toothed" electromagnets arranged around a central gear-shaped piece of iron. The electromagnets are energized by an external driver circuit or a micro controller. To make the motor shaft turn, first, one electromagnet is given power, which magnetically attracts the gear's teeth. When the gear's teeth are aligned to the first electromagnet, they are slightly offset from the next electromagnet. This means that when the next electromagnet is turned on and the first is turned off, the gear rotates slightly to align with the next one. From there the process is repeated. Each of those rotations is called a "step", with an integer number of steps making a full rotation. In that way, the motor can be turned by a precise angle.

The circular arrangement of electromagnets is divided into groups, each group called a phase, and there is an equal number of electromagnets per group. The number of groups is chosen by the designer of the stepper motor. The electromagnets of each group are interleaved with the electromagnets of other groups to form a uniform pattern of arrangement. For example, if the stepper motor has two groups identified as A or B, and ten electromagnets in total, then the grouping pattern would be ABABABABAB.

Electromagnets within the same group are all energized together. Because of this, stepper motors with more phases typically have more wires (or leads) to control the motor.

Components Required: 

  • Arduino Uno                     1 No
  • Stepper Motor                  1 No
  • Connecting wires             4 No

Procedure

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right stepper Motor Starts rotate 360 deg one revolution clockwise & then anticlockwise.

Arduino-Sketch:

#include 
constintstepsPerRevolution = 200;  // change this to fit the number of steps per revolution
                                     // for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8,9,10,11);           
void setup() {
  // set the speed at 60 rpm:
myStepper.setSpeed(60);
  // initialize the serial port:
Serial.begin(9600);
}
void loop() {
  // step one revolution  in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
   // step one revolution in the other direction:
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}

Source code for Interfacing_Stepper_Motor


11. Interfacing IR Obstacle Sensor & Relay

Infrared technology addresses a wide variety of wireless applications. The main areas are sensing and remote controls. In the electromagnetic spectrum, the infrared portion is divided into three regions: near infrared region, mid infrared region and far infrared region.

The frequency range of infrared is higher than microwave and lesser than visible light. For optical sensing and optical communication, photo optics technologies are used in the near infrared region as the light is less complex than RF when implemented as a source of signal. Optical wireless communication is done with IR data transmission for short range applications. An infrared sensor emits and/or detects infrared radiation to sense its surroundings.

Components Required: 

  • ARDUINO Uno                 1 No
  • IR Obstacle Sensor         1 No
  • Relay                               1 No
  • BC547 Transistor            1 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right whenever obstacle detected the relay will switch on for 10 seconds and then it switch off.

Arduino-Sketch:

int RELAY = 2;
int SENSOR = 3;
int state;
void setup()
{
Serial.begin(9600);
pinMode(RELAY,OUTPUT);
pinMode(SENSOR,INPUT_PULLUP);
pulseIn(SENSOR,LOW);
}
void loop()
{
state=digitalRead(SENSOR);
if(state==LOW)
{
digitalWrite(RELAY,LOW);
Serial.println("OFF");
}
if(state==HIGH)
{
digitalWrite(RELAY,HIGH);
Serial.println("Obstacle detected");
delay(2000);
}
}

Source Code for Interfacing_IR_Obstacle_Sensor_Relay


12. Interfacing Temperature Sensor (LM35)

A temperature sensor is a Thermocouple or a resistance temperature detector (RTD) that gathers the temperature from a specific source and alters the collected information into understandable type for an apparatus or an observer. Temperature sensors are used in several applications namely HV system and AC system environmental controls, medical devices, food processing units, chemical handling, controlling systems, automotive under the hood monitoring and etc.

The LM35 is one kind of commonly used temperature sensor that can be used to measure temperature with an electrical o/p comparative to the temperature (in °C). It can measure temperature more correctly compare with a Thermistor. This sensor generates a high output voltage than thermocouples and may not need that the output voltage is amplified. The LM35 has an output voltage that is proportional to the Celsius temperature. The scale factor is .01V/°C.

The LM35 does not need any exterior calibration and maintains an exactness of +/-0.4°C at room temperature and +/-0.8°C over a range of 0°C to +100°C.One more significant characteristic of this sensor is that it draws just 60 microamps from its supply and acquires a low self-heating capacity. The LM35 temperature sensor available in many different packages like T0-46 metal can transistor-like package, TO-92 plastic transistor-like package, 8-lead surface mount SO-8 small outline package.

Components Required: 

  • ARDUINO Uno                   1 No
  • LCD 16x2                          1 No
  • LM35                                 1 No
  • Connecting wires              13 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right Temperature will be displayed on LCD 16x2 Display.

Arduino-Sketch:

#include 
int reading = 0;
intsensorPin = A0;
    // initialize the library with the numbers of the interface pins
LiquidCrystallcd(7, 6, 5, 4, 3, 2);
void setup() {
    // set up the LCD's number of columns and rows:
lcd.begin(16, 2);
    }
void loop()
    {
reading = analogRead(sensorPin);
intcelsius = reading/2;
lcd.setCursor(0, 0);
lcd.print("Temperature: ");        
lcd.setCursor(0,1);
lcd.print(celsius, DEC);
lcd.print((char)223);
lcd.print("C");
delay(500);
lcd.clear();
    }
}

Source Code for Interfacing_Temperature_Sensor


13. Interfacing HC05 Bluetooth Module for controlling Relay / Buzzer / DC motor

HC‐05 module is an easy to use Bluetooth SPP (Serial Port Protocol) module,designed for transparent wireless serial connection setup.The HC-05 Bluetooth Module can be used in a Master or Slave configuration, making it a great solution for wireless communication.This serial port bluetooth module is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation with complete 2.4GHz radio transceiver and baseband. It uses CSR Bluecore 04‐External single chip Rluetooth system with CMOS technology and with AFH (Adaptive Frequency Hopping Feature).

Components Required: 

  • ARDUINO Uno         1 No
  • LCD 16x2                 1 No
  • LM35                        1 No
  • Connecting wires     13 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right Temperature will be displayed on LCD 16x2 Display.

 Arduino-Sketch:

int Relay = 13;
int Motor = 12;
int Buzzer = 11;
char state;
void setup() {
pinMode(Relay, OUTPUT);
pinMode(Motor, OUTPUT);
pinMode(Buzzer, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0){
state = Serial.read();
}
if (state == '1')
{
digitalWrite(Relay, HIGH);
Serial.println("Relay: ON");
state=0;
}
else if (state == '2')
{
digitalWrite(Relay, LOW);
Serial.println("Relay: OFF");
state=0;
}
else if (state == '3')
{
digitalWrite(Motor, HIGH);
Serial.println("Motor: ON");
state=0;
}
else if (state == '4')
{
digitalWrite(Motor, LOW);
Serial.println("Motor: OFF");
state=0;
}
else if (state == '5')
{
digitalWrite(Buzzer, HIGH);
Serial.println("Buzzer: ON");
state=0;
}
else if (state == '6')
{
digitalWrite(Buzzer, LOW);
Serial.println("Buzzer: OFF");
state=0;
}
}

Source Code for Interfacing_Bluetooth_Module


14. Interfacing Proximity Sensor


A proximity sensor is a sensor able to detect the presence of nearby objects without any physical contact.
A proximity sensor often emits an electromagnetic field or a beam of electromagnetic radiation (infrared, for instance), and looks for changes in the field or return signal. The object being sensed is often referred to as the proximity sensor's target. Different proximity sensor targets demand different sensors. For example, a capacitive proximity sensor or photoelectric sensor might be suitable for a plastic target; an inductive proximity sensor always requires a metal target. Proximity sensors can have a high reliability and long functional life because of the absence of mechanical parts and lack of physical contact between the sensor and the sensed object. Proximity sensors are also used in machine vibration monitoring to measure the variation in distance between a shaft and its support bearing. This is common in large steam turbines, compressors, and motors that use sleeve-type bearings.

Components Required: 

  • ARDUINO Uno         1 No
  • PIR Sensor              1 No
  • Connecting wires     3 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right after 30 Seconds if any moment appear or detected on PIR warning light glow for a 2 seconds and go off after 2 seconds.

 Arduino-Sketch:

intalertsignal=4; // Sensor input pin D4
intwarnlight=13; // Warning light output pin D5
intalertsignalState;
void setup()
    {
pinMode(warnlight, OUTPUT); // Warning light pin as output
pinMode(alertsignal, INPUT_PULLUP); // Sensor pin as input
digitalWrite(warnlight, HIGH);
delay(30*1000);
digitalWrite(warnlight, LOW);
    /* inhibit alert input for 30 seconds during initial power on.
    Only for PIR sensor (see article) */
    }
void loop()
    {
alertsignalState=digitalRead(alertsignal);
if(alertsignalState == HIGH)
    {
digitalWrite(warnlight, HIGH);
delay(2000);
digitalWrite(warnlight, LOW);
delay(1000);
    }
else
    {
digitalWrite(warnlight, LOW);
    }
    }

Source Code for Interfacing_PIR_Sensor


15. Interfacing Buzzer for playing Melody (Tone)

Components Required: 

  • ARDUINO Uno         1 No
  • Buzzer                      1 No
  • BC547 Transistor     1 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If all goes right a melody will be played on Buzzer.

 Arduino-Sketch:

#include "pitches.h"
// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
intnoteDurations[] = {
  4, 8, 8, 4,4,4,4,4 };
void setup()
 {
 }
void loop() {
  // iterate over the notes of the melody:
for (intthisNote = 0; thisNote< 8; thisNote++) {
    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
intnoteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
intpauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
    // stop the tone playing:
noTone(8);
  // no need to repeat the melody.
}
}

Source Code for Buzzer for playing Melody


16. Interfacing Ultrasonic Sensor (HCSR04)

As the name indicates, ultrasonic sensors measure distance by using ultrasonic waves. The sensor head emits an ultrasonic wave and receives the wave reflected back from the target. Ultrasonic Sensors measure the distance to the target by measuring the time between the emission and reception. An optical sensor has a transmitter and receiver, whereas an ultrasonic sensor uses a single ultrasonic element for both emission and reception. In a reflective model ultrasonic sensor, a single oscillator emits and receives ultrasonic waves alternately. This enables miniaturization of the sensor head.

Components Required: 

  • ARDUINO Uno         1 No
  • Buzzer                      1 No
  • BC547 Transistor     1 No
  • HCSR04                  1 No
  • LED RED                 1 No
  • 1k Resistor               2 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • If everything goes right, you should see the burning eye of the red LED when there is no object in the safe-zone (within 5 cm from the HC-SR04 module), and an ear-splitting beep from the Piezo-buzzer.

 Arduino-Sketch:

//Pins for HC-SR04
constinttrigPin = 13;
                //Pin which delivers time to receive echo using pulseIn()
intechoPin = 12;
intsafeZone = 5;
    // Pins for Indicators
intstatusLed = 11;
intpzBzr = 10;
void setup()
{
                 }
void loop()
                  {
                //raw duration in milliseconds, cm is the
                //converted amount into a distance
                long duration, cm;
                //initializing the pin states
                pinMode(trigPin, OUTPUT);
                pinMode(statusLed, OUTPUT);
                pinMode(pzBzr, OUTPUT);
                //sending the signal, starting with LOW for a clean signal
                digitalWrite(trigPin, LOW);
                delayMicroseconds(2);
                digitalWrite(trigPin, HIGH);
                delayMicroseconds(10);
                digitalWrite(trigPin, LOW);
                //setting up the input pin, and receiving the duration in uS
                pinMode(echoPin, INPUT);
                duration = pulseIn(echoPin, HIGH);
                // convert the time into a distance
                cm = microsecondsToCentimeters(duration);
                //Checking if anything is within the safezone
                // If not, keep status LED on
                // Incase of a safezone violation, activate the piezo-buzzer
                if (cm >safeZone)
                                {
                                                digitalWrite(statusLed, HIGH);
                                                digitalWrite(pzBzr, LOW);
                                }
                                else
                                {
                                                digitalWrite(pzBzr, HIGH);
                                                digitalWrite(statusLed, LOW);
                                }
                delay(100);
                }
longmicrosecondsToCentimeters(long microseconds)
                 {
                                // The speed of sound is 340 m/s or 29 microseconds per centimeter
                                // The ping travels forth and back
                                // So to calculate the distance of the object we take half of the travel
                                return microseconds / 29 / 2;
                }

Source Code for Interfacing_Ultrasonic_Sensor_HCSR04


17. Interfacing Servo Motor & Joystick

A servomotor is a rotary actuator or linear actuator that allows for precise control of angular or linear position, velocity and acceleration. It consists of a suitable motor coupled to a sensor for position feedback. It also requires a relatively sophisticated controller, often a dedicated module designed specifically for use with servomotors.Servomotors are not a specific class of motor although the term servomotor is often used to refer to a motor suitable for use in a closed-loop control system.

Servomotors are used in applications such as robotics, CNC machinery or automated manufacturing.

Components Required: 

  • ARDUINO Uno         1 No
  • POT or Joystick        1 No
  • Servo Motor              1 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • Rotate the knob of pot or move joystick and observe the corresponding rotation of Servo motor..

 Arduino-Sketch:

#include 
Servo servo1;
Servo servo2;
int x_key = A1;
int y_key = A0;
int x_pos;
int y_pos;
int servo1_pin = 8;
int servo2_pin = 9;
int initial_position = 90;
int initial_position1 = 90;
void setup ( ) {
Serial.begin (9600) ;
servo1.attach (servo1_pin ) ;
servo2.attach (servo2_pin ) ;
servo1.write (initial_position);
servo2.write (initial_position1);
pinMode (x_key, INPUT) ;
pinMode (y_key, INPUT) ;
}
void loop ( ) {
x_pos = analogRead (x_key) ; 
y_pos = analogRead (y_key) ;
if (x_pos < 300){
if (initial_position < 10) { } else{ initial_position = initial_position - 20; servo1.write ( initial_position ) ; delay (100) ; } } if (x_pos > 700){
if (initial_position > 180)
{
}
else{
initial_position = initial_position + 20;
servo1.write ( initial_position ) ;
delay (100) ;
}
}
if (y_pos < 300){
if (initial_position1 < 10) { } else{ initial_position1 = initial_position1 - 20; servo2.write ( initial_position1 ) ; delay (100) ; } } if (y_pos > 700){
if (initial_position1 > 180)
{ 
}       
else{
initial_position1 = initial_position1 + 20;
servo2.write ( initial_position1 ) ;
delay (100) ;
}
}
}

Source Code for Interfacing_Servo_Motor_Joystick


18. Interfacing of Flex Sensor



A Flex Sensor or bend sensor is a sensor that measures the amount of deflection or bending. Usually, the sensor is stuck to the surface, and resistance of sensor element is varied by bending the surface. Since the resistance is directly proportional to the amount of bend it is used as goniometer, and often called flexible potentiometer.

Components Required: 

  • ARDUINO Uno         1 No
  • Flex Sensor              1 No
  • 22K Ohm Resistor    1 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • Rotate the knob of pot or move joystick and observe the corresponding rotation of Servo motor..

 Arduino-Sketch:

const int flexPin = A0;
const int ledPin = 7;
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
}
void loop()
{
int flexValue;
flexValue = analogRead(flexPin);
Serial.print("sensor: ");
Serial.println(flexValue);
if(flexValue>890)
digitalWrite(ledPin,HIGH);
else
digitalWrite(ledPin,LOW);
delay(20);
}

Source Code for Flex_Sensor


19.  Interfacing RF Transmitter & Receiver for Data Communication

The RF modules are very small in dimension and have a wide operating voltage range i.e. 3V to 12V.

Basically the RF modules are 433 MHz RF transmitter and receiver modules. The transmitter draws no power when transmitting logic zero while fully suppressing the carrier frequency thus consume significantly low power in battery operation. When logic one is sent carrier is fully on to about 4.5mA with a 3volts power supply. The data is sent serially from the transmitter which is received by the tuned receiver. Transmitter and the receiver are duly interfaced to two microcontrollers for data transfer. 

As compared to the other radio-frequency devices, the performance of an RF module will depend on several factors like by increasing the transmitter’s power a large communication distance will be gathered. However, which will result in high electrical power drain on the transmitter device, which causes shorter operating life of the battery powered devices. Also by using this devices at higher transmitted power will create interference with other RF devices.

Components Required: 

  • ARDUINO Uno         1 No
  • RF Tx & Rx              1 No
  • Connecting Wires    8 No

Procedure:

  • Connections are made as per the circuit diagram.
  • Connect your ARDUINO Uno to your computer.
  • Enter the program given below.
  • Now upload the program.
  • f all goes right, you will be receive the word “Hello from aakaarlab” on Serial monitor on receiver section.

 Arduino-Sketch:

/*SimpleSendThis sketch transmits a short text message using the VirtualWirelibraryconnect the Transmitter data pin to Arduino pin 12*/
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
send("Hello from aakaarlab");
delay(1000);
}
void send (char *message)
{
vw_send((uint8_t *)message, strlen(message));
vw_wait_tx(); // Wait until the whole message is gone
}Program for Receiver section:/*SimpleReceiveThis sketch displays text strings received using VirtualWireConnect the Receiver data pin to Arduino pin 11*/
#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
bytemessageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
Serial.begin(9600);
Serial.println("Device is ready");
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
vw_rx_start(); // Start the receiver
}
void loop()
{
if (vw_get_message(message, &messageLength)) // Non-blocking
{
Serial.print("Received: ");
for (inti = 0; i<messageLength; i++)
{
Serial.write(message[i]);
}
Serial.println();
}
}

Source Code for RF_Transmitter

Source Code for RFReceiver



I BUILT MY SITE FOR FREE USING