Вы находитесь на странице: 1из 159

Embedded Systems

A combination of hardware and software which


together form a component of a larger machine.

Computing systems embedded within electronic


devices.

Billions of units produced yearly, versus millions of


desktop units

An embedded system is designed to run on its own


without human intervention, and may be required to
respond to events in real time.
Introduction to Embedded Systems
Application Areas
Televisions and Stereos
Remote controls
Phones / Mobile phones
Refrigerators
Microwave Ovens
Washing machines
Watches
Alarm clocks
Electronic musical instruments
Electronic toys
Medical equipment
PDAs
Consumer Products
Application Areas
Medical Systems
pace maker, patient monitoring systems, injection systems, intensive
care units,
Office Equipment
printer, copier, fax,
Tools
Multimeter, Oscilloscopes, Line Tester, GPS,
Banking
ATMs, Statement printers,
Transportation
(Planes/Trains/Automobiles and Boats)
Radars, Traffic lights, Signaling Systems
Agriculture
feeding systems, milking systems
Application Areas
Automobiles
engine management, trip computer, cruise
control, immobilizer, car alarm.
airbag, ABS, ESP
Building Systems
elevator, heater, air conditioning, lighting, key card
entries, locks, alarm systems
Space
satellites
Embedding System example Digital Camera
Digital camera chip

CCD

CCD preprocessor Pixel coprocessor D2A


A2D

lens

JPEG codec Microcontroller Multiplier/Accum

DMA controller Display ctrl

Memory controller ISA bus interface UART LCD ctrl


Microcontrollers
Microcontrollers
Microprocessor
CPU (on single chip)
Microcontroller
CPU + Timers + I/O (+RAM) (+ROM)
Reduced chip count for board design
Embedded system

Upgraded Technology
Surface Mount Device (SMD)
Ball Grid Array (BGA)
Microcontrollers
Microcontrollers can be used to build projects directly,
but often packaged with other components onto a PCB
to make them easier to use for beginners and for rapid
prototyping.

These boards are I/O boards

They get data in and out of a microcontroller. They are


also called microcontroller modules.

Microchip PIC and Atmel AVR are two popular families


of microcontrollers.
Memory Chips- ROM
Memory Chips-RAM
Address
Input & Output
Required to communicate with outside world
PC System:
Keyboard
Monitor
Parallel port (printer port)
Serial port + USB
Embedded System:
Sensors (e.g. in automobile: acceleration sensor, seat
sensor)
Actuators (e.g. in automobile: valves for airbags)
Input & Output

Input / output device implementation


can be:
Memory-mapped
I/O mapped (ports)
DMA (direct memory access)
Classification of Microcontrollers
They are three informal Microcontroller groups
Bare microcontrollers,
Programmable I/O boards &
Tethered I/O boards
Bare microcontrollers - are the most flexible but
most difficult to work.
Microchip PIC and Atmel AVR are two popular
families of microcontrollers
Classification of Microcontrollers
Programmable I/O boards It is a microcontroller on
a PCB with other components to make it easier to
program, attach/detach components, and turn on
and off.
They have components to regulate power to protect
the microcontroller and a USB or RS-232 serial port
connector to make it easy to attach cables for
communication.
Small reset switches make it easy to restart the
power without having to physically detach the power
supply or battery.
Classification of Microcontrollers
Tethered I/O board - used to get sensor data into
a computer and to control physical devices
(motors, lights, etc.) without the need to program
the board.
Tethered I/O boards provide a way to
communicate between more exotic input devices
such as light sensors and video cameras, and
output devices such as servomotors and lights.
Messages are sent and received from the boards
through software such as Processing, Max, Flash,
and many programming languages.
This ease of use often comes at a high price.
Microprocessors
It is a general purpose computer.
Memory, I/O ports, timers, interrupts are not
available inside the chip
Systems become bulkier and expensive.
Very few pins are programmable
Widely used in modern PCs and Laptops
INTEL 8086, INTEL Pentium series
Microprocessor
Microcontroller

INTEL 8051, 89960, PIC16F877


Basics of Design
Design goal:
Construct an implementation with desired
functionality
Key design challenge:
Simultaneously optimize numerous design metrics
Design metric
A measurable feature of a systems
implementation
Optimizing design metrics is a key challenge
Optimizing Design Metrics
Common metrics
Unit cost: the monetary cost of manufacturing
each copy of the system, excluding NRE cost
NRE cost (Non-Recurring Engineering cost): The
one-time monetary cost of designing the system
Size: the physical space required by the system
Performance: the execution time or throughput of
the system
Power: the amount of power consumed by the
system
Flexibility: the ability to change the functionality
of the system without incurring heavy NRE cost
Optimizing Design Metrics cont
Common metrics
Time-to-prototype: the time needed to build a
working version of the system
Time-to-market: the time required to develop a
system to the point that it can be released and
sold to customers
Maintainability: the ability to modify the system
after its initial release
Correctness, safety and
Design Metrics
Expertise with both software and hardware is needed to
optimize design metrics
Not just a hardware or software expert, as is common
A designer must be comfortable with various technologies in order to
choose the best for a given application and constraints.

Power

Performance Size

NRE cost
Design Metrics
Time required to develop a product to the point it can be sold
to customers
Market window
Period during which the product would have highest sales
Average time-to-market constraint is about 8 months
Delays can be costly
Revenues ($)

Time (months)
Revenue Models
Simplified revenue model
Product life = 2W, peak at W
Time of market entry defines a triangle, representing market
penetration
Triangle area equals revenue
Loss
The difference between the on-time and delayed triangle areas

Peak revenue

Peak revenue from


Revenues ($)

delayed entry
On-time
Market rise Market fall

Delayed

D W 2W
On-time Delayed Time
entry entry
Losses due to delayed market entry
Area = 1/2 * base * height
On-time = 1/2 * 2W * W
Delayed = 1/2 * (W-D+W)*(W-D)
Percentage revenue loss = (D(3W-D)/2W2)*100%
Lifetime 2W=52 wks, delay D=4 wks
(4*(3*26 4)/2*26^2) = 22%
Lifetime 2W=52 wks, delay D=10 wks
(10*(3*26 10)/2*26^2) = 50%
Delays are costly! Peak revenue

Revenues ($) Peak revenue from


delayed entry
On-time
Market rise Market fall

Delayed

D W 2W
On-time Delayed Time
entry entry
NRE(Non Recurring Engineering costs)
Costs:
Unit cost: the monetary cost of manufacturing each copy of the system,
excluding NRE cost
NRE cost (Non-Recurring Engineering cost): The one-time monetary cost of
designing the system
total cost = NRE cost + unit cost * # of units
per-product cost = total cost / # of units
= (NRE cost / # of units) + unit cost
Example
NRE=$2000, unit=$100
For 10 units
total cost = $2000 + 10*$100 = $3000
per-product cost = $2000/10 + $100 = $300

Amortizing NRE cost over the units results in an additional


$200 per unit
NRE and unit cost metrics
Compare technologies by costs
-- best depends on quantity
Technology A: NRE=$2,000, unit=$100
Technology B: NRE=$30,000, unit=$30
Technology C: NRE=$100,000, unit=$2
$200,000 $200
A A
B B
$160,000 $160
C C
to ta l c o st (x1000)

p e r p ro d uc t c o st
$120,000 $120

$80,000 $80

$40,000 $40

$0 $0
0 800 1600 2400 0 800 1600 2400
Number of units (volume) Number of units (volume)
Performance design
Widely-used measure of system, widely-abused
frequency, instructions per second not good measures
Digital camera example a user cares about how fast it
processes images, not clock speed or instructions per second
Latency (response time)
Time between task start Clock and end
e.g., Cameras A and B process images in 0.25 seconds
Throughput
Tasks per second, e.g. Camera A processes 4 images
per second
Throughput can be more than latency seems to imply
due to concurrency, e.g. Camera B may process 8
images per second (by capturing a new image while
previous image is being stored).
Speedup of B over S = Bs performance / As performance
Throughput speedup = 8/4 = 2
Embedded System Technologies
Technology
A manner of accomplishing a task, especially using
technical processes, methods, or knowledge
Three key technologies for embedded systems
Processor technology
IC technology
Design technology
Arduino
Worlds First Open Source
Embedded Platform.....
Arduino Board
An Arduino development board consists of
8 bit microcontroller
Programming hardware
USB programming interface
I/O Pins
Arduino Board
Arduino Board
Arduino board has a software environment, an
IDE which is an integrated development
environment.
It is having
Cross-compiler
Debugger
Simulator
Programmer
Arduino Environment
You write the code in IDE.
And you don't have to use the Arduino IDE to
write code .
You could program an Arduino using eclipse or
some other IDE
Arduino IDE is easier to handle.
Arduino Shields
Arduino environment has different shields
They are
Special purpose boards
With unique functionalities
Easy to attach
Good libraries provided
Arduino board is an open source board
You can modify the board schematic and design
your own board.
As its expensive to do that, buy a pre-made
board.
Execution
The two types of code executing on a
microcontroller is the
1) Application Code
This executes systems main functionality
And we write this code
2) Firmware
Its a low level code written to support the main
functionality
And that is the USB interface code in
ATMega16u2, Power modes, reset etc.
Bootloader
The bootloader is a
Firmware on a microcontroller
Allows the flash and EEPROM to be
programmed
Manages USB communication, since
application programming is via USB.
The bootloader cannot be updated through
USB interface.
In-Circuit Serial Programming (ICSP) is used to
update bootloader by using the special pins
on the board.
Arduino Board
The board got two ICSP ports for ATmega328,
and ATmega16U2
One ICSP header near the ATmega16U2.
And theres another ICSP header for the
ATmega328.
Prerequisites
Familiar with the basics of C Language &
Object Oriented programming languages.

Arduino is nothing but basics of C and added


features of Arduino programming language.

A basic understanding of Microcontrollers and


Electronics is also expected.
Arudino
Arduino is a computer hardware and software
company.

Open-source electronic prototyping platform enabling


users to create interactive electronic objects.

The project's products are distributed as open-source


hardware and software, which are licensed under
the GNU Lesser General Public License (LGPL) or
the GNU General Public License (GPL) permitting the
manufacture of Arduino boards and software
distribution by anyone.
Arduino Boards
The Arduino project started in 2005 as a
program in Interaction Design Institute at Italy.

Arduino boards are available commercially in


preassembled form or as DIY kits.

The Board designs use a variety of


microprocessors and microcontrollers.
Arudino Boards
Different Arduino boards are available.
Different microcontrollers are used.
All Arduino boards can be programmed
through the Arduino IDE software.
They differ in number of Input & Output Pins
with voltage ratings from 3.7 v to 5 v.
Types of Boards
Boards based on ATMEGA32 microcontroller

Arduino Uno R3
Arduino Uno R3 SMD
Red Board
Arduino Pro 3.3v/8 MHz
Arduino Pro 5V/16MHz
Arduino mini 05
Arduino Pro mini 3.3v/8mhz
Arduino Pro mini 5v/16mhz
Arduino Ethernet
Arduino Fio
Types of Boards
Boards Based on ATMEGA32u4 microcontroller
LilyPad Arduino 328 main board
LilyPad Arduino simply board
Duemilanove
Nano
Diecimila
Types of Boards
Boards based on ATMEGA2560 microcontroller
Arduino Mega 2560 R3
Mega Pro 3.3V
Mega Pro 5V
Mega Pro Mini 3.3V
Boards based on AT91SAM3X8E microcontroller
Arduino Mega 2560 R3
Arduino UNO board
Pins on Arduino Board
Pin 1. Power USB :
Arduino board can be powered by using the USB cable from your
computer.
All you need to do is connect the USB cable to the USB connection.

Pin 2. Power (Barrel Jack) : Arduino boards can be powered directly


from the AC mains power supply by connecting it to the Barrel Jack.

Pin 3. Voltage Regulator: The function of the voltage regulator is to


control the voltage given to the Arduino board and stabilize the DC
voltages used by the processor and other elements.

Pin 4. Crystal Oscillator: The crystal oscillator frequency is 16,000,000


Hertz or 16 MHz.
Pins on Arduino Board
Pins 5 & 17 Arduino Reset :
You can reset your Arduino board i.e. start
your program from the beginning.
You can reset the UNO board in two ways.
First, by using the reset button (17) on the
board.
Second, you can connect to an external reset
button to the Arduino pin labelled RESET (5).
Pins on Arduino Board
Pins 6,7,8,9 Pins (3.3, 5, GND, Vin)
3.3V (6) Supply 3.3 output volt
5V (7) Supply 5 output volt
GND (8)(Ground) There are several GND pins on
the Arduino, any of which can be used to ground
your circuit.
Vin (9) This pin also can be used to power the
Arduino board from an external power source,
like AC mains power supply.
Pins on Arduino Board
10 Analog pin : The Arduino UNO board has
five Analog input pins A0 through A5.
These pins can read the signal from an
Analog sensor.
ex: Humidity Sensor or Temperature sensor
Converts it into a digital value that can be
read by the microcontroller.
Pins on Arduino Board
11 Main Microcontroller
Each Arduino board has its own microcontroller
The microcontrollers are usually of the ATMEL Company
13 Power LED indicator : This LED should light up when you plug
your Arduino into a power source to indicate that your board is
powered up correctly.
14 TX and RX LEDs
First, at the digital pins 0 and 1, to indicate the pins responsible for
serial communication.
Second, the TX and RX led (13). The TX led flashes with different
speed while sending the serial data. The speed of flashing depends
on the baud rate used by the board.
RX flashes during the receiving process.
Pins on Arduino Board
15 Digital I/O : The Arduino UNO board has 14
digital I/O pins (of which 6 provide PWM
(Pulse Width Modulation) output.
These pins can be configured to work as input
digital pins to read logic values (0 or 1) or
as digital output pins to drive different
modules like LEDs, relays, etc.
The pins labelled ~ can be used to generate
PWM.
Pins on Arduino Board
16. AREF
AREF stands for Analog Reference.
It is sometimes, used to set an external
reference voltage (between 0 and 5 Volts) as
the upper limit for the Analog input pins
Setup
Set up the Arduino Board.
Prepare the Board to receive(or upload) the
program via USB cable.
Download Arduino IDE Software
Power up your Board
Launch Arduino IDE software.
Atmega328 Microcontroller

An 8-bit microcontroller with 28 pins.


14 are I/O pins, of which 6 can be used as
PWM outputs and 6 as analog input pins.
Has 32K of flash memory.
Has 1K of EEPROM.
Has 2K of internal SRAM.
Atmega328 used with the popular Arduino
Duemilanove boards.
Layout of Arduino Board
Getting Started with Arduino

Materials needed
Arduino-compatible board ex: Arduino UNO
USB cable A to B
2 - LEDs
2 - 330 resistors
A mini breadboard
5 - Jumper wires
Connecting the Arduino

Plug in the respective USB terminals to the


USB cable and the tiny LEDs on the Arduino
should begin to flash.
If the LEDs didn't turn on, ensure that the USB
port on your computer is functioning and
make sure the cable isn't faulty.
If it still does not light up, there is something
wrong with your board and you should get it
checked.
Flashing LEDS on Board
Setting up on Windows OS
The computer will begin to install the drivers for the Arduino by itself.
If it does not succeed, do the following:
1. Open Device Manager.
2. Click on Ports (COM & LPT).
3. Right-click on Unknown Device and select Properties.
4. Click on Install Driver and choose browse files on the computer.
5. Choose the drivers folder in the previously installed Arduino
folder.

The computer should say that your Arduino UNO (USB) has been
successfully installed on COM port (xx). Here xx refers to a single or
double digit number.

If this message didn't pop up, go back to the Device Manager and
check if it has been installed under COM ports.
Arduino IDE
The Arduino software, commonly referred to
as the Arduino IDE (Integrated Development
Environment)
The IDE for Windows, Mac OS, and Linux is
almost identical.
When you use Arduino IDE package your
sketches must follow a specific coding format.
Arduino Sketches
The Arudino sketches dont have a main
function in the code.

The Arduino bootloader program that


preloaded onto Arduino.

The Arduino starts the bootloader, and the


bootloader program starts to run the code in
your sketch.
Boot Loader
The bootloader program specifically looks for two separate
functions in the sketch

Setup()
Loop()

The Arduino bootloader calls the setup function as the first


thing when the Arduino Board powers.

The code you place in the setup function in your sketch


only runs one time

Then the bootloader moves on to the loop function code.


Use of Libraries
How advance the Arduino sketch is, you may or may
not need to use other functions found in external
library files.

If you do need to use external libraries, you first need


to define them at the start of your Arduino program,
using the #include directive
#include < library >

The #include directives will be the first lines in your


sketch
How to
There are 2 ways of opening IDE
Click on Arudino icon
By default it opens setup and loop functions
Open IDE and click on File New

Connecting to a Arduino Board


Tools Board Arduino Uno

Write the sketch and

Finally, hit the Upload button.


If everything is fine, the LEDs on the Arduino should start flickering
as the code is uploaded to the Arduino.
The code will then have uploaded to the Arduino.
Sketch
To print Hello World in serial monitor

void setup()
{
serial.begin(9600);
serial.println("Hello World!");
}
void loop()
{
}
Output
Click on the Serial Monitor button on the right
side
Switch the baud rate on the Serial Monitor
window to 9600.
You should see your message Hello World!
waiting for you there.
LED Sketch
Go to File Examples Basics Blink

Plug in the LED such that the longer leg goes


into pin 13 and the shorter leg goes into the
GND pin

Upload the code. Your LED will start blinking


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

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
}
Double LED Blink
Sketch
int led1 = 12;
int led2 = 13;

void setup()
{
// initialize the digital pins as an output.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
// turn off LEDs before loop begins
digitalWrite(led1, LOW); // turn the LED off (LOW is the voltage level)
digitalWrite(led2, LOW); // turn the LED off (LOW is the voltage level)
}
//the loop routine runs over and over again forever:
void loop()
{
digitalWrite(led1, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(led2, LOW); // turn the LED off (LOW is the voltage level)
delay(1000); // wait for a second
digitalWrite(led1, LOW); // turn the LED off (LOW is the voltage level)
digitalWrite(led2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
}
Structure OF Arduino sketch

Arduino (Sketch)programs can be divided in three


main parts:
Structure
Values (variables and constants) and
Functions.

Software structure consists of two main functions


Setup( ) function
Loop( ) function
The setup() function is called when a sketch
starts.
Initialize the variables, pin modes and start
using libraries

The loop() function loops allowing your


program to change and respond.
Data types used in Arduino
Void
Boolean
Char
Unsigned
Byte
Unsigned int
Word
Long
Unsigned Long
Short
Float
Double
Data Types
Void
is used only in function declarations.
It indicates that the function is expected to return no
information to the function from which it was called.

Boolean
A Boolean holds one of two values, true or false.
Each Boolean variable occupies one byte of memory.

Ex : boolean val = false


boolean val = true
Char
A data type that takes up one byte of memory that stores a
character value
Char chrX = a
Char chrY = 97

Unsigned
Data type that occupies one byte of memory.
The unsigned char data type encodes numbers from 0
to 255.
Unsigned Char chrQ = 121 ;
Byte
stores an 8-bit unsigned number, from 0 to 255
byte m = 25 ;
int
Primary data-type for number storage.
int stores a 16-bit (2-byte) value. This yields a
range of -32,768 to 32,767
int counter = 32 ;
Data Types
Unsigned int
same as int data type.
They only store positive values.
Yielding a range of 0 to 65,535 ((2^16) - 1)
The Due stores a 4 byte (32-bit) value, ranging
from 0 to 4,294,967,295 (2^32 - 1)
i.e 2 N 1 where N = 16 or 32 bits
Data Types
Word
On the Uno and other ATMEGA based boards,
word stores a 16-bit unsigned number.
On the Due and Zero,
it stores a 32-bit unsigned number
word w = 1000 ;
Data Types
long
Long variables are extended size variables Store
32 bits (4 bytes) from 2,147,483,648 to
2,147,483,647
long velocity = 102346 ;
Unsigned Long
store 32 bits (4 bytes).
will not store negative numbers
Their range is 0 to 4,294,967,295 (2^32 - 1)
Ex : unsigned Long velocity = 101006 ;
Data Types
short
A 16-bit data-type.
On ATMega and ARM based a short stores a
16-bit (2-byte) value.
yields a range of -32,768 to 32,767
EX : short val = 13 ;
Data Types
float
Floating-point numbers are often used to
approximate the analog and continuous
values
They are stored as 32 bits (4 bytes)
Can be as large as 3.4028235E+38 and as low
as 3.4028235E+38
ex : float num = 1.352;
Data Types
Double
On the Uno and other ATMEGA based boards,
Double floating-point number occupies four
bytes.
On the Arduino Due, double have 8-byte
(64 bit) precision.
ex: double num = 45.352 ;
Scope of a Variable
A scope is a region of the program and there
are three places where variables can be
declared.
Inside a function or a block, which is
called local variables
Outside of all functions, which is called global
variables
In the definition of function parameters,
which is called formal parameters
Operators
An operator is a symbol that tells to perform
specific mathematical or logical functions.

Types of operators
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators
A and B are variables

= A=B
+ A+B
- A-B
* A*B
/ A/B
% A%B
Comparison Operators
A and B are variables

== (A == B) is not true
!= (A != B) is true
< (A < B) is true
> (A > B) is true
<= (A <= B) is less than or equal to
>= (A >= B) is greater than or equal to
Boolean Operators

A and B are variables

and && (A && B) is true


or || (A || B) is true
not ! !(A && B) is false
Bitwise Operators
A = 60 and B = 13
And & (A & B) - copies a bit to the result if
it exists in both operands.
Or | (A | B) - copies a bit if it exists in either
operands.
Xor ^ (A ^ B) - copies the bit if it is set in one
operand but not both.
Not ~ (~A ) - Complement Operator
shift left << A << 2 value is moved left by the
number of bits specified by the right operand.
shift right>> A >> 2 value is moved right by the
number of bits specified by the right operand.
Compound Operators
Increment ++ increases integer value
by one
Decrement -- decreases integer value
by one
compound addition += adds right operand to
the left operand and assign the result to left
operand
compound subtraction -= subtracts right
operand from the left operand and assign the
result to left operand
Compound Operators
compound division /= divides left operand with the
right operand and assign the result to left operand
compound modulo %= takes modulus using two
operands and assign the result to left operand
compound bitwise or |= bitwise inclusive OR and
assignment operator
compound bitwise and &= Bitwise AND assignment
operator
compound multiplication *= multiplies right operand
with the left operand and assign the result to left
operand
Decision Making

Decision making structures require that the


programmer specify one or more conditions
to be evaluated or tested by the program.
Types
If Statement
If --else Statement
If --elseif -- else Statement
Switch Case Statement
Conditional Operator
Loops
While
will loop continuously, and infinitely, until the
expression inside the parenthesis, () becomes false.
condition is tested at the beginning of the loop before
the body of the loop
Do --- While
Execution of statements are done and condition is
tested
For loop
executes statements for a predetermined number of
times
Strings
Are used to store text
Can be used to display text on an LCD or in the
Arduino IDE Serial Monitor window.
Strings are also useful for storing the user
input.
Two types of strings
Arrays of characters
Arduino String
Strings
Character Arrays
Array is a consecutive series of the same type
of variable stored in memory
A string is an array of char variables
A string is a special array that has one extra
element at the end of the string, which always
has the value of 0 (zero). This is known as a
"null terminated string".
Strings
Character Array Ex
void setup()
{
char my_str[] = "Hello";
serial.begin(9600);
serial.println(my_str);
}
void loop()
{
}
Object

An object is a construct that contains both


data and functions.
A String object can be created just like a
variable and assigned a value or string.
The String object contains functions (which
are called "methods" in object oriented
programming (OOP)) which operate on the
string data contained in the String object.
String Object Example
void setup()
{
string my_str = "This is my string."; // my_str is the String Object
serial.begin(9600); // (1) print the string
serial.println(my_str); // (2) change the string to upper-case
my_str.toUpperCase();
serial.println(my_str); // (3) overwrite the string
my_str = "My new string.";
serial.println(my_str); // (4) replace a word in the string
my_str.replace("string", "Arduino sketch");
serial.println(my_str); // (5) get the length of the string
serial.print("String length is: ");
serial.println(my_str.length());
}
void loop()
{

}
Arrays
Declaration
type arrayName [ arraySize ] ;
Reserves the appropriate amount of memory
To reserve 11 elements for integer array
- int c[12] ; c is an array of 12 integers
- int n[10]; n is an array of 10 integers
Array example
int n[ 7 ] ; // n is an array of 10 integers
void setup ()
{
}
void loop ()
{
for ( int i = 0; i < 7; ++i ) // initialize of array n to 0
{
n[ i ] = 0; // set element at location i to 0
serial.print (i) ;
serial.print (\r) ;
}
for ( int j = 0; j < 7; ++j ) // output each array value
{
serial.print (n[j]) ;
serial.print (\r) ;
}
}
Output
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
Measurements

There are many ways to measure or sense


things in Electronic Applications.
Measurements or Sensing can be done by
Transducers and Sensors
Transducer = Sensor + Signal Conditioning.
A signal conditioning circuit, conditions the
signal so that it is strong enough for further
processing.
Sensors
A Sensor converts one form of energy to
another.
It senses a physical quantity and converts it
into an electrical signal.
It detects events or changes in its
environment & send the information to the
system which then tells the output devices to
provide the corresponding output.
It converts real world data (Analog) into data
that a computer can understand using ADC
(Analog to Digital converter).
Types of Sensors
Sensors can be classified according to :
Type of signal they produce (Analog Sensors or
Digital Sensors) and
The type of phenomena they measure.

Sensors
accelerometers
pressure sensors
light sensors
sound sensors
temperature sensors
Sensors
Flame Sensor
int Buzzer = 13; // Use buzzer for alert
int FlamePin = 2; // This is for input pin
int Flame = HIGH; // HIGH when FLAME Exposed

void setup()
{
pinMode(Buzzer, OUTPUT);
pinMode(FlamePin, INPUT);
Serial.begin(9600);
}
void loop() {
Flame = digitalRead(FlamePin);
if (Flame== HIGH)
{
Serial.println("HIGH FLAME");
digitalWrite(Buzzer, HIGH);
}
else
{
Serial.println("No flame");
digitalWrite(Buzzer, LOW);
}
}
Sensors
Sensors
Humidity Sensor - DHT-22
It is a digital-output, relative humidity, and
temperature sensor.
It uses a capacitive humidity sensor and a
thermistor to measure the surrounding air,
and sends a digital signal on the data pin.
Humidity Sensor
Humidity Sensor
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
// Connect pin 2 of the sensor to whatever your
DHTPIN is
// Connect pin 4 (on the right) of the sensor to
GROUND
// Connect a 10K resistor from pin 2 (data) to pin
1 (power) of the sensor
// Initialize DHT sensor.
Humdity Sensor
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop()
{
delay(2000); // Wait a few seconds between measurements
float h = dht.readHumidity();
// Reading temp or humidity takes about 250 msec
float t = dht.readTemperature();
// Read temperature as Celsius
float f = dht.readTemperature(true);
// Read temperature as Fahrenheit (isFahrenheit =
true)
// Check if any reads failed and exit early (to try
again).
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Humidty Sensor
// Compute heat index in Fahrenheit (the default)

float hif = dht.computeHeatIndex(f, h);

// Compute heat index in Celsius (isFahreheit = false)


float hic = dht.computeHeatIndex(t, h, false);
Serial.print ("Humidity: ");
Serial.print (h);
Serial.print (" %\t");
Serial.print ("Temperature: ");
Serial.print (t);
Serial.print (" *C ");
Serial.print (f);
Serial.print (" *F\t");
Serial.print ("Heat index: ");
Serial.print (hic);
Serial.print (" *C ");
Serial.print (hif);
Serial.println (" *F");
}
Liquid Crystal Display
A Liquid Crystal Display is a display Unit built
using Liquid Crystal Technology.
When we build electronic based projects, we
need a medium or device to display output
values and messages.
The most basic form of electronic display
available is 7 Segment Display(Which has its
own limitations).
The next best available option is LCD, which
comes in different size & specifications.
LCD
The commonly used one is 162 LCD
Module, which can display 32 ASCII characters
in 2 lines (16 characters in 1 line).
Other commonly used LCD displays are 204
Character , 12864 Graphical LCD Display and
2.4 inch TFT Touch screen LCD display.
How to interface LCD to Arduino
162 LCD module to Arduino &
204 LCD module to Arduino.
Interfacing 162 LCD to Arduino
The knowledge on interfacing LCD module to
Arduino is very essential in designing
embedded systems.
The LCD module has 16 pins and can be
operated in 4-bit mode/8-bit mode.
JHD162A is a 162 LCD module based on
the HD44780 driver from Hitachi.
The JHD162A has 16 pins and can be operated
in 4-bit mode (using only 4 data lines) or 8-bit
mode (using all 8 data lines).
Interfacing 162 LCD to Arduino
The schematic of a JHD162A LCD pin diagram.
Pins of LCD
Pin1(Vss) : Ground pin of the LCD module.
Pin2(Vcc) : Power to LCD module (+5V supply is given to this pin)
Pin3(VEE) :Contrast adjustment pin.
This is done by connecting the ends of a 10K pot to +5V and gnd
and then connecting the slider pin to the VEE pin.
The voltage at the VEE pin defines the contrast. The normal setting
is between 0.4 and 0.9V.

Pin4(RS) : Register select pin. The JHD162A has two registers


namely command register and data register.

Logic HIGH at RS pin selects data register and logic LOW at RS pin
selects command register.
If RS pin HIGH and feed an input to the data lines (DB0 to DB7), this
input will be treated as data to display on LCD screen.
If RS pin LOW and feed an input to the data lines, then this will be
treated as a command (a command to be written to LCD controller
like positioning cursor or clear screen or scroll)
Pins of LCD
Pin5(R/W) : Read/Write modes.
This pin is used for selecting between read and
write modes.
Logic HIGH at this pin activates read mode and
Logic LOW at this pin activates write mode.

Pin6(E) : This pin enable the LCD module.


A HIGH to LOW signal at this pin will enable the module.
Pin7(DB0) to Pin14(DB7) : These are data pins.
The commands and data are fed to the LCD module
though these pins.
Pin15(LED+) : Anode of the back light LED.
When operated on 5V, a 560 ohm resistor should be connected in
series to this pin.
In Arduino based projects the back light LED can be powered from the 3.3V source
on the Arduino board.

Pin16(LED) : Cathode of the back light LED.


Interfacing LCD to Arduino
Interfacing LCD with Arduino
RS pin of the LCD module is connected to digital pin 12 of the Arduino.
R/W pin of the LCD is grounded.
Enable pin of the LCD module is connected to digital pin 11 of the Arduino.

LCD module and Arduino are interfaced in the 4-bit mode. This means only four of
the digital input lines( DB4 to DB7) of the LCD are used.

Digital lines DB4, DB5, DB6 and DB7 are interfaced to digital pins 5, 4, 3 and 2 of
the Arduino.

The 10K potentiometer is used for adjusting the contrast of the display. 560 ohm
resistor R1 limits the current through the back light LED.

The Arduino can be powered through the external power jack provided on the
board.

+5V required in some other parts of the circuit can be tapped from the 5V source
on the Arduino board. The Arduino can be also powered from the PC through the
USB port.
Interfacing LCD
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // sets the interfacing pins

void setup()
{
lcd.begin(16, 2); // initializes the 16x2 LCD
}
void loop()
{
lcd.setCursor(0,0); //sets the cursor at row 0 column 0
lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
lcd.setCursor(2,1); //sets the cursor at row 1 column 2
lcd.print(United Engineers"); // prints United Engineers
}
Wireless Communication
Wireless is a form of communication or transmission
of information over a distance without requiring wires,
cables or any other electrical conductors.

The devices used for wireless communication are


Cordless Telephones & Mobiles, GPS units, ZigBee
Units, Wireless Computer parts and Satellite TV.

The Communication is set and the information is


transmitted through the air, without requiring any
cables, by using electromagnetic waves like radio
frequencies, infrared, satellite.
WiFi Technology
Wi-Fi is the name of a popular wireless local area
networking technology that uses radio waves to
provide wireless high-speed Internet
and network connections.
WiFi technology is based on the IEEE 802.11
standards.
Wi-Fi compatible devices can connect to the
Internet via a WLAN network and a wireless
access points.
Wi-Fi most commonly uses the 2.4 gigahertz
(12 cm) UHF and 5 gigahertz (6 cm) SHF ISMradio
bands.
WiFi Technology
Wi-Fi may be used to provide internet access to
devices that are within the range of a wireless
network that is connected to the Internet.

The coverage of one or more hotspots can extend


from an area as small as a few rooms to as large
as many square kilometres.

Embedded Wi-Fi modules have a real-time OS


and provide a simple means of wirelessly
enabling any device which has and communicates
via a serial port. This allows the design of simple
monitoring devices.
WiFi Shields
Shields are boards that can be plugged on top
of the PCB extending its capabilities.
Arduino WiFi Shield connects your Arduino to
the internet wirelessly.
The Arduino WiFi Shield allows an Arduino
board to connect to the internet using the
802.11 wireless specification (WiFi).
It is based on the HDG204 Wireless LAN
802.11b/g System in-Package.
Arduino WiFi Shield
An AT32UC3 provides a network (IP) stack capable of
both TCP and UDP.
WiFi Library is used to write sketches which connect to
the internet using the shield.
The WiFi Shield can connect to wireless networks which
operate according to the 802.11b and 802.11g
specifications.
There is an onboard micro-SD card slot, which can be
used to store files for serving over the network.
The onboard micro-SD card reader is accessible through
the SD Library. When working with this library, SS is on
Pin 4.
Arduino WiFi Shield
Arduino communicates with both the Wifi shield's
processor and SD card using the SPI bus (through the
ICSP header).
The WiFi shield has an ESP8266 which is an effective
platform for communicating over the internet.
It is a wireless SOCs, designed for space and power
constrained mobile platform designers.
It has ability to embed WiFi capabilities within other
systems, or to function as a standalone application,
with the lowest cost, and minimal space
requirement.
Arduino & ESP8266
Connect Arduino with an ESP-01 module to control
an LED over the internet.
You can control any electrical device through the
internet from anywhere in the World by using an
web server.
The ESP8266 can be controlled from your local wifi
network or from the internet.
The ESP-01 module has GPIO pins that can be
programmed to turn an LED or a relay ON/OFF over
the internet.
The module can be programmed using an
Arduino/USB to TTL converter through the serial pins
(RX,TX).
Arduino and ESP8266
ESP8266 has been designed for mobile, wearable electronics and
Internet of Things applications.
There are three methods to upload the code to ESP8266
Arduino Uno to Flash the code to ESP8266.
While uploading the code press the flash button, keep the flash
button pushed while you click once on reset. You may now release
the flash button.
The ESP8266 is now in flash mode. You will be able to upload the
sketch now.
In Arduino IDE go to Tools Select Board Generic ESP8266 module
Write the sketch press upload button. Change the ssid of your wifi
access point, and change the password of your wifi password and
compile.
ESP8266
Arduino sketch
#include <ESP8266WiFi.h>
const char* ssid = "YOUR_SSID"; //type your ssid
const char* password = "YOUR_PASSWORD"; //type your password
int ledPin = 2; // GPIO2 of ESP8266
WiFiServer server(80); //Service Port

void setup()
{
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500); Serial.print(".");
}
Arduino sketch
Serial.println("");
Serial.println("WiFi connected"); // Start the server
server.begin();
Serial.println("Server started"); // Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client)
{
return;
}
// Wait until the client sends some data
Arduino sketch
Serial.println("new client");
while(!client.available())
{
delay(1);
}
// Read the first line of the request

String request = client.readStringUntil('\r');


Serial.println(request);
client.flush(); // Match the request
int value = LOW;
if (request.indexOf("/LED=ON") != -1)
{
digitalWrite(ledPin, HIGH);
value = HIGH;
}
Arduino sketch
if (request.indexOf("/LED=OFF") != -1)
{
digitalWrite(ledPin, LOW);
value = LOW;
}
//Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response

client.println("HTTP/1.1 200 OK");


client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Led pin is now: ");
Arduino sketch
if(value == HIGH)
{
client.print("On");
} else
{
client.print("Off");
}
client.println("<br><br>");
client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 2
ON<br>");
client.println("Click <a href=\"/LED=OFF\">here turn the LED on pin 2
OFF<br>");
client.println("</html>"); delay(1);
Serial.println("Client disconnected");
Serial.println("");
}
Arduino ESP8266
Open the serial monitor
Open the URL shown in your serial monitor
through your web browser.
Connect GPIO 2 of ESP8266 to the LED +ve
terminal.
Now you can control the LED remotely
through the internet.
Click on the respective hyperlinks in your
browser to toggle the LED ON/OFF.
Arduino ESP8266
As ESP8266 module has been uploaded with
the sketch
The ESP8266 module can only be accessed
through the local wifi network.
Remove Arduino Board and make ESP8266 a
standalone module.
To be able to control your devices from the
internet, you have to do port forwarding on
your router.
Arduino ESP8266
Find the ip address of your system by ipconfig.
Open router setting and go to the
Forwarding settings.
Enter the details for the Service Port and IP
Address.
The service port is the port number from your
Arduino code (Service port: 80)
WiFiServer server(80);//Service Port
Enter the address: xxx.xxx.xx.xx:80
Open the browser page to control the LED.
Serial communication
In telecommunication and data
transmission, serial communication is the
process of sending data one bit at a time,
sequentially, over a communication or bus.
RS-232 is a standard for serial communication
transmission of data.
Upload the sketch to the Arduino.
Open the Serial monitor, keep the USB connected
to the Arduino during this process, as the USB
cable is your communication link between your
computer and the Arduino.
During data transmission TX and RX LEDs on
Board blink while transmitting and Receiving.
Serial Communication
/* Serial ECHO
/* variable byteRead temporarily store the data coming from the PC */

byte byteRead;
void setup()
{
Serial.begin(9600); // Turn the Serial Protocol ON
}
void loop()
{
if (Serial.available()) /* check if data has been sent from the computer: */
{
/* read the most recent byte */
byteRead = Serial.read();
/*ECHO the value that was read, back to the serial port. */
Serial.write(byteRead);
}
}
Servo Motors
Special types of applications of electrical motors
where rotation of the motor is for a certain angle
but not continuously for long period of time.
A servo motor is a rotary actuator that allows for
precise control of angular position and has a
motor coupled to a sensor for position feedback.
It Requires a servo drive to complete the system.
Servo Motors are recommended for high-speed
(greater than 2,000 RPM) and high torque
applications requiring dynamic load changes.
Applications
Robotics
Conveyor Belts
Camera Auto Focus
Solar Tracking System
Metal Cutting & Metal Forming Machines
Antenna Positioning
Woodworking/CNC
Textiles-Spinning and Weaving
Printing Presses/Printers
Automatic Door Openers
Arduino with Servo motor
Servo motors have 3 connections
Black/Brown ground wire
Red wire (5V)
Yellow or White PWM wire.

Connect
the power and ground pins directly to the Arduino
5V and GND pins.
PWM input will be connected to Arduino's digital
output pin.
Arudino Servo
Write the sketch in Arudino IDE and Upload

#include <servo.h>
Servo servoMain; //initialize a servo object for the servo
int angle = 0;
void setup()
{
servoMain.attach(9);
// attach signal pin of servo to pin9 of Arduino
}
void loop()
{
for(angle = 0; angle < 180; angle += 1)
// command to move from 0 degrees to 180 degrees
{
servoMain.write(angle);
//command to rotate the servo to the specified angle delay(15);
}
Arudino Servo
delay(1000);
for(angle = 180; angle>=1; angle-=5)
// command to move from 180 degrees to 0 degrees
{
servo_test.write(angle);
//command to rotate the servo to the specified
angle delay(5);
}
delay(1000);
}
Stepper Motors
Stepper motors are DC motors that move in
discrete steps.
They have multiple coils that are organized in
groups called "phases". By energizing each
phase in sequence, the motor will rotate,
one step at a time.
They are either bipolar, requiring two power
sources or a switchable polarity power source,
or uni-polar, requiring only one power source.
The Stepper Motors are manufactured with
steps per revolution of 12, 24, 72, 144, 180,
and 200.
Resulting in stepping angles of 30, 15, 5, 2.5,
2, and 1.8 degrees per step.
The stepper motor can be controlled with or
without feedback.
Stepper Motors are commonly recommended
for applications that are cost-sensitive and low
maintenance.
Stepper Motor
Stepper Motor Control
#include <Stepper.h>
const int stepsPerRevolution = 90;
// 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(5);
// initialize the serial port:
Serial.begin(9600);
}
Stepper motor control
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);
}

Вам также может понравиться