Contents
1. Background
2. Setting up Arduino Development Environment
3. Arduino Power Management
3.1 Powering Up Arduino Board
3.2 Output Power of Arduino
4. Indicators And Switches
4.1 LED
4.1.1 Working With Onboard LED
4.1.2 Connecting and Controlling External LED
4.2 Buzzer
4.3 Switches
5. Arduino With Display
6.Arduino With Sensors
6.1 Sensor Principles
6.2 A/D Converter
6.3 Temperature Sensor
6.4 Metal Sensor
6.5 Ultrasonic Sensor With Arduino 7. PWM
7.1 PWM Basics
7.2 Arduino's PWM Support
7.3 Controlling LED Intensity through PWM 8. Working With Relays
8.1 Relay Basics
8.2 Arduino with Relays
8.2.1 Relay Control Using Transistor
8.2.2 Relay Control using Optocoupler
9. Working With Motors
9.1 DC Motor Control using Transistors
9.2 Controlling Motors Through Relay
10. Wireless With IR Sensor 11. Conclusion
Arduino is a great embedded platform for prototyping your hobby projects. It is really easy to learn, simple yet efficient and powerful. Arduino Boards are powered by Atmel family Microcontrollers. The board as several features which are so crucial to many hardware applications which includes Digital pins,Ability to drive low power motors, PWM, ability to connect to other devices using Serial Communication, onbard A/D converter which can directly read sensor values and many more. Even though the platform is claimed to be only for prototyping, I have personally used the board for many production projects and it works quite well in those works too. In an era of Internet Of Things where main focus of development in embedded system is being shifted entirely towards developing services for the devices. However understanding and learning the hardware capabilities of these devices, ways of controlling displays, indicators, buzzers, actuators, working with sensors also plays an important role. It helps once build a conceptual framework of the capabilities of such devices which makes it easy to integrate such boards over IoT.
Even though Arduino has been around for some good time and has had gone through several changes, the core features remains same. There are many blogs and articles around that explains the working of Arduino with different hardwares, I found not a single web entry that provides an insight of the overall hardware features of the platform. Therefore for a non embedded developer( non Electronics developer), learning the hardware part becomes a real stiff learning curve. In this Tutorial I would try to provide an insight into overall hardware capabilities of Arduino with most common hardware required to develop real time projects with the platform. This tutorial is aimed at developers who are well versed with progrmming but are trying to start with embedded platform in general and Arduino in particular. Choice of Arduino is obvious because of it's simplicity which makes Arduino learning real simple. For most of the connections, I have preferred connecting the hardware with Pin connectors and bread boards so that those who are not comfortable with Soldering and PCBs can find it easy to follow.
First download latest Arduino IDE from Arduini's Official Software Download Site. Windows user will be able to download an Installer. The installer has a FTDI usb driver along with the IDE itself. Prefer to install the USB driver. This is essential. Without USB driver your IDE can not communicate with the Arduino Device.
Following is the Pin Description of the device that I am using.
Figure 2.1: Arduino Diecimilia/Duemilanova with Pin Levels
Once the software is installed, plug Arduino's USB cable to your laptop. You will see a notification in tray "installing driver". Once driver installation is successfull Open Device manager ( start->right click on Computer icon->Properties->Device manager).
Figure 2.2: Device Manager After Arduino is Plugged in.
In the Ports(Com and LPT) section you see USB serial port. In case of Arduino Uno R3, you will see Arduino Uno marker along the port. When you plug out the cable, you won't find the port anymore. So this is the port at which your Arduino device is connected.
If you have connected your device for the first time, you will also notice that the LED near digital pin 13 is blinking. Most of the Arduino boards are preloaded with a blink program which blinks the LED connected to pin 13.
Before starting with our coding, we need just couple of more steps to setup IDE with the board.
Open the IDE. Tools->Boards select the board you are connecting as shown in figure below.
Figure 2.3: Arduino Board Selection
Once the board is selected, you need to set the correct serial port as you have figured out from figure 2.2
Figure 2.4: Selecting USB Serial Port in IDE
Before we go into programming the boards we will learn some simple basics of Arduino C programming.
2.2 Basics of Arduino C Program
Following is the basic structure of the Arduino program. An Arduino C program is also known as a sketch.
Collapse |
Copy Code
void setup() {
}
void loop() {
}
setup()
is executed once ( when you reset the device, or restrat the device, or plug in the USB cable ). loop()
runs continuesly. Main logic must be implemented inside loop.
Arduino Duemilanova/Diecimilia/Uno R3 ( from here onwards will refer simply as Arduino) board has 14 Digital IP pins. Each pin can be program separately. A Pin can be in with OUTPUT mode or input mode which needs to be specified in setup using
pinMode(PIN_NO,OUTPUT)
or pinMode(PIN_NO,INPUT);
Input mode is used when you connect a switch to a pin and want the pin to read the status. These digital pins in input mode can only recognize logic level input like 0 and 1. PIN_NO ranges from 0-13 depending upon the pin you are programming.
you can write logical output in a pin in OUTPUT mode or can read the the value at the pin ( 1 or 0) usingdigitalWrite(PIN_NO,HIGH)/digitalWrite(PIN_NO,LOW)
and int n=digitalRead(PIN_NO)
respectively.
Few pins in Digital ports are marked as PWM( like 10 and 11 in figure). They can be used to generate gate pulse of different duty cycle. PWm pin can be programmed to produce perfect square gate pulse of specific duty cycles using analogWrite(PIN_NO,byteValue)
Where byteValue can be betweet 0 to 255 where 255 represts highest or 100% duty cycle. PWM pins can be used to control DC motors precise speed control or controlling intensity of electrical bulbs through MOSFETs/IGBTs and so on.
Arduino has 6 analog read pins (0 to 5) opposite to the digital ports. These are input pins which are connected to 10 bit ADC. Sensors can be directly connected to these pins. Arduino can read the voltage at the pin with intvalue=analogRead(ANALOG_PIN_NO)
The software comes with a Serial library, through which other programs can communicate with Arduino using Serial communication. Arduino IDE also comes with a Serial Monitor through which one can test the serial communication.
For initializing serial communication, in the setup function one needs to initialize the serial communication object with Serial.begin(BAUD_RATE)
Baud Rate varies in the multiples of 96200.Serial.print("msg")
,Serial.println("msg")
, Serial.write(someVariable)
are common functions by means of which the board can write data on the serial port which can be read by any external program capable of communicating with the device over serial port.
int v=Serial.read()
is used to read data from Serial port written by other programs on serial port.
delay(delayInMilli);
is used to make the next instruction wait for delayinMilli period of time which is specified in milliseconds.
Most of the basic hardware Input and output can be performed using above commands.
I request you to please go through My Arduino Getting Started Tutorial more more information about Arduino C programming and Serial Communication basics.
An embedded system may need to drive several loads like motors, trigger relays, provide powers for sensors and so on. Therefore understanding how much power the device draws and how much power it is capable to provide to provide to other peripheral hardware unit is very important aspect of embedded system. In this section we will learn about power management of Arduino.
Arduino's operating voltage is 5v as with most of the embedded system devices and boards. It can be powered up either through a USB or through an External power source. Arduino board has a voltage regulator that can produce 5v regulated supply to the board. External power source's voltage is regulated through this. As with any voltage regulator, the unit needs higher voltage input to produce 5v output. Hence when Arduino is to be powered by external voltage source like battery, it has to be a 9v power supply. Figure 3.1 Shows different ways to power up Arduino board.
Figure 3.1: Different ways of Powering Up Arduino
You can use a 9v Adapter to convert AC to 9V DC directly and give input to Arduino through it's power jack. If you want the device to be completely battery driven, you can use a Connector for 9V battery and can put that in power port. Arduino also provides two pins by label Vin and Gnd which just preceeds the analog ports. You can connect your 9V battery with Arduino using these two pins with the help of battery connecting wires.
However you have a Jumper in the board just near the USB plug which needs to be set to USB if you are using USB to power up Arduino or in Vin if you are using external power. Jumper is shown in figure 3.2.
Figure:3.2 Jumper Setting for Power Selection
When you look at Arduino board straight as in figure 3.1, you can see a set of pins grouped togather which are RST, 3V, 5V, GND, GND, Vin. I call the pins togather as Power Port. The 5v and 3v pins are sometimes also referred to as VCC pins as they are source to other devices. For example if you want to connect a sensor with Arduino ( form example LM 35), it needs 5 v to operate. This voltage is provided by 5v pin. Devices like ZigBee operates at 3V. Such devices can be powered up by 3v VCC pin. Current drawing capability of Vcc pins are 200mA. Arduino also has 14 digital IO pins. When provided with HIGH logic level, these pins produces 5v output. However current drawing capability of digital IO pins are as low as 40mA. Due to very low current drawing capability these pins can not drive any load. Even LED is difficult to drive with this current. Hence digital pins can be used to control other devices only through a switching electronic device like an Optocoupler ( MCT2E) or a transistor (Digital Switching of Devices will be explained later).
It is important to note that digital pins suopports reading voltage just like controlling devices. When a digital switch is connected to digital I/O pins whose's logic level needs to be read by the pins, the pin is said to be acting like a Sink. Care should be taken such that sum of current being sinked to the device through all I/O pins must not exceed 100mA. hence it is always advisable to connect a switch output to digital pin with current limiting resistor.
The maximum current that can be supplied to any pins is about 40mA. So if you connect a 5v-1A power supply to any of the analog pins, even though the voltage is within the range, over current will literally fry your microcontroller. Therefore when you work with Arduino, ample care must be taken to understand the voltage and current specification of the devices and limit input current whenever you use any pins ( analog/digital) as Sink by connecting the source through appropriate current limiting resistor.
From the above discussion we derive following important points:
1) Arduino 5v, 3v Vcc pins can be used directly to drive low current loads( like LED, LCD, 5V DC motors, Sensors)
2) Arduino digital pins are not sufficient to drive even low current loads
3) Arduino digital pins can be used to provide 5V switching voltage to digital switches. Higher current rating devices can be switched by Arduino using a coupler like Optocoupler or Transistor.
4) Arduino pins as Sink has very low current specifications. Therefore high current source must not be connected to any of the pins configured as sink. Use current limiting resistor with the pins as Sink.
With this knowledge we are literally ready to move ahead with our Arduino development.
Often in your DIY projects you need indicators. Say for instance when you build a fire alarm system, you sensor may monitor heat and light intensity and when the value exceeds threshold value, you want it to trigger an alarm.
You may also want to indicate that a specific device is active through a LED. LEDs and Buzzers are most common indicators that are part of almost all DIY projects. Because of the ease of use, cost effectiveness, hardware developers are fond of these two components.
Switches plays an important role for triggering an external event for the device. For example you want a motor to start: press a switch, let the board read the event and turn the motor on. You want to turn on a light by pressing a switch: use simple switches.
So indicators and switches are most basic, common and most widely used components with any hardware projects. They are cheap, they are efficient and they are effective. Hence in this section we will discuss about using using LEDs and Switches with Arduino.
Light Emitting Diode or LED's are most common indicators for any electronic devices from an adapter to laptop. It makes it visible for the user that certain part of the system is functioning well. LEDs are available in different colors and current specification. Current specification of LEDs varies from 30mA to several amperes. Because LEDs draws current, it is also treated as current load. LEDs can operate between 1.2V to about 24v depending upon it's specification.
Arduino board has a built in LED which can be controlled by Pin 13 of Digital pins. In order to control any device through Arduino digital IO pins, we must configure the pin as OUTPUT pin and make it high using digitalWrite(13,HIGH).
Simple Sketch for blinking can be found in Arduino example: File->Examples->Basics->Blink. For continuity of the discussion, I am simply dumping the code here.
int led = 13;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(led, HIGH); delay(1000); digitalWrite(led, LOW); delay(1000); }
This will make your LED associated with pin 13 switching on and off in turns in every 1 sec. Turned on state of the LED can be seen in figure 4.1.
Figure 4.1: LED Connected to Pin 13
The Onboard LED is fine, it needs no circuit connections. But what about connecting an external LED and controlling it with digital pins. As digital pins may not provide enough current for LED, we need the LED to be drawing current from a source which can supply enough supply. So we will connect the Anode of the LED ( the longer leg) with Vcc 5v of Arduino. But if we connect the cathod ( smaller leg) directly to ground, firstly the we can not control the LED as we can not control Vcc pin. So we connect LED's cathod to Emittor of an NPN transistor ( I have used BC 548, you can use any other transistor of NPN type). Transistor's collector is grounded. Though there is no resistor with LED in 4.2 a), I advise you to connect the LED with BC548 with a 100Ohm resistor. It limits the current and prevents the LED being fried up.
Transistor's base is connected to any of Arduino's digital i/o pin ( say pin 12) through a bais resistor R2(100/470 ohm). When the pin is HIGH, transistor gets base voltage which completes transistor circuit and LED is grounded through the transistor. When the pin is LOW, transistor does not get forward bais voltage so is turned off. Thus LED's ground pin is not connected to LED. Hence it is turned off.
You can actually take a 3 pin connector, put the transistor in it and connect with it's wires. You can also make the connection in breadboard if you so wish!
You can now use the code listing of 4.1 to perform the experiement. Just change Pin 13 to pin 12. Alternatively you can also add pin 12 as digital output pin and control external LED with on board LED. 4.2 b) Shows glowing of LED.
C) Thransistor BC 548/547 Pin Out
Figure 4.2: Connecting External LED With Arduino
For your convenience, I have also put up an independent image showing exactly this in 4.3.
Figure 4.3: Closer Look At The Connection
Just like LED, Buzzer is also an output component. There are many different types of buzzer out of which Pizeo electric buzzers are most common. But unlike LEDs buzzer's current requirement is very low. It can operate in current as low as 10mA. Therefore we can connect the buzzer directly with a digital pin and Arduino's ground.
You can connect the buzzer with Pin 8 ( Try to avoid a pin which is marked as PWM) and done. Use the code listing of 4.1 to turn on and off the buzzer in alternative seconds. Do not forget to change the pin number to the buzzer pin you have connected the buzzer with.
Buzzer will either come with two wires or two pins. If the buzzer has two pins, the longer leg is anode and must be connected to the digital pin and the shorter leg is cathod which must be connected to ground.
If the buzzer has wires ( as in figure 4.4) then RED wire is positive and blue/black wire is ground. Figure 4.4 Shows the Buzzer Connection with Arduino.
Figure 4.4 Arduino With Buzzer
Needless to say that there are several Switches available. The one we would experiement with is a Push button or Push Switch. It remains on till you push the button and becomes off when you leave it. You would switch on a LED with push button click.
Push switches have four legs, which provides two pair f switching poles. Figure 4.5 b) shows how the pins are paired. So while switchin a single device with a switch ( which we generally will do), select either pair A with B or C with D. Note A , C and B,D are interchangable.
Circuit diagram of the Switch with LED is shown in Figure 4.5 A). LED is given positive voltage through Arduino 5v through a resistor. The cathod is connected to one pole of the switch and another pole of the same pair is connected to ground. So when switch is pushed, LED's circuit is complete and it glows. When switch is released, LED's circuit is broken and it is turned off.
We do not need any coding for this experiement. The result can be seen from figure 4.6.
C) Physical Connection
4.5 Switch With Arduino
4.6 Result of Switch Experiement
LCD's are most common output devices for embedded system. From Beverage Vending machine to handheld ticket printer to hotel billing system, you see the display with many embedded system. There are several displays which are commonly used. Most common displays are: LCD Displays, Graphic Displays, Seven Segment Displays and many more. Duel Line LCD displays are most common device that is used with embedded system. That is because embedded system functionalities are generally restricted. So 2 Line display is sufficient to display most of the things.
Here I am going to show you how to work with display in Arduino. LCD is a 16 pin device which operates at 5V. Arduino's 5V Vcc is sufficient to power LCDs. However LCDs don't come with pin headers which makes it difficult to work without Soldering.
However we have a way out for every such problem. Look at figure 5.1 c). This is a standard Multi pin Connector. 8-Multi pin Connectors are available in themarket for about $.5-$1. You can get two 8-pin connectors and put the male pins in the LCD and the respective female socket's pre soldered wires go to Arduino pin.
LCD's needs two VCCs: One for lighting up front characters and another one is for backlight which is optional. Figure 5.1 A) Shows the Connection Table. LCD pins 11,12,13,14 are the data pins which should be connected to Arduino's digital I/Os. RW' should be grounded for enabling the write operation. Enable and RS are two control pins.
Therefore from Arduino, we just need to control 6 pins. VO controls the brightness. You might want to vary it depending upon environment light. So connect it with a 10K variable resistor called pot to ground. POT's first and last pin must be connected to 5 v and ground respectively. The middle one goes to VO pin of LCD.
(Click on the Image to see Full Size Image)
C) Multi Pin Connector
Figure 5.1: Connecting LCD With Arduino
Once connection is done, we can take the help of LiquidCrystal library of Arduino to print in the LCD.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
void setup()
{
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
lcd.clear(); lcd.begin(16,2); }
void loop() {
lcd.print("Codeproject.com");
lcd.setCursor(0,1);
lcd.print("Rupam, Gulbarga"); delay(2000);
lcd.clear(); lcd.home(); }
LiquidCrystal lcd(12,11,5,4,3,2);
is most important here. lcd
is a variable of LiquidCrystal
class which is initialized with (RS,ENABLE,D4,D3,D2,D1)
. Where all all the values are respective Arduino Pin Numbers and not LCD pin numbers.
lcd.begin(NO_OF_CHARACTERS,NO_OF_LINES)
initialize the lcd for printing NO_OF_LINES
and NO_OF_CHARACTERS
par line. lcd.home()
takes the cursor to first character of first line. lcd.print()
can print characters starting from a position where the cursor is currently in.
lcd.clear()
clears all data from LCD. lcd.setCursor(CHARACTER_NO,LINE_NUMBER)
takes the cursor to particular LINE_NUMBER
and CHARECTER_NO
of that specific Line.
Figure 5.2 Shows the output of above listing with Circuit diagram specified in 5.2 A). You are free to change the pins. But do not forget to change lcd initialization accordingly.
Figure 5.2: Physical World Connection And Output
Sensors are small electronic devices that can convert physical parameters to electrical parameters. There are wide range of sensors for measuring environment parameters like Humidity, Temperature, Moisture, Co2 and many more. Figure 6.1 Shows different sensors that might be used with Arduino.
Sensors generally have a operating voltage and current range. Most of the common sensors operates at input 5v and requires medium range current. Which means that sensors can be supplied with voltage directly from Arduino's 5V Vcc pin.
Sensors produces electrical output which is in the range of operating voltage. Arduino can read this voltage through it's Analog pins and there are 6 analog pins grouped togather as right most port at the bottom. The operating voltage range of these pins are 5V and operating current is about 100mA. One of the important thing you must know is that if you do not connect any sensors to any of the analog pins, the pins would still not read zero as expected. That is because they tend to pick up environmental charge.Thus in open state, reading the pins will return random low voltage.
As operating voltage is 5v, most of the sensors works with 5v. However as electrical parameters are analog ( continues) in nature, so is the sensor output.
But Microcontrollers care capable of processing only digital data. Therefore Arduino provides a on board A/D ( Analog to Digital Converter) of 10 bits. A/D converter works with the logic of sampling and quantization. It samples the signal with number of bits equal to A/D bits. Then quantize the input signal to nearest sample value.
You can read this Wiki on A/D converter for a better understanding of the concept.
The meaning is that Max voltage i.e. 5V can be represented by 2^10 i.e. 1024. So if the value returned by say analogRead(5) is x, then actual voltage =
Sensor output Voltage=x*5/1024
Further output voltage of sensor will be associated with some value of physical parameters. For example temperature sensor LM35 which we will shortly see produces output voltage in the range of 0-1.1V for temperature from 0-92'C respectively. Thus 1.1/92 ( or about .1v) represents 1 unit of temperature. This is also called sensor precision.
As sensors output voltage or current according to the physical parameter it is monitoring, they are also called sources and Arduino ( or any other device reading the sensor data) is called a sink. When many sensors are connected through wireless technique and many sinks are network togather with a common objective ( for instance measuring average temperature of an area) it is called Wireless Sensor Network or WSN.
Figure 6.1: Different Sensors
I have already provided the details about temperature and light sensor in my Live Weather Station with Arduino's tutorial. However I am writing this particular article for absolute beginners. Therefore this and next subsection will be based on the concepts presented in the aforementioned tutorial. There will be no change in the connections. However we will differ in code. In this particular tutorial I will not be using ArdOS the way I did it in the previous tutorial.
We will begin with configuring our hardware and testing it first. We would follow it by integrating the setup with Internet f Things.
We will begin with Temperature sensor LM 35. This is possibly one of the cheapest and effective sensors to kick start with your Arduino DIY. It is a three pin sensor which operates between 0-5V range and used for measuing temperature in the range of 0-92'c.
If you are a hardware beginner and just starting to learn your hardware then it is always a good idea to study the data sheet of the components before working with them. It gives you electrical and logical understanding essential for working with those devices.
You can download LM35 Datasheet from here.
LM35 has three pins, which are to be connected to Ground, Vcc and Analog pin of Arduino. You can provide it power directly from Arduino 5V pin and connect the output pin to any of the analog pins. I have connected it to pin 5. See figure 2.1 to understand the circuit.
Figure 6.2: LM 35 Connection With Arduino
You might wonder how to connect those three pins to Arduino.Plenty of tutorial will suggest you to use bread board. So you can either use bread board or use three pin connector. I prefer short three pin connector as shown in figure 2.2. So you insert the LM35 pins into the three slots of the connector and insert the wires into respective Arduino slots.
Figure 6.3: Connecting LM 35 using 3-Pin Connector
Now before we code LM 35, a little understanding of Concept isn important.
LM35 Converts temperature to voltage of range 1V. That means When Temperature is about 90'c, output voltage of LM35 will be about 1V. Now how Arduino reads this temperature?
As you have noticed the output voltage of LM35 is connected with Arduino's Analog pin 5, Arduino will read the analog voltage which will be converted to digital value through internal 10 bit ADC. 10Bit ADC means that Arduino reads 1024 (2^10) when voltage is 5 volt. But as output of LM35 will never exceed 1V, 4Vs or about 10% of the precision is lost. This can be overcome simply by changing the reference voltage from 5V to 1.1V. This can be achived using following simple code.
Collapse |
Copy Code
analogReference(INTERNAL);
However, if you use 1.1V as aRef, the equation changes entirely. If you divide 1.1V over 1024, each step up in the analog reading is equal to approximately 0.001074V = 1.0742 mV. If 10mV is equal to 1 degree Celcius, 10 / 1.0742 = ~9.31. So, for every change of 9.31 in the analog reading, there is one degree of temperature change.
Therefore,
Temperature value= Value_Read_By_Pin_5/9.31 with 1.1 reference voltage. Let us write a simple program to probe the temperature once in every Second.
Here goes our code for the same:
float tempC;
int reading;
int tempPin = 0;
void setup()
{
analogReference(INTERNAL);
Serial.begin(9600);
}
void loop()
{
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.print("Temp= ");
Serial.print(tempC);
Serial.println(" 'C");
delay(1000);
}
Bellow is the screenshot of the LM35 roperation. You can observe increase of the Temperature when I bring an Incense stick near to the sensor.
Figure 6.4: LM 35 Serial Output
6.4 LDR Sensor
LDR stands for Light Dependent resistor. As light increases on the surface of LDR, it's resistance increases, resulting in low voltage accross it. As Light reduces, resistance also reduces resulting in high voltage output accross it. Therefore if we connect LDR as one of the resistors in a voltage divider circuit, then voltage accross divider will vary as we vary light intensity. Figure 2.4 shows the Arduino connectivity of the LDR as well as the principle of voltage divider circuit.
Figure 6.5: LDR Sensor Circuit Diagram
As R2=1K/4.7k constant, Vout will decrease if R1 decreases which is when light intensity is low and Vout increase when R1 is high which is when light is higher.
Therefore the logic in Arduino should follow the principle that analog pin value is directly proportional to light intensity value. We can represent the Light intensity as percentage of maximum intensity as follows:
Light_Intensity_In_Percentage= (Analog_Value)*100/1024
Let us see the sketch to to test Light Intensity variation detection in terms of Percentage using the LDR circuit.
float light;
int reading;
int lightPin = 5;
void setup()
{
Serial.begin(9600);
}
void loop()
{
reading = analogRead(lightPin);
light = (float)reading*100/1024.0;
Serial.print("Light = ");
Serial.print(light);
Serial.println(" %");
Serial.println(reading);
delay(1000);
}
The output can be seen in figure 6.6.
Figure 6.6: LDR Sensor Result
Metal sensors are inductive sensors. Which means that it induces current when metal is brought nearer to it. Here we will see the working principle of ID18-3008NA metal sensors which also acts like a switch. Therefore these sensors are also referred to as Proximity Switch. You can get yourself a metal sensor for about $3.5. Here 18 stands for maximum operating voltage, N stands for NPN type. You also have PNP type switch available. Recall in Section 4.1.2 we have already seen the functionality of a NPN switch. Figure 6.7 A and B shows the proximity sensor.
Figure 6.7: Arduino With Metal Proximity Sensor
Metal proximity sensor will have three color wires: Blue should be grounded, brwon is +vcc which should be given to Arduino +5v Vcc. When you take metal nearer to the Sensor, it induces more current which results in higher voltage. So you can print the voltage coming from analog pin in Serial port and then make a threshold to determine if metal is detected or not.
Here is the simple Code listing for metal sensor which I have connected to Analog Pin 3.
float metal;
int reading;
int metalPin = 3;
void setup()
{
Serial.begin(9600);
}
void loop()
{
reading = analogRead(metalPin);
metal = (float)reading*100/1024.0;
Serial.print("Metal in Proximity = ");
Serial.print(metal);
Serial.println(" %");
if(reading>250)
Serial.println("Metal Detected");
delay(1000);
}
Generally Iron/Copper or metal with good magnetic properties will induce more than 1V when brought nearer to the metal sensor.( You need not touch the surface. It can start detecting from a distance of about 3CM.
Few months back I had done a cool model called Automated Mining. You can check out this Video to understand in detail as how metal sensor works:
Metal Sensor Application Video
Ultrasound is a technique of measuring distance from objects/obstacles. It contains a transmitter and a receiver. Transmitter transmits a short Ultrasound pulse periodically. If there is an object in front, the pulse hit the object can comes back. Receiver then measures the round trip time and can estimate the distance based on the round trip time.
The reason for covering Ultrasonic sensor is a) It is one of the most commonly used sensors with DIY robots and b) It works on the principle of measuring pulse round trip time rather than voltage at an analog pin.
Also Ultrasonic works with pulses. Therefore detecting the pulse needs PWM pin. So Ultrasonic sensor's output is connected to a PWM pin rather than an analog Pin.
Figure 6.8 Gives the circuit diagram of Ultrasonic sensor. All you have to do is connect Vcc and Gnd of Ultrasonic device to that of Arduino. Trigger is connected to any non PWM pin and Echo is connected to any of the PWM pin.
Figure 6.8: Ultrasonic Sensor Circuit Diagram
In order to accurately calculate round trip pulse timing, we need a library called NewPing. Download NewPing from Google Code.
Add the library by Selecting the Zip file through Sketch->Import Library-> Add Library In your Arduino IDE.
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(13,OUTPUT);
Serial.begin(19200); }
void loop() {
delay(50);
unsigned int uS = sonar.ping();
Serial.print("Ping: ");
unsigned int dist=uS / US_ROUNDTRIP_CM;
if(dist<5 && dist>0)
{
digitalWrite(13,HIGH);
}
else
{
digitalWrite(13,LOW);
}
Serial.print(dist);
Serial.println("cm");
}
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
will initialize an Object of NewPing
with Echo, Trigger
pin and maximum distance the pulse is expected to travel.
sonar.Ping()
will genrate a pulse and measure the time when it reads back the same pulse after the pulse is hit an object. If no object is in front, pulse never gets back and it returns 0.
Distance is calculated by dividing the time with unit time taken for pulse to travel 1CM distance. We print the distance with Serial Command and glow the LED high when the Object comes about 5CM distance from the sensor.
Pulse Width Modulation or PWM is one of the most important techniques for Speed and Intensity control of the devices. Every electronic and electrical load like bulbs, LEDs, Motors depends upon the current flow through them. Current can be controlled by changing the amplitude of voltage. Of of the ways to do it is using variable resistors or pots. But the fact is Pot can not be controlled by microcontrollers. Hence controlling the current flow through devices is really difficult.
Current can be controlled by another means. Rather than changing the voltage amplitude, amount of time voltage is applied to load can be controlled. PWM is the principle of controlling current through loads by controlling the period for which voltage is supplied to it ( commonly known as duty cycle).
As the name suggests, pulse width modulation is all about varying the ON period of the pulse. Consider the following code snippet
float freq=1000;double T;
int onDelayUs,offDelayUs;
float dutyCycle=10;void setup()
{
pinMode(13, OUTPUT);
T=1*1000000/freq; onDelayUs=T*dutyCycle/100; offDelayUs=T*(100-dutyCycle)/100;}
void loop()
{
digitalWrite(13, HIGH);
delayMicroseconds(onDelayUs); digitalWrite(13, LOW);
delayMicroseconds(offDelayUs);
}
The above code is very simple which turns pin 13 LED HIGH for every onDelayUs period after every offDelayUs period. So basically you are producing a pulse at pin 13 for specific duty cycle. Figure 7.2 Shows the waveform for various duty cycles.
Now when you connect circuit of section 4.1.2 and provide connect transistor's base with a resistor to pin 13, Transistor will be switching on only for the period onDelayUs, load current will start increasing, then transistor will be off, stopping the voltage to the load which results in reduction in the load current. But before load current becomes 0, again transistor will be ON, increasing the current. Thus current can be varied depending upon how much time transistor is on which in turn depends upon the duty cycle.
However this techniques has few drawback. First is that switching time of digital I/O pins are very slow, so we do not get exact square pulse. Secondly such pins are effected by interrupt. Hence in order to work with the above listing, one must also disable all interrupts for Arduino. This method also introduces jitter to the load because of above faults.
To overcome this problem of using digital IO pins to produce PWM, Arduino offers a great PWM support through ATMEGX microcontroller's internal timers.
See figure 7.1 A). Several Arduino pins among digital IO pins like pin 11 can provide PWM support. PWM signal of particular duty cycle can be produced through any of these pins by using analogWrite(pin, value); command.
Yes, you read it write. We use analogWrite() for digital pins for producing PWM signal as PWM is a continues signal ( on and off togather).
analogWrite() expects the value field to be between 0-255. Where 255 represents 100% duty cycle. A Desired duty cycle value can be calculated simply by
Analog_Write_Value=100.0*dutyCycle/256.0;
The output frequency is the 16MHz system clock frequency, divided by the prescaler value (64).
Figure 7.1 A, B shows the circuit diagram and physical connection respectively for testing intensity control of LED through PWM. Here pin 11 PWM pin is used to produce PWM.
Figure 7.1 Controlling Light Intensity With PWM
Figure 7.2 PWM Waveform
Here is the Simple Listing to test the circuit.
int ledPin = 11; // LED connected to digital pin 9
void setup() {
}
int fadeValue=255;
void loop() {
analogWrite(ledPin, fadeValue);
fadeValue=fadeValue-5;
if(fadeValue<0)
fadeValue=255;
delay(500);
}
The above listing keeps on dimming LED in every 500mS from brightest of off state and repeats the operation. Figure 7.3 Shows the output of the above listing and circuit.
Figure 7.3: Changing LED Intensity using PWM
We have so far seen controlling the intensity of digital devices which more or less operates at low voltage/current range. What if we want to operate in high current range? What if we want our Arduino to control switching of an Electrical Bulb? What if we want Arduino to control polarity of motor? Surely in such cases load can not be grounded through a transistor as current rating of the transistor is low and current direction can not be reversed.
The most common, effective and widely used solutions are relays. These are beast of a component. If you are to become a proficient hardware programmer, you absolutely have to master the art of understanding and working with relays.
Relays are Electro-Mechanical switches which can select between different input lines through a connector by attracting or repelling it through magnetic property of a coil electromagnet.
I would encourage you to read this wiki entry for Relays.
As you see there are several types of relays which are mainly categorized into SPST( Single Pole, Single throw), SPDT ( Single Pole, Double Throw), DPDT ( Double pole double throw). Throw refers to as input lines and pole refers to as output. So SPDT relay can select any of the two input as it's output.
Figure 8.1 B shows a typical SPDT relay. This has 5 pins. The center top pin is the pole pin or output. The bottom two pins are the input lines which relay select. One of the input is connected when relay is off and is called Normally Connected 9 NC) the other is selected when relay is activated called Normally Off or NO. Top left and right pins are +Vcc and gnd pins respectively. +Vcc voltage depends upon relay's operating voltage. Different specification relays are available: 5V,6V,9V,12V,18V, and 24v Relays are common SPDT relay types. Note here that this voltage is the voltage for switching on relay. NO and NC voltages can be several order higher or even AC voltages. Figure 8.1 Shows a typical SPDT relay, it's pin out, and internal schematic.
Figure 8.1: Relay Connection Principle, Schematic and Pinout
Lowest voltage relay i.e. 5V relay needs about 200mA current at 5V. So it is quite easy for us to know that the digital pins can not drive the relay directly. Then? Well, we need to treat the relay itself as a load. Now our problem is solved. We can connect relay's Vs with +Vcc and Gnd to Collector of a NPN transistor like BC548. When we supply base current to transistor through one of the digital pins, transistor completes relay's ground circuit through it's emittor as show in figure 8.3. However Transistors are generally effected by reverse current. As relay's switching mechanism depends upon magnatism in a coil, when it drives a load, chances of load current inducing back EMF is higher. Therefore, in working with transistor, relays have a flyback diade connected accross it whose role is to ground reverse emf.
Another drawback of transistor driven relay circuit is, when you work with PCB's if a transistor is burnt due to over current, it is quite a task to replace it from the PCB with another transistor. Hence we use another mechanism. We couple the relay's Vs with Vcc with a chip called Optocupler.
One of the cheap and most available optocoupler is MCT2E. Inside the chip, Optocupoler has a photo transmitter in the input side which can operate at a very low current and therefore can be triggered directly by an Arduino Digital pin. At the output side the chip has a photo transistor which gets base current soon as internal photo diade starts emitting light. The transistor is of NPN type. Therefore soon as it is switched on, it can produce the same voltage applied to it's collector at pin 6 to pin 4. As there is no connection between input and output side, this chip is not affected by any reverse current. This concept is also called optical isolation. Datasheet of MCT2E says that it is capable of an opto-isolation of about 1800v.
So optocoupler's pin 1 is connected to Arduino's digital pin, it's pin 5 is connected to +Vcc of Relay( for a 12V relay, pin 5 is connected to 12V source and 9V relay, it is connected to 9v). Pin 4 which is the output pin of the optocoupler is connected with the VS pin of relay. Ground of Relay, Optocoupler ( pin 2), the voltage source ( +Vcc) and Arduino are made common. This is very very important while working with any hardware project. If you forget to connect the grounds of all these devices togather, then your relay will not trigger.
Figure 8.2: Relay With Load Connection with Arduino
Figure 8.3: Connecting Relay With Transistor
If you are unwilling to work with independent setup of relays, you can also purchase 5V Relay break out boards, which you might get for about $3. But tell you the fact, if you mount your own relay units, it would cost you about $.5 :) Figure 8.4 Shows a typical 5V relay break out board. With three pin connectors which are input Vcc, Sig,Gnd respectively. Here Sig is Vs.
Output side consists of three female slot pins with screw support. NO and NC are pins where input voltage will be provided and Pole is the output. The realy also has an inbuilt LED that goes high when relay is active.
As relay is 5V, we need to connect Vcc with Arduino Vcc, Gnd with Arduino Ground and Sig with any of the digital i/o pins. At this moment, we want to test the switching of relay. So no need to connect Pole, NO and NC.
Figure 8.4: 5V Relay Breakout Board
Use the Blink Code of Section 4.1.1 to test the Relay switching. You will see relay is switching on and off at every second, with a sweet "click" sound, glowing and turning off the associated LED. See as pin 13 is going HIGH, relay is also switched on.
Figure 8.5: Relay Output with Blinking Sketch
Motors and Actuators are most important devices if you want to build your own robot. DC motors are important category of motors. Several types of DC motors are used in DIY project, for example Brushless DC motors, Geared Motors and so on. This wiki article on DC motor is a wonderful articel to get started with motors.
In this article we are concerned with controlling DC motor. You can get yourself a 6V/9V/12V motor. You can also get one out from your old CD/DVD drives. Motors are also load and therefore can be switched the same way that of Relays/LEDs. Just like relays motors are prone to inducing back emf. Therefore we must connect a flyback diode accross the motor just like relays. Figure 8.1 Shows the circuit of a typical motor switching. Vcc depends upon motors voltage rating.
If you want to control the speed of the motor, you can connect transistor to PWM pin and use the listing of PWM section to control it's speed. Else if the purpose is to only switch it on and off, use connect transistor base with a normal digital io pin like pin 13 and use the listing of 4.1.2 to check switching on and off of motors at every second.
Figure 9.1: Controlling DC Motor With Arduino Using Transistor
Figure 9.2: DC Motor Speed Control With PWM
Remember that Relay switching time is multifold times slower than that of digital circuit's switching. Therefore relays can not be used for speed control of the motors. They are mainly used for switching On and Off of Motors. One of the advantage of relay is that you can provide +Vcc, -Vcc to NC and NO of a relay whose output can be connected to another relay's NO. Now by controling both the relays you can actually rotate the motor in either direction.
Connecting motor with relay is simple and does not require any diode accross the motor as that is taken care by flyback diode accross relay.
Figure 9.3 Shows the circuit diagram of 5V relay whose actual connection is shown in figure 9.4. I have used a 9V battery as Vcc. You can also use 9V/12V adapters.
Figure 9.3: Circuit Diagram of Motor Switching Using Relay
Figure 9.4: Physical Connection of Motor Switching With Relay
You can test the circuit with the same blinking Listing of 4.1.2
Arduino is a fantastic solution for virtually anything you want to do with hardware. Wireless is no exception. Bluetooth modules are now available for Arduino which works nicely. You can use RF with Arduino. But one of the coolest support is that of IR.
Though IR( Infrared) is actually a sensor and should have covered in Sensor category, but as it is most widely used for remote controlling devices, I would be covering this as a separate topic under wireless.
IR receivers are available from different vendors and unlike other sensors, do not have any standard pin out. You can order an IR sensor for under $1. However make sure that you know the pin out of the sensor you order. It is very important as I personally have seen IR sensors of all sorts and pin out.
However most common IR sensors would looking like figure 10.1 with Gnd, Vcc and O/P pin. O/P must be connected with any of PWM pin. IR also works like that of Ultrasonic sensor. The receiver can detect IR pulses modulated at 38KHz.
You can use any home remote control ( TV/ AC) to generate signal.
Figure 10.1: Arduino With IR Receiver
Decoding the signal requires a special library. Download IRemote Library from GitHub. Add the library to your Arduino IDE. The library comes with a cool IRcvDemo, Save it as a different name and upload the sketch to Arduino. I have added a little more tweek to the code. You can turn on and off of pin 13 LED with the code
#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
irrecv.enableIRIn(); }
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
switch(results.value)
{
case 0x1111:
digitalWrite(13,HIGH);
Serial.println("LED ON");
break;
case 0x2222:
digitalWrite(13,LOW);
Serial.println("LED OFF");
break;
}
irrecv.resume(); }
}
This has just one problem. Every remote/company follow a different IR protocol. In other words, the hex value associated with button press will be different. So what you can do is test your IR, read the code of any two bottons and replace 0x1111 and 0x2222 with that code.
SerialMonitor's dump is shown in figure 10.2 and the actual result is shown in figure 10.3.
Figure 10.2: SerialMonitor screenshot of Working With IR Receiver
Figure 10.3: LED on and Off through IR Receiver
Observe the sign in remote and green LED on baord! You can see that the LED is turned on and off by alternative press of the ON/OFF button.
There are so many hardware components and devices that plays an important role in DIY/Production embedded projects. There are so many sensors and motors that no tutorial in the world can cover all of them in a single tutorial. However there are some basic stuff that a DIY guy must know. Some basics of Voltage and current, some basic sensors and actuators. Some ways of displays. I have tried to cover most important, low cost hardware that are necessory for DIY projects. I have listed independent codes. I have focussed mainly on Hardware part in this tutorial. You can also check out my ArdOS tutorial where I have provided detail description of Working with ArdOS with Arduino.
gasshopper.iics is a group of like minded programmers and learners in codeproject. The basic objective is to keep in touch and be notified while a member contributes an article, to check out with technology and share what we know. We are the "students" of codeproject.
This group is managed by Rupam Das, an active author here. Other Notable members include Ranjan who extends his helping hands to invaluable number of authors in their articles and writes some great articles himself.
Rupam Das is mentor of Grasshopper Network,founder and CEO of Integrated Ideas Consultancy Services, a research consultancy firm in India. He has been part of projects in several technologies including Matlab, C#, Android, OpenCV, Drupal, Omnet++, legacy C, vb, gcc, NS-2, Arduino, Raspberry-PI. Off late he has made peace with the fact that he loves C# more than anything else but is still struck in legacy style of coding.
Rupam loves algorithm and prefers Image processing, Artificial Intelligence and Bio-medical Engineering over other technologies.
He is frustrated with his poor writing and "grammer" skills but happy that coding polishes these frustrations.