Advanced Embedded Book PDF
Advanced Embedded Book PDF
Embedded Systems
Contents
Chapter 1 1.1
1.1.1
1.1.2
Characteristics ................................................................................................................. 8
1.1.3
User interface.................................................................................................................. 8
1.1.4
1.1.5
Peripherals ...................................................................................................................... 9
1.2
Microcontrollers...................................................................................................................... 9
1.2.1
1.2.2
1.2.3
1.2.4
1.2.5
1.2.6
1.2.7
1.2.8
1.3
1.3.1
1.4
1.5
1.6
1.7
1.7.1
1.7.2
1.7.3
1.7.4
1.7.5
Chapter 2 -
2.1
Features ................................................................................................................................ 21
2.2
2.3
2.4
Advanced Embedded
June 2011
2.6
2.7
2.7.1
2.7.2
Chapter 3 -
3.1
3.2
3.3
JTAG Image............................................................................................................................ 27
3.4
Chapter 4 -
4.1
Peripherals ............................................................................................................................ 32
4.2
4.2.1
4.2.2
4.2.3
4.3
Microcontroller ..................................................................................................................... 36
4.4
LEDs ....................................................................................................................................... 36
4.5
Switches ................................................................................................................................ 36
4.6
4.7
CC2500 Module..................................................................................................................... 37
4.8
4.9
4.10
4.11
4.12
Chapter 5 5.1
5.1.1
5.2
5.3
5.3.1
5.4
5.4.1
Building makefile........................................................................................................... 43
Advanced Embedded
June 2011
5.5
5.6
5.7
5.8
5.9
Chapter 6 -
6.1
Introduction .......................................................................................................................... 52
6.2
6.3
6.4
Bit-Wise Operators................................................................................................................ 53
6.4.1
6.4.2
6.4.3
6.5
6.5.1
6.5.2
6.5.3
6.5.4
6.6
Pointers ................................................................................................................................. 55
6.6.1
Chapter 7 -
7.1
Registers ................................................................................................................................ 57
7.2
7.3
7.3.1
7.3.2
7.4
7.5
Chapter 8 -
8.1
Introduction .......................................................................................................................... 60
8.2
8.3
8.4
Advanced Embedded
June 2011
Circuit Connection................................................................................................................. 62
8.6
8.7
8.8
Chapter 9 9.1
Chapter 10 -
10.1
Introduction .......................................................................................................................... 66
10.2
10.3
10.4
Chapter 11 -
11.1
Introduction .......................................................................................................................... 70
11.2
Theory of Operation.............................................................................................................. 70
Chapter 12 -
12.1
Introduction .......................................................................................................................... 71
12.2
Theory of Operation.............................................................................................................. 71
12.3
Chapter 13 -
13.1
13.2
Characteristics of WSN.......................................................................................................... 76
13.3
13.4
Chapter 14 14.1
OSI Model.............................................................................................................................. 80
14.1.1
Introduction .................................................................................................................. 80
14.1.2
14.2
Ethernet ................................................................................................................................ 82
14.2.1
Introduction .................................................................................................................. 82
14.2.2
14.2.3
14.2.4
14.3
14.3.1
Introduction .................................................................................................................. 83
Advanced Embedded
June 2011
TCP ................................................................................................................................ 83
14.3.3
14.3.4
IP Address...................................................................................................................... 87
14.4
14.5
14.6
Ping........................................................................................................................................ 89
14.6.1
Introduction .................................................................................................................. 89
14.6.2
14.6.3
14.7
14.7.1
Introduction .................................................................................................................. 90
14.7.2
Web Client/Browser...................................................................................................... 90
14.7.3
Web Server.................................................................................................................... 91
14.8
Telnet .................................................................................................................................... 92
14.8.1
Telnet Messages............................................................................................................ 92
14.8.2
Implementation ............................................................................................................ 93
14.8.3
Summary ....................................................................................................................... 93
14.9
Chapter 15 -
15.1
Introduction .......................................................................................................................... 94
15.2
15.3
15.4
Chapter 16 -
Appendix ................................................................................................................... 97
16.1
16.2
16.3
16.3.1
16.3.2
16.4
Chapter 17 -
Advanced Embedded
June 2011
Chapter 1 -
Advanced Embedded
June 2011
Picture of the internals of an ADSL modem/router. A modern example of an embedded system. This
image shows the parts found inside a Netgear DG632 ADSL Modem/router. It acts as a router
between an ethernet port and an ADSL broadband internet connection, and provides typical home
router features, such as DHCP.
The labeled parts are as follows:
1. Telephone decoupling electronics (for ADSL).
2. Multicolour LED (displaying network status).
3. Single colour LED (displaying USB status).
4. Main processor, a TNETD7300GDU, a member of Texas Instruments' AR7 product line.
5. JTAG (Joint Test Action Group) test and programming port.
6. RAM, a single ESMT M12L64164A 8 MB chip.
7. Flash memory, obscured by sticker.
8. Power supply regulator.
9. Main power supply fuse.
10. Power connector.
11. Reset button.
12. Quartz crystal.
13. Ethernet port.
14. Ethernet transformer, Delta LF8505.
15. KS8721B Ethernet PHY transmitter receiver.
16. USB port.
17. Telephone (RJ11) port.
18. Telephone connector fuses.
Advanced Embedded
June 2011
Characteristics
1. Embedded systems are designed to do some specific task, rather than be a general-purpose
computer for multiple tasks. Some also have real-time performance constraints that must be met,
for reasons such as safety and usability; others may have low or no performance requirements,
allowing the system hardware to be simplified to reduce costs.
2. Embedded systems are not always standalone devices. Many embedded systems consist of small,
computerized parts within a larger device that serves a more general purpose. For example, the
Gibson Robot Guitar features an embedded system for tuning the strings, but the overall purpose of
the Robot Guitar is, of course, to play music. Similarly, an embedded system in an automobile
provides a specific function as a subsystem of the car itself.
3. The program instructions written for embedded systems are referred to as firmware, and are
stored in read-only memory or Flash memory chips. They run with limited computer hardware
resources: little memory, small or non-existent keyboard and/or screen.
1.1.3
User interface
Embedded systems range from no user interface at all dedicated only to one task to complex
graphical user interfaces that resemble modern computer desktop operating systems. Simple
embedded devices use buttons, LEDs, graphic or character LCDs (for example popular HD44780 LCD)
with a simple menu system.
More sophisticated devices use graphical screen with touch sensing or screen-edge buttons provide
flexibility while minimizing space used: the meaning of the buttons can change with the screen, and
selection involves the natural behavior of pointing at what's desired. Handheld systems often have a
screen with a "joystick button" for a pointing device.
Some systems provide user interface remotely with the help of a serial (e.g. RS-232, USB, IC, etc.) or
network (e.g. Ethernet) connection. In spite of the potentially necessary proprietary client software
and/or specialist cables that are needed, this approach usually gives a lot of advantages: extends the
capabilities of embedded system, avoids the cost of a display, simplifies BSP, allows to build rich user
interface on the PC. A good example of this is the combination of an embedded web server running
on an embedded device (such as an IP camera) or a network routers. The user interface is displayed
in a web browser on a PC connected to the device, therefore needing no bespoke software to be
installed.
Advanced Embedded
June 2011
Secondly, Embedded processors can be broken into two broad categories: ordinary microprocessors
(P) and microcontrollers (C), which have many more peripherals on chip, reducing cost and size.
Contrasting to the personal computer and server markets, a fairly large number of basic CPU
architectures are used; there are Von Neumann as well as various degrees of Harvard architectures,
RISC as well as non-RISC and VLIW; word lengths vary from 4-bit to 64-bits and beyond (mainly in
DSP processors) although the most typical remain 8/16-bit. Most architectures come in a large
number of different variants and shapes, many of which are also manufactured by several different
companies.
A long but still not exhaustive list of common architectures are: 65816, 65C02, 68HC08, 68HC11, 68k,
78K0R/78K0, 8051, ARM, AVR, AVR32, Blackfin, C167, Coldfire, COP8, Cortus APS3, eZ8, eZ80, FR-V,
H8, HT48, M16C, M32C, MIPS, MSP430, PIC, PowerPC, R8C, RL78, SHARC, SPARC, ST6, SuperH, TLCS47, TLCS-870, TLCS-900, TriCore, V850, x86, XE8000, Z80, AsAP etc.
1.1.5
Peripherals
Embedded Systems talk with the outside world via peripherals, such as:
1.2 Microcontrollers
1.2.1
What is a Microcontroller?
Advanced Embedded
June 2011
1.2.3
Microcontrollers have gone through a silent evolution (invisible). The evolution can be rightly
termed as silent as the impact or application of a microcontroller is not well known to a common
user, although microcontroller technology has undergone significant change since early 1970's.
Development of some popular microcontrollers is given as follows.
1.2.4
Intel 4004
1971
Intel 8048
8 bit
1976
Intel 8031
8 bit (ROM-less)
Intel 8051
1980
Microchip PIC16C64
8 bit
1985
Motorola 68HC11
Intel 80C196
16 bit
1982
Atmel AT89C51
Microprocessors have undergone significant evolution over the past four decades. This development
is clearly perceptible to a common user, especially, in terms of phenomenal growth in capabilities of
personal computers. Development of some of the microprocessors can be given as follows.
Advanced Embedded
June 2011
Intel 4004
1971
Intel 8080
8085
8 bit (NMOS)
8 bit
1974
Intel 8088
8086
16 bit
16 bit
1978
Intel 80186
80286
16 bit
16 bit
1982
Intel 80386
1985
Intel 80486 SX
DX
32 bit
32 bit (built in floating point unit)
1989
64 bit
1993
1997
1999
2000
8 bit
1976
32-bit
1993
1995
Intel 80586
I
MMX
Celeron II
III
IV
Z-80 (Zilog)
Motorola Power PC
601
602
603
Advanced Embedded
June 2011
At times, a microcontroller can have external memory also (if there is no internal memory or extra
memory interface is required). Early microcontrollers were manufactured using bipolar or NMOS
technologies. Most modern microcontrollers are manufactured with CMOS technology, which leads
to reduction in size and power loss. Current drawn by the IC is also reduced considerably from 10mA
to a few micro Amperes in sleep mode (for a microcontroller running typically at a clock speed of
20MHz).
1.2.6
Many years ago, in the late 1940's, the US Government asked Harvard and Princeton universities to
come up with a computer architecture to be used in computing distances of Naval artillery shell for
defence applications. Princeton suggested computer architecture with a single memory interface. It
is also known as Von Neumann architecture after the name of the chief scientist of the project in
Princeton University John Von Neumann (1903 - 1957 Born in Budapest, Hungary).
Harvard suggested a computer with two different memory interfaces, one for the data / variables
and the other for program / instructions. Although Princeton architecture was accepted for
simplicity and ease of implementation, Harvard architecture became popular later, due to the
parallelism of instruction execution.
Advanced Embedded
June 2011
1.2.7
Example:
An instruction "Read a data byte from memory and store it in the accumulator" is executed as
follows: Cycle 1 - Read Instruction
Cycle 2 - Read Data out of RAM and put into Accumulator
Advanced Embedded
June 2011
1.2.8
The same instruction (as shown under Princeton Architecture) would be executed as follows:
Cycle 1
- Complete previous instruction
- Read the "Move Data to Accumulator" instruction
Cycle 2
- Execute "Move Data to Accumulator" instruction
- Read next instruction
Hence each instruction is effectively executed in one instruction cycle, except for the ones that
modify the content of the program counter. For example, the "jump" (or call) instructions takes 2
cycles. Thus, due to parallelism, Harvard architecture executes more instructions in a given time
compared to Princeton Architecture.
Advanced Embedded
June 2011
Bits
Registers
Variable RAM
Program counter stack
Microcontroller can have ability to perform manipulation of individual bits in certain registers (bit
manipulation). This is a unique feature of a microcontroller, not available in a microprocessor.
Eight bits make a byte. Memory bytes are known as file registers. Registers are some special RAM
locations that can be accessed by the processor very easily.
Advanced Embedded
June 2011
These are the following options available for I/O register space in Harvard Architecture.
Advanced Embedded
June 2011
At the very heart of CISC is a set "complex" instruction like ADD. The computer's memory banks are
directly operated on, thus making the loading or storing functions redundant. ADD is similar to what
a programmer in C++ or any other high-level language would code. Takes control over thousands or
millions of transistors, CPU etc. One of the primary advantages of this system is that the compiler
has to do very little work to translate a high-level language statement into assembly. Micro program
instruction sets can be written to match high-level languages and the compiler does not have to be
as complicated. Minimal lines of coding must also have reduced the probability of errors in the code,
thus reducing cost and debugging-time. In addition, small code sizes could be stored easily to enable
a frugal use of RAM.
CISC seemed like such a natural and intuitive system at the time and it didn't even have a name. The
term was retroactively coined in contrast to reduced instruction set computer computers of the
1970s (although we also have examples of pre-RISC systems of the 1960s) which eventually brought
CISC (Complex Instruction Set Computer) to its knees and forced CISC-philes to defend and debate
with their adversaries.
Advanced Embedded
June 2011
LOAD A, 2:3
LOAD B, 5:2
ADD A, B
STORE 2:3, A
Increasing instruction set & chip hardware complexity leads backward-compatibility issues
Variable length instructions slow down the overall performance of the machine
Many specialized instructions are15 not used frequently
CISC instructions typically also set the condition codes as a side effect
Advanced Embedded
June 2011
With an increase in processor speeds, CISC chips are now able to execute more than one
instruction within a single clock which enables RISC-like pipelining.
We can fit many more transistors on a single chip thus providing more space to execute
CISC-like commands.
Although today, it is proposed that Intel x86 is the only chip which retains pure CISC architecture. It
is however at least as fast the fastest true RISC single-chip solutions available. How the two are
compared depends on whether a qualitative comparison or a quantitative comparison is made.
Well known RISC families include DEC Alpha, AMD 29k, ARC, ARM, Atmel AVR, MIPS, PA-RISC, Power
(including PowerPC), SuperH, and SPARC.
Device architecture
Flash, EEPROM, and SRAM are all integrated onto a single chip, removing the need for external
memory in most applications. Some devices have a parallel external bus option to allow adding
additional data memory or memory-mapped devices. Almost all devices have serial interfaces, which
can be used to connect larger serial EEPROMs or flash chips.
Advanced Embedded
June 2011
1.7.4.1 EEPROM
Almost all AVR microcontrollers have internal EEPROM for semi-permanent data storage. Like flash
memory, EEPROM can maintain its contents when electrical power is removed.
In most variants of the AVR architecture, this internal EEPROM memory is not mapped into the
MCU's addressable memory space. It can only be accessed the same way an external peripheral
device is, using special pointer registers and read/write instructions which makes EEPROM access
much slower than other internal RAM.
Advanced Embedded
June 2011
Chapter 2 -
2.1 Features
High-performance, Low-power AVR 8-bit Microcontroller. Advanced RISC Architecture.
Nonvolatile Program and Data Memories
128K Bytes of In-System Reprogrammable Flash. Endurance: 10,000 Write/Erase Cycles
Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program
True Read-While-Write Operation
4K Bytes EEPROM
Endurance: 100,000 Write/Erase Cycles
4K Bytes Internal SRAM
Up to 64K Bytes Optional External Memory Space
Programming Lock for Software Security
SPI Interface for In-System Programming
JTAG (IEEE std. 1149.1 Compliant) Interface
Boundary-scan Capabilities According to the JTAG Standard
Extensive On-chip Debug Support
Programming of Flash, EEPROM, Fuses and Lock Bits through the JTAG Interface
Peripheral Features
53 Programmable I/O Lines
Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes
Two Expanded 16-bit Timer/Counters with Separate Prescaler, Compare Mode and
Capture Mode
Real Time Counter with Separate Oscillator
Two 8-bit PWM Channels
6 PWM Channels with Programmable Resolution from 2 to 16 Bits
Output Compare Modulator
8-channel, 10-bit ADC
8 Single-ended Channels
7 Differential Channels
2 Differential Channels with Programmable Gain at 1x, 10x, or 200x
Byte-oriented Two-wire Serial Interface
Dual Programmable Serial USARTs
Master/Slave SPI Serial Interface
Programmable Watchdog Timer with On-chip Oscillator
On-chip Analog Comparator
Special Microcontroller Features
Power-on Reset and Programmable Brown-out Detection
Internal Calibrated RC Oscillator
External and Internal Interrupt Sources
Software Selectable Clock Frequency
Global Pull-up Disable
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
2.7.1
Clock Options
External Crystal/Ceramic Resonator
External Low-frequency Crystal
External RC Oscillator
Calibrated Internal RC Oscillator
External Clock
The default clock source setting is the 1 MHz Internal RC Oscillator with longest startup time. This
default setting ensures that all users can make their desired clock source setting using an In-System
or Parallel Programmer.
Advanced Embedded
June 2011
Chapter 3 -
Advanced Embedded
June 2011
2. Plug the USB cable (JTAG / USB on the board). Open Device Manager where you can see
following,
Advanced Embedded
June 2011
Advanced Embedded
June 2011
8. If you wish to change COM PORT number (AVR Studio, JTAG ICE detects COM Port from 1 to 4),
then right click and click on Properties
Advanced Embedded
June 2011
9. Now open Port Settings Tab and click on Advanced and choose desired COM Port and click on OK
Advanced Embedded
June 2011
Chapter 4 -
4.1 Peripherals
-
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Using DC Adapter
Board contains DC regulator of 3.3V and 5V which can be fed from any DC source < 12V. Full Diode
Bridge is provided at the input, securing wrong polarity errors.
=> No polarity considerations while giving DC jack input.
3.3V Regulator
Full Diode Bridge
3.3V Regulator for
Ethernet
Connect the 9V DC adapter provided, and press the DC-Jack Switch, RED power LED should turn ON,
indicating successful powering of the board.
4.2.2
Using USB
Advanced Embedded
June 2011
4.3 Microcontroller
WiNet Board has Atmega128A as the processing unit. AtMega128A is a 3.3V device, it has 128KB
flash, 4KB RAM, I2C, SPI, JTAG, ISP and UART interfaces. Complete details can found in the
datasheet.
4.4 LEDs
6 LEDs are provided on WiNet for general purpose debugging. They are connected from PORTA-0 to
PORTA-5
4.5 Switches
4 Switches are provided for general inputs. On pressing it connects to GND. User has to pull the line
up from the microcontroller itself for no press condition.
Advanced Embedded
June 2011
ATmega128L
FTDI-232
Microcontroller
USB
USBDM
TXD
USBDP
RXD
Via UART
JP5
1
2
2
RXD1
TXD1
JP6
TXD1
TXD FTDI
1
2
2
RXD1
RXD FTDI
Advanced Embedded
June 2011
ATmega128A
TMP-275
Microcontroller
VCC
VCC
I2C_SDA
I2C_SCL
INT6
GND
SDA
V+
SCL
A0
ALERT
A1
GND
A2
ATmega128A
APDS-9300
Pin 1
Pin 2
Pin 3
Microcontroller
Pin 4
I2C_SCL
Pin 5
I2C_SDA
Pin 6
INT
ADDR_SEL
VSS
Advanced Embedded
June 2011
Install FTDI Drivers, Please read How to Install FTDI Drivers chapter.
Advanced Embedded
June 2011
3. Check the COM PORT number is < 5. If not change it, see the
FTDI driver chapter for the same.
Advanced Embedded
June 2011
Chapter 5 -
avr-gcc => The compiler for AVR microcontrollers, which gives object code as output.
avr-as => AVR assembler, used for converting assembly code to object code.
avr-ld => AVR-GCC linker, which will combine all object files into executable file, ELF.
avr-objcopy => Used to convert executable into desired output format. We will use it to
create hex file.
5. avr-gdb => AVR microcontroller based debugger. A very powerful debugger but needs a lot
of time to grasp.
6. avrdude => Used to program the microcontroller with generated hex file.
A bunch of other utilities exist in addition to these. Refer to documentation for further guidance.
Advanced Embedded
June 2011
Linker:
Translator/Copier:
Converts the
output binary into
the intel based hex
file.
.o .out
.out .hex
avr-gcc
avr-objcopy
Compiler:
Compiles the
source code to
object code
.c .o
avr-gcc
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Advanced Embedded
June 2011
4. Choose Debug Platform: JTAG ICE, Device: Atmega128, Port as per your system.
You can check platform options. Click on Finish.
Advanced Embedded
June 2011
Advanced Embedded
June 2011
2. Select Platform as: JTAG ICE, select correct COM Port (you can also choose Auto) and click on
Connect. (Make sure Boards power is ON and JTAG cable is connected in the correct orientation)
Advanced Embedded
June 2011
5. Chose Device as: ATmega 128 and click on Read Signature to verify the chip signature.
It should return OK and show the message: Signature matches selected device.
Advanced Embedded
June 2011
10. To know more details and about JTAG debugging steps, please follow Atmels JTAG ICE manual,
www.atmel.com/atmel/acrobat/doc2475.pdf
Advanced Embedded
June 2011
52 Embedded C Review
Chapter 6 -
Embedded C Review
6.1 Introduction
In this section, we will be discussing a limited set of features of C language. The features we will be
studying are:
1.
2.
3.
4.
MACRO definitions
Typedef Keyword
Bit-Wise operators
Pointers
// Using PI macro
// Using ADD macro
Here, we have created 2 MACROs. The first macro is just a constant value, which gets replaced
before compilation. The second definition works like addition function to add X and Y. However,
please note that MACROs are completely different from functions.
MACROs are called before Compilation process, while functions are used at runtime.
Here, we have used typedef to create a new data-type as uint_demo. The uint_demo data type
mimics unsigned int data-type.
AVR Library contains a lot of typedef definitions. Checkout the header files of AVR to know more
about it.
Advanced Embedded
June 2011
53 Embedded C Review
Operator Symbol in C
&
|
^
~
<<
>>
Operation Mode
Binary
Binary
Binary
Unary
Binary
Binary
Binary operators require 2 operands to work, while unary operator requires only 1 operand to
operate.
6.4.1
The AND, OR, XOR operations work according to following Truth tables.
Input A
0
0
1
1
Input B
0
1
0
1
AND
0
0
0
1
OR
0
1
1
1
XOR
0
1
1
0
Here we see that AND gives 1 only if both inputs are 1, OR gives 1 if any of input is 1. While, XOR
gives 1 if and only if one of the input is 1.
Example #1 : Bitwise AND, OR, XOR
int a = 46, b = 23;
int x =a & b;
int y = a | b;
int z = a ^ b;
The values of x,y,z variables can be shown in the form of table as:
Variable
a
b
x
y
z
Binary Form
0000000000101110
0000000000010111
0000000000000110
0000000000111111
0000000000111001
Integer Value
46
23
6
63
57
Operation Applied
None
None
AND
OR
XOR
June 2011
54 Embedded C Review
Example #2: Complement Operator
int a = 6;
int x =~a;
Variable
A
X
Binary Form
0000000000000110
1111111111111001
Value
6
-7
Here, the bits of variable a are shifted leftwards 2 times. The result can be illustrated as:
Left Shift Operation
Bit N
7
Value
128
a
0
x
1
Result=> 176
6
64
1
0
5
32
1
1
4
16
0
1
3
8
1
0
2
4
1
0
1
2
0
0
0
1
0
0
The bit at 7th place comes at 9th place and similarly every other bit is shifted leftwards. As you can
clearly see, the output value becomes 4 times the original.
Right Shift Operation
Bit N
7
Value
128
b
0
y
0
Result=> 24
6
64
0
0
5
32
1
0
4
16
1
1
3
8
0
1
2
4
0
0
1
2
0
0
0
1
0
0
Here, the bit at 6th place is shifted at 5th place and similarly all other bits are shifted. Hence, the right
shift operation results in 24 as output.
? Did you Know
The left shift operator can be used when multiplying a value by 2 or a multiple of 2. Similarly, Right
Shift operator can be used to divide by 2 or multiple of 2.
Advanced Embedded
June 2011
55 Embedded C Review
Setting a bit
Use the bitwise OR operator (|) to set a bit.
REGA |= 1 << x;
Clearing a bit
Use the bitwise AND operator (&) to clear a bit.
REGA &= ~(1 << x);
That will clear bit x of REGA. You must invert the bit string with the bitwise NOT operator (~),
then AND it.
6.5.3
Toggling a bit
The XOR operator (^) can be used to toggle a bit.
REGA ^= 1 << x;
Checking/Reading a bit
To check a bit, AND it with the bit you want to check:
bit = REGA & (1 << x);
That will put the value of bit x of REGA into the variable bit.
6.6 Pointers
Pointers are special variables which store address of another memory location instead of storing
some value. Two important operators used in pointers are value-at (*), address-of (&).
The size of a pointer does not depend on the type of data-type on which it is pointing. Its size is
always going to be equal to size of int.
Pointer Demo
char x = 56;
char *ptr;
*ptr = &x;
char out = *ptr;
printf(%d,ptr);
// An char pointer
// The operator address-of(&) is used to retrieve address of variable x
// retrieves the value pointed by ptr
// Prints the address of pointer ptr
In this example, we create a pointer to a character variable x. Graphically, this can illustrated as:
Advanced Embedded
June 2011
56 Embedded C Review
2000
Address [1024]
1024
56
Here, the pointer ptr is stored at location 2000 in memory. The content of location 2000 is the
address of variable x, that is 1024. Hence, the pointer points to memory location of x variable. When
the value pointed by a ptr has to be used, we use *ptr to use its value.
6.6.1 Pointer Operations
We can only use addition and subtraction operations on pointers. The use of Multiplication/division
or any other operation on pointer will throw an error.
Operation
Operators allowed
Effect of operation
Addition
+, ++
Address of pointer is incremented
Subtraction
-, -Address of pointer is decremented
As an example, if the initial address of a pointer, *ptr is 2030. Then, *ptr++ will cause the ptr to point
to 2032 memory address.
Pointers can be summarized as:
Pointer Type
char*
int*
long int*
Size of Pointer
2
2
2
Data Type
Char
Int
long int
Size of variable
1
2
4
Example
char *ptr;
int *ptr;
long *ptr;
We have covered the very basics of pointers. We can also have pointer to another pointer variable.
Also, some other complex forms may be there. Covering each aspect of pointers in not possible here.
For more information on pointers, check out http://oreilly.com/catalog/pcp3/chapter/ch13.html.
Some C tips and techniques are described in the following Manual provided by Atmel. Interested
readers can have a look.
www.atmel.com/atmel/acrobat/doc1497.pdf
Advanced Embedded
June 2011
Chapter 7 -
So lets start with understanding the functioning of AVR. We will first discuss about I/O Ports. See
the pin configuration of Atmega-16.
You can see it has 32 I/O (Input/Output) pins grouped as A, B, C & D with 8 pins in each group. This
group is called as PORT.
Notice that all these pins have some function written in bracket. These are additional function that
pin can perform other than I/O. Some of them are.
7.1
Registers
All the configurations in microcontroller is set through 8 bit (1 byte) locations in RAM (RAM is a bank
of memory bytes) of the microcontroller called as Registers. All the functions are mapped to its
locations in RAM and the value we set at that location that is at that Register configures the
functioning of microcontroller. There are total 32 x 8bit registers in Atmega-16. As Register size of
this microcontroller is 8 bit, it called as 8 bit microcontroller.
Input Output functions are set by Three Registers for each PORT.
The I/O Ports are defined in <avr/io.h>. You need to include this header file to work with I/O Ports.
PIN
PA7
PA6
PA5
PA4
PA3
PA2
PA1
PA0
Advanced Embedded
June 2011
If I write DDRA = 0xFF (0x for Hexadecimal number system) that is setting all the bits of DDRA to be
1, will make all the pins of PORTA as Output.
Similarly by writing DDRD = 0x00 that is setting all the bits of DDRD to be 0, will make all the pins of
PORTD as Input.
Now lets take another example. Consider I want to set the pins of PORTB as shown in table,
PORT-B
PB7
PB6
PB5
PB4
PB3
PB2
PB1
PB0
Function
Output
Output
Input
Output
Input
Input
Input
Output
DDRB
For this configuration we have to set DDRB as 11010001 which in hexadecimal isD1. So we will write
DDRB=0xD1
Summary
7.3
This register sets the value to the corresponding PORT. Now a pin can be Output or Input. So lets
discuss both the cases.
7.3.1
Output Pin
If a pin is set to be output, then by setting bit 1 we make output High that is +5V and by setting bit 0
we make output Low that is 0V.
Lets take an example. Consider I have set DDRA=0xFF, that is all the pins to be Output. Now I want
to set Outputs as shown in table.
PORT-A
Value
PORTA
PA7
PA6
PA5
PA4
Low(0V)
0
PA3
PA2
PA1
PA0
For this configuration we have to set PORTA as 11000110 which in hexadecimal isC6. So we will
write PORTA=0xC6;
Advanced Embedded
June 2011
Input Pin
If a pin is set to be input, then by setting its corresponding bit in PORTX register will make it as
follows,
Tri-stated means the input will hang (no specific value) if no input voltage is specified on that pin.
Pull Up means input will go to +5V if no input voltage is given on that pin. It is basically connecting
PIN to +5V through a 10K Ohm resistance.
Summary
For an example consider I have connected a sensor on PC4 and configured it as an input pin through
DDR register. Now I want to read the value of PC4 whether it is Low or High. So I will just check 4th
bit of PINC register.
We can only read bits of the PINX register; can never write on that as it is meant for reading the
value of PORT.
Summary
Advanced Embedded
June 2011
60 LCD Interfacing
Chapter 8 -
LCD Interfacing
8.1 Introduction
Now we need to interface an LCD to our microcontroller so that we can display messages, outputs,
etc. Sometimes using an LCD becomes almost inevitable for debugging and calibrating the sensors
(discussed later). We will use the 16x2 LCD, which means it has two rows of 16 characters each.
Hence in total we can display 32 characters.
Advanced Embedded
June 2011
61 LCD Interfacing
c) Incorporation of a refreshing controller into the LCD, Thereby reliving the CPU of the task of
refreshing the LCD. In contrast, the LED must be refreshed by the CPU (or in some other way) to
keep displaying the data.
The interfacing of LCD is quite difficult. But we will try to make it simple and let us explain it for you.
We will learn how to interface the text intelligent LCD display. These displays are available in the
market of 16 column and one Row and more than one row displays.
Micro controller
Data RAM
Code RAM
ROM
MICRO CONTROLLER:
It is theData
brain
of LCD display. This
is handling
the all working ofBusy
the LCD.
flag
Register
Command
Register
DATA RAM:
This RAM is storing the ASCII values of corresponding characters which will be displayed on the LCD.
For each column there is one location in the RAM. When we will store the ASCII value at that
location than its corresponding character will be displayed on the screen.
CODE RAM:
This RAM stores the binary pattern according to the character.
ROM:
This ROM stores the binary pattern which is according to the Pixels of LCD and there are patterns of
every character.
COMMAND REGISTER:
It stores various commands for proper functioning.
DATA REGISTER: This register work as buffer for data lines and the internal buses of LCD. The ASCII
values of characters will be given to the data register.
BF (BUSY FLAG):
It indicates the internal working of the LCD. It show whether LCD is busy in any operation or not.
If BF=0 (LCD is idle we can proceed for next operation)
If BF=1 (LCD is busy we cannot proceed for next operation and we have to wait unless operation
completes).
Advanced Embedded
June 2011
62 LCD Interfacing
RS (REGISTER SELECT):
The RS pin is used to select Data Register or Command Register.
If RS=0, CR Register is selected, allowing the user to send a command such as clear display,curser at
the home etc.
If RS=1, DR Register is selected, allowing the user to send data to be display on the LCD.
R/W (READ/WRITE):
When R/W=0, Write operation..
When R/W=1 Read Operation
EN (ENABLE):
The Enable pin is used by the LCD to latch binary bits available on its data pins. When data is
supplied to data pins, a negative edge is applied to this pin So that the LCD latches in the data
present at the data pins. This pulse must be a minimum of 450 ns wide.
There should be positive edge at EN pin when read operation is required.
D7-D0:
This is 8-bit data pins. D7-D0 are used to send information to the LCD or read the contents of the
LCDs internal registers.
BK-LED (LEDA, LEDK):
These pins are used to give the supply to the back light of the LCD display. So, that content of the
LCD display can be viewed in the dark.
LCD Connections
Advanced Embedded
June 2011
63 LCD Interfacing
#1
Info
#2
Info
void lcd_clrscr(void);
Clear display and set cursor to home position.
#3
Info
void lcd_home(void);
Set cursor to home position.
#5
Info
#6
Info
#7
Info
#8
Info
#9
Info
#4
Info
Advanced Embedded
June 2011
64 LCD Interfacing
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
LCD_PORT
LCD_DATA0_PORT
LCD_DATA1_PORT
LCD_DATA2_PORT
LCD_DATA3_PORT
LCD_DATA0_PIN
LCD_DATA1_PIN
LCD_DATA2_PIN
LCD_DATA3_PIN
LCD_RS_PORT
LCD_RS_PIN
LCD_RW_PORT
LCD_RW_PIN
LCD_E_PORT
LCD_E_PIN
PORTF
LCD_PORT
LCD_PORT
LCD_PORT
LCD_PORT
4
5
6
7
LCD_PORT
0
LCD_PORT
1
LCD_PORT
2
LCD_LINES
LCD_DISP_LENGTH
LCD_LINE_LENGTH
LCD_START_LINE1
LCD_START_LINE2
LCD_START_LINE3
LCD_START_LINE4
LCD_WRAP_LINES
LCD_IO_MODE
2
16
0x40
0x00
0x40
0x14
0x54
0
1
Advanced Embedded
June 2011
Chapter 9 -
Most of the AVRs in Atmel's product line contain at least some internal EEPROM memory. EEPROM,
short for Electronically Erasable Read-Only memory, is a form of non-volatile memory with a
reasonably long lifespan. Because it is non-volatile, it will retain its information during periods of no
AVR power and thus is a great place for storing sparingly changing data such as device parameters.
The AVR internal EEPROM memory has a limited lifespan of 100,000 writes - reads are unlimited.
How it is accessed?
The AVR's internal EEPROM is accessed via special registers inside the AVR, which control the
address to be written to (EEPROM uses byte addressing), the data to be written (or the data which
has been read) as well as the flags to instruct the EEPROM controller to perform a write or a read.
The C language does not have any standards mandating how memory other than a single flat model
(SRAM in AVRs) is accessed or addressed. Because of this, just like storing data into program
memory via your program, every compiler has a unique implementation based on what the author
believed was the most logical system.
At the moment, we now have access to the eeprom memory, via the routines now provided by
eeprom.h. There are three main types of EEPROM access: byte, word and block. Each type has both
a write and a read variant, for obvious reasons. The names of the routines exposed by our new
headers are:
uint8_t eeprom_read_byte (const uint8_t *addr)
void eeprom_write_byte (uint8_t *addr, uint8_t value)
uint16_t eeprom_read_word (const uint16_t *addr)
void eeprom_write_word (uint16_t *addr, uint16_t value)
void eeprom_read_block (void *pointer_ram, const void *pointer_eeprom, size_t n)
void eeprom_write_block (void *pointer_eeprom, const void *pointer_ram, size_t n)
For more details see:
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=38417
Advanced Embedded
June 2011
66 UART Communication
Basic UART packet format: 1 start bit, 8 data bits, 1 parity bit, 1 stop bit.
BAUD Rate: This parameter specifies the desired baud rate (bits per second) of the UART. Most
typical standard baud rates are: 300, 1200, 2400, 9600, 19200, etc. However, any baud rate can be
used. This parameter affects both the receiver and the transmitter. The default is 2400 (bauds).
In the UART protocol, the transmitter and the receiver do not share a clock signal. That is, a clock
signal does not emanate from one UART transmitter to the other UART receiver. Due to this reason
the protocol is said to be asynchronous.
Since no common clock is shared, a known data transfer rate (baud rate) must be agreed upon prior
to data transmission. That is, the receiving UART needs to know the transmitting UARTs baud rate
(and conversely the transmitter needs to know the receivers baud rate, if any). In almost all cases
the receiving and transmitting baud rates are the same. The transmitter shifts out the data starting
with the LSB first.
Once the baud rate has been established (prior to initial communication), both the transmitter and
the receivers internal clock is set to the same frequency (though not the same phase). The receiver
"synchronizes" its internal clock to that of the transmitters at the beginning of every data packet
received. This allows the receiver to sample the data bit at the bit-cell center.
Advanced Embedded
June 2011
67 UART Communication
A key concept in UART design is that UARTs internal clock runs at much faster rate than the baud
rate. For example, the popular 16450 UART controller runs its internal clock at 16 times the baud
rate. This allows the UART receiver to sample the incoming data with granularity of 1/16 the baudrate period. This "oversampling" is critical since the receiver adds about 2 clock-ticks in the input
data synchronizer uncertainty. The incoming data is not sampled directly by the receiver, but goes
through a synchronizer which translates the clock domain from the transmitters to that of the
receiver. Additionally, the greater the granularity, the receiver has greater immunity with the baud
rate error.
The receiver detects the start bit by detecting the transition from logic 1 to logic 0 (note that while
the data line is idle, the logic level is high). In the case of 16450 UART, once the start-bit is detected,
the next data bits "centre" can be assured to be 24 ticks minus 2 (worse case synchronizer
uncertainty) later. From then on, every next data bit centre is 16 clock ticks later. Figure 2 illustrates
this point.
Once the start bit is detected, the subsequent data bits are assembled in a de-serializer. Error
condition maybe generated if the parity/stop bits are incorrect or missing.
Advanced Embedded
June 2011
68 UART Communication
To start with, check the Terminal Settings in Docklight. Go to Tools-> Project Settings. Select the
Send/Receive communication channel, i.e., the name by which the serial port is known in your
computer (like COM1). In the COM port settings, select the same values as you had set while
coding Atmega128. So, we will select Baud Rate 9600, Data Bits 8, Stop Bits 1, Parity Bits none. You
can select none in Parity Error Character. Click OK.
We are now ready to send/receive data, so, select Run->Start Communication, or, press F5. If your
uC is acting as a transmitter, then the characters it sends will appear in the Communication window
of Docklight. E.g,
uart1_putchar(K);
_delay_ms(500);
// Sends character K after every 500ms
Hence what you get on the screen is a KKKKKKKKKKKKKKKKKKKKKKKKK.. one K increasing every
500ms. To stop receiving characters, select Run->Stop Communication, or press F6.
If the receiver option is also enabled in Atmega128, then whatever you type from keyboard will be
received by it. You can either display these received characters on an LCD, control motors depending
on what characters you send, etc.
Advanced Embedded
June 2011
69 UART Communication
#2
Info
#3
Info
#4
Info
#5
Info
#6
Info
#7
Info
#8
Info
#9
Info
#10
Info
#1
Info
Advanced Embedded
June 2011
MOSI
MISO
SCK
SS
:
:
:
:
Master: This device provides the serial clock to the other device for data transfer. As a clock is used
for the data transfer, this protocol is Synchronous in nature. SS for Master will be disconnected.
Slave: This device accepts the clock from master device. SS for this has to be made 0 externally.
Advanced Embedded
June 2011
71 I2C Communication
SCL is the clock line. It is used to synchronize all data transfers over the I2C bus. SDA is the data line.
The SCL & SDA lines are connected to all devices on the I2C bus. There needs to be a third wire which
is just the ground or 0 volts. There may also be a 5volt wire is power is being distributed to the
devices. Both SCL and SDA lines are "open drain" drivers. What this means is that the chip can drive
its output low, but it cannot drive it high. For the line to be able to go high you must provide pull-up
resistors to the 5v supply. There should be a resistor from the SCL line to the 5v line and another
from the SDA line to the 5v line. You only need one set of pull-up resistors for the whole I2C bus, not
for each device, as illustrated below:
Advanced Embedded
June 2011
72 I2C Communication
the I2C bus, the other being the stop sequence. The start sequence and stop sequence are special in
that these are the only places where the SDA (data line) is allowed to change while the SCL (clock
line) is high. When data is being transferred, SDA must remain stable and not change whilst SCL is
high. The start and stop sequences mark the beginning and end of a transaction with the slave
device.
Data is transferred in sequences of 8 bits. The bits are placed on the SDA line starting with the MSB
(Most Significant Bit). The SCL line is then pulsed high, then low. Remember that the chip cannot
really drive the line high, it simply "lets go" of it and the resistor actually pulls it high. For every 8 bits
transferred, the device receiving the data sends back an acknowledge bit, so there are actually 9 SCL
clock pulses to transfer each 8 bit byte of data. If the receiving device sends back a low ACK bit, then
it has received the data and is ready to accept another byte. If it sends back a high then it is
indicating it cannot accept any further data and the master should terminate the transfer by sending
a stop sequence.
How fast?
The standard clock (SCL) speed for I2C up to 100KHz. Philips do define faster speeds: Fast mode,
which is up to 400KHz and High Speed mode which is up to 3.4MHz. All of our modules are designed
to work at up to 100KHz. We have tested our modules up to 1MHz but this needs a small delay of a
few uS between each byte transferred. In practical robots, we have never had any need to use high
SCL speeds. Keep SCL at or below 100KHz and then forget about it.
12.2.3 I2C Device Addressing
All I2C addresses are of 7 bits. This means that you can have up to 128 devices on the I2C bus, since a
7-bit number can be from 0 to 127. When sending out the 7 bit address, we still always send 8 bits.
The extra bit is used to inform the slave if the master is writing to it or reading from it. If the bit is
zero are master is writing to the slave. If the bit is 1 the master is reading from the slave. The 7 bit
address is placed in the upper 7 bits of the byte and the Read/Write (R/W) bit is in the LSB (Least
Significant Bit).
Advanced Embedded
June 2011
73 I2C Communication
The placement of the 7 bit address in the upper 7 bits of the byte is a source of confusion for the
newcomer. It means that to write to address 21, you must actually send out 42 which is 21 moved
over by 1 bit. It is probably easier to think of the I2C bus addresses as 8 bit addresses, with even
addresses as write only, and the odd addresses as the read address for the same device. To take our
TMP-275 for example, this is at address 0x9E. You would uses 0x9E to write to the TMP-275 and
0x9F to read from it. So the read/write bit just makes it an odd/even address.
12.2.4 The I2C Software Protocol
The first thing that will happen is that the master will send out a start sequence. This will alert all the
slave devices on the bus that a transaction is starting and they should listen in in case it is for them.
Next the master will send out the device address. The slave that matches this address will continue
with the transaction, any others will ignore the rest of this transaction and wait for the next. Having
addressed the slave device the master must now send out the internal location or register number
inside the slave that it wishes to write to or read from. This number is obviously dependant on what
the slave actually is and how many internal registers it has. Some very simple devices do not have
any, but most do, including all of our modules. Having sent the I2C address and the internal register
address the master can now send the data byte (or bytes, it doesn't have to be just one). The master
can continue to send data bytes to the slave and these will normally be placed in the following
registers because the slave will automatically increment the internal register address after each
byte. When the master has finished writing all data to the slave, it sends a stop sequence which
completes the transaction. So to write to a slave device:
1. Send a start sequence
2. Send the I2C address of the slave with the R/W bit low (even address)
3. Send the internal register number you want to write to
4. Send the data byte
5. [Optionally, send any further data bytes]
6. Send the stop sequence.
12.2.5 Reading from the Slave
Before reading data from the slave device, you must tell it which of its internal addresses you want
to read. For this you need to configure few registers. So a read of the slave actually starts off by
writing to it. This is the same as when you want to write to it. You send the start sequence, the I2C
address of the slave with the R/W bit low (even address) and the internal register number you want
to write to. Now you send another start sequence (sometimes called a restart) and the I2C address
again - this time with the read bit set. You then read as many data bytes as you wish and terminate
the transaction with a stop sequence. So to read the both temperature bytes from the TMP-275
module:
1. Send a start sequence
2. Send I2C address with the R/W bit low (even address) to Write
3. Send Internal Register address of the Device, on which you want to write to.
4. Send a start sequence again (repeated start)
5. Send I2C address with the R/W bit high (odd address) to Read
6. Read data byte from Device
7. Send the stop sequence.
Advanced Embedded
June 2011
74 I2C Communication
The bit sequence will look like this:
void i2c_init(void);
Initialize the I2C master interface. Need to be called only once.
#2
Info
void i2c_stop(void);
Terminates the data transfer and releases the I2C bus.
#3
Info
#4
Info
#5
Info
#6
Info
#7
Info
#8
Info
#9
Info
Advanced Embedded
June 2011
The WSN is built of "nodes" from a few to several hundreds or even thousands, where each node is
connected to sensors.
Each such sensor network node has typically following parts:
Advanced Embedded
June 2011
Advanced Embedded
June 2011
Star networks are connected to a centralized communications hub. Each node cannot communicate
directly with one another; all communications must be routed through the centralized hub. Each
node is then a client while the central hub is the server.
Tree networks use a central hub called a Root node as the main communications router. One level
down from the Root node in the hierarchy is a Central hub. This lower level then forms a Star
network. The Tree network can be considered a hybrid of both the Star and Peer to Peer networking
topologies.
Advanced Embedded
June 2011
Mesh networks allow data to hop from node to node, this allows the network to be self-healing.
Each node is then able to communicate with each other as data is routed from node to node until it
reaches the desired location. This type of network is one of the most complex and can cost a
significant amount of money to deploy properly.
Advanced Embedded
June 2011
Advanced Embedded
June 2011
80 Network Communication
1. Application Layer: This is the layer where all of user applications are running. This layer
comprises applications like Internet Explorer, Yahoo! Messenger etc. which have data to
send/receive.
Various Protocols which develop this Layer are HTTP, SMTP, Telnet, DNS etc.
2. Presentation Layer: This layer performs operations like Data Encryption, Compression. This
presents data in formatted way and hence its name.
Advanced Embedded
June 2011
81 Network Communication
3. Session Layer: This layer maintains communication between two network applications and is
also responsible for Authentication and authorization. This layer is responsible for
maintaining sessions of various applications.
4. Transport Layer: Transport Layer receives the data to be sent from Session Layer and
creates segments of variable length. The original data/message is also called payload data.
Transport layer. It multiplexes data of various applications, creates virtual end-to-end
connections, and provides transparent way to transmit data in a network.
Protocols which develop this layer may be TCP (Transmission Control Protocol) or UDP
(Uniform Datagram Protocol).
5. Network Layer: It is responsible for packetizing data. Network layer assigns Source and
Destination IP addresses to the packet. The IP address is a unique number which identifies a
network device. Destination IP Address specifies the device which will receive the packet.
IP (Internet Protocol) implements this layer. Routing of packets is done at this level using IP
Addresses.
6. Data Link Layer: This layer divides the data packet received from Network Layer into fixed
sized blocks of data, called Frames. The size of frame is defined using MTU (Max
Transmission Unit) which is the maximum size of packet that can be transferred. The Data
Link Layer is subdivided into 2 sub-layers:
a. MAC Media Access Control => Frames are given a MAC (Media Access Control)
address, which is a 48-bit number and is unique on the Local network. The task of
assigning MAC address is done by this layer.
b. LLC - Logical Link Control => This layer is responsible for Error Checking and flow
control.
7. Physical Layer: This layer denotes the physical medium through which data is sent. Physical
layer defines the cable or physical medium itself, e.g., thinnet, thicknet, unshielded twisted
pairs (UTP). The data may be sent in the form of electrical signals or in the form of light
impulses.
While Programming, we can shorten the OSI model to TCP/IP model as:
Application Layer
Transport Layer
Internet Layer
Network Access Layer
Here Application Layer consists of Application Layer + Presentation Layer + Session Layer.
Also, Network access layer consists of Data Link Layer and Physical layer. This is the layer where
Network protocols like Ethernet, Token Ring etc. come into the play. As Ethernet is the most popular
topology used now-a-days, we will be studying about Ethernet only.
Advanced Embedded
June 2011
82 Network Communication
14.2 Ethernet
14.2.1 Introduction
Ethernet is a standard protocol used for data communication over the Local networks. IEEE 802.3
standard defines Ethernet at the physical and data link layers of the OSI network model. It uses
CSMA carrier signalling to transmit signals at lower level.
Various functions performed by Ethernet are:
1. Packs the packets of data into fixed length frames.
2. Assigns a locally Unique MAC (Media Access Control) Address.
14.2.2 Ethernet Frame
Ethernet packs data in the form of Frames. The structure of a Frame is shown as:
Advanced Embedded
June 2011
83 Network Communication
14.2.4 Ethernet using ENC28J60
We will be using ENC28J60 IC for the Ethernet Support on our board. The ENC28J60 is a small chip
with 28 pins only and has a SPI interface which is easy to use from any microcontroller. We can also
call it Ethernet to SPI converter. A simple block diagram illustrating the ENC28J60 IC can be shown
as:
14.3.2 TCP
TCP or Transmission Control Protocol is a protocol which is used for controlling data transmission
between two devices. It is a reliable, connection oriented protocol. Connection oriented basically
means that we first need to setup a virtual connection between the communicating parties before
they can actually send/receive the data. This process is known as Handshake. After the connection is
established, data transmission can begin. The connection must be closed once we are finished with
the data to be transmitted.
Advanced Embedded
June 2011
84 Network Communication
Prime features of TCP:
End to end reliability=> The data transfer in TCP happens to be reliable due to built-in
support for Error checking. Also, a virtual connection is established to ensure more efficient
and reliable delivery of data.
Data packet Re-Sequencing=> The data packets are always sequenced and it ensures the
data to be delivered correctly in case of multi-packet data. Also, arrival of packet 5 before 3,
wont result in data loss.
Flow control=> Flow control is a mechanism used for controlling the normal flow of data so
that the communicating parties remain unaffected when transfer rates are unequal. This will
prevent condition of Stack Buffer Overflow/Underflow.
Advanced Embedded
June 2011
85 Network Communication
The fields of TCP Header are explained below:
4. SrcPort => The source port is port number of requesting client. It can be any random value
for a new connection. But the value must remain the same till the connection is open.
5. DstPort => The destination port is port at which server is running.
6. Sequence No=> Data at application layer is broken into multiple segments at Transport
Layer, which are ordered according to sequence number.
7. Acknowledgement No=> Every packet that is sent and a valid part of a connection is
acknowledged with an empty TCP segment with the ACK flag set.
8. Reserved=> This is unused and contains binary zeroes.
9. Data Offset=> The segment offset specifies the length of the TCP header in 32bit/4byte
blocks. Without tcp header options, the value is 5.
10. TCP Flags=> This field consists of six binary flags as:
a. Urgent Pointer (URG) => Segment will be routed faster, used for termination of a
connection.
b. Acknowledgement (ACK) => Used to acknowledge data and in the second and third
stage of a TCP connection initiation.
c. Push (PSH) => The IP stack will not buffer the segment and forward it to the
application immediately.
d. Reset (RST) => Tells the peer that the connection has been terminated.
e. Synchronization (SYN) => A segment with the SYN flag set indicates that client wants
to initiate a new connection to the destination port.
f. Final (FIN) => The connection should be closed, the peer is supposed to answer with
one last segment with the FIN flag set as well.
11. Window=> The amount of bytes that can be sent before the data should be acknowledged
with an ACK before sending more segments.
12. Checksum=> The checksum of pseudo header, tcp header and payload. The pseudo is a
structure containing IP source and destination address, 1 byte set to zero, the protocol (1
byte with a decimal value of 6), and 2 bytes (unsigned short) containing the total length of
the TCP segment.
13. Urgent pointer=> Only used if the urgent flag is set, else zero. It points to the end of the
payload data that should be sent with priority.
Transport layer can also have protocol like UDP, which is a connectionless data transmission
protocol. The discussion of UDP Protocol is out of the scope for this course.
14.3.3 IP Internet Protocol
This protocol works at Network Layer. It manages device addressing. Each device is given a unique
logical address called IP address (discussed later in detail). Various other features provided by IP:
1. Creation of packets
2. Routing of packets
3. Providing unique address to each and every device
Advanced Embedded
June 2011
86 Network Communication
14.3.3.1 IP Header
Advanced Embedded
June 2011
87 Network Communication
14.3.4 IP Address
An IP address is a unique address given to any networked device. The IP addresses come in 2 flavors.
IPv4 and IPv6. We will be only discussing the IPv4 addresses. An IPv4 address is a 32-bit unique
number. It is subdivided into 4 octets of 8 bits each, separated by Dots. An example of an IP address
is 10.0.0.5.
? Did you Know
You can get the IP address assigned to your PC using ipconfig on Windows, ifconfig on Linux.
14.3.4.1 Valid IP Addresses
Valid IP Addresses begin from 1.0.0.1 223.255.255.254. IPs ranging from 224.0.0.0 to
255.255.255.255 are reserved and cannot be used for general purposes. Any IP address cannot have
a zero in the last octet, like x.x.x.0. Also, the address ending in 255, like x.x.x.255 is used as a
broadcast address for the given network. When destination address is the broadcast address, then
everyone on the network receives the packet.
Valid IP Address Examples: 192.168.1.1, 10.24.32.5, 117.56.3.1
Invalid IP Addresses Examples: 0.1.5.10, 10.14.240.0
Even in the range of valid IP addresses, we have few ranges reserved for some specific purposes.
Like, 127.x.x.x is reserved for loopback interface.
There are 3 IP network addresses reserved for private networks.
10.0.0.0 to 10.255.255.255
172.16.0.0 to 172.31.255.255
192.168.0.0 to 192.168.255.255
As we can see, the part of IP address which is covered by 1s in Subnet Mask is called Network ID.
The part of IP Address, which is covered by 0s of Subnet mask is Host ID. Based on the subnet mask,
we can categorize IP addresses into various classes.
14.3.4.2 IP Address Classes
The various classes of networks specify additional or fewer octets to designate the network ID
versus the host ID.
Advanced Embedded
June 2011
88 Network Communication
Class
1st Octet
2nd Octet
3rd Octet
A
Net ID
Host ID
B
Net ID
Host ID
C
Net ID
The addressing scheme for class A through E networks is shown below:
Network Type
Class A
Class B
Class C
Class D
Class E
Address Range
001.x.x.x to 126.x.x.x
128.1.x.x to 191.254.x.x
192.0.1.x to 223.255.254.x
224.x.x.x to 239.255.255.255
240.x.x.x to 247.255.255.255
Subnet Mask
255.0.0.0
255.255.0.0
255.255.255.0
4th Octet
Host ID
Comments
For very large networks
For medium size networks
For small networks
Used to support multicasting
168
2562
65536x168
11010048
1
256
256x1
256
8
1
8
8
Taking an arbitrary message to be sent. This is the data to be sent by application layer.
Defining the TCP and IP headers as C structures.
Defining functions for checksum calculation, Converting IP address into 32-bit Integer format.
Filling up the values of header fields.
Sending the manually filled packet to Data Link Layer.
The network uses Big Endian notation, as compared to Little Endian notation used in Intel
Processors. While creating the packets manually, we need to know this thing and explicitly change
the byte-order. Endianness is discussed in Appendix Section.
Advanced Embedded
June 2011
89 Network Communication
14.6 Ping
14.6.1 Introduction
In December of 1983 I encountered some odd behaviour of the IP network at BRL. Recalling Dr.
Mills' comments, I quickly coded up the PING program, which revolved around opening an ICMP
style SOCK_RAW AF_INET Berkeley-style socket(). The code compiled just fine, but it didn't work -there was no kernel support for raw ICMP sockets! Incensed, I coded up the kernel support and had
everything working well before sunrise. Not surprisingly, Chuck Kennedy (aka "Kermit") had found
and fixed the network hardware before I was able to launch my very first "ping" packet. But I've used
it a few times since then. If I'd known then that it would be my most famous accomplishment in life,
I might have worked on it another day or two and added some more options.
By Ping Author
Ping is a network command, which is used to detect if a Host is responding or not. Ping uses ICMP
(Internet Control Message Protocol) Protocol, which works at Network Layer.
? Did you Know
Ping command can be used to test if you are connected to internet. Like: ping www.google.com.
14.6.2 Ping/ICMP Header
The format of Ping Packet headers is shown as:
1. Type=> Message type, for example 0 - echo reply, 8 - echo request, 3 destination unreachable.
2. Code => This is significant when sending an error message (unreachable), and
specifies the kind of error.
3. Checksum=> The checksum for the ICMP header + data. It is same as the IP
checksum.
4. Identifier=> used in echo request/reply messages, to identify the request.
5. ICMP Sequence => identifies the sequence of echo messages, if more than one
is sent.
We can easily fill up all the fields of ICMP packet header. A good article for ICMP/Ping is
available at: http://support.microsoft.com/kb/170292.
Advanced Embedded
June 2011
90 Network Communication
Advanced Embedded
June 2011
91 Network Communication
14.7.3 Web Server
Web Server is the application which serves Browser(Web Client). For building a Web Server, we need
to study how a Web Server responds according to various situations.
In above example, we sent a request to the Web Server. The response we got was:
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
200 is the Status Code. The meaning of 200 is Success. Status Codes determine whether we got
success or some error.
Various Status Codes can be categorized as:
Response Code
1xx
2xx
3xx
4xx
5xx
Most Important Codes that we need to implement in our Web Server are:
200 Success, The requested data is also sent
301 Resource we requested has been Moved Permanently
404 Requested resource was Not Found
500 Internal Server Error
? Did you Know
A very basic server serving only 1 or 2 files can be created only 5 lines of coding in perl. The perl
language is provided by default on Linux machines while we can use ActivePerl on Windows
platforms.
Advanced Embedded
June 2011
92 Network Communication
14.8 Telnet
A telnet is a simple Application Layer Protocol which allows us logging in to remote computers. A
client is used to connect to the Server. Once our login session is started, we can send and receive
data between client and server using a window called Terminal. Telnet runs on Port number 23.
14.8.1 Telnet Messages
Telnet uses raw TCP packets. It does not add any data in the form of headers. Hence it is a very
simple form of communication. It provides a set of Messages/Commands. Messages can be
transmitted back and forth between Server and client.
Various messages provided by telnet for communication are:
Name
SE
NOP
DM
Code
Meaning
240
End of subnegotiation
parameters
241
No operation
242
Data mark
BRK
IP
243
244
Break
Suspend
AO
245
Abort output
AYT
246
EC
247
Erase character
EL
248
Erase line
GA
249
Go ahead
SB
WILL
250
251
Subnegotiation
Will
WONT 252
Wont
DO
Do
253
DONT 254
Dont
IAC
Interpret as command
255
Comment
Advanced Embedded
June 2011
93 Network Communication
14.8.2 Implementation
Telnet can be implemented very easily. The implementation is similar as we implemented HTTP
Server. In case of telnet, we need to send these messages for communication instead of forming
HTTP responses as earlier.
14.8.3 Summary
Telnet was widely used during initial times for router configurations and other various purposes. As
it was realized that telnet does not provide any security mechanism and hence data can be traced
very easily, the usage of telnet was considerably reduced. A new protocol called SSH(Secure SHell) is
used now a days which uses Data Encryption to securely deliver information. It also provides many
advanced feature not available in Telnet.
Advanced Embedded
June 2011
Advanced Embedded
June 2011
#2
Info
#3
Info
#4
Info
#5
Info
#6
Info
#7
Info
uint16_t get_tcp_data_pointer(void);
This function returns the address of TCP packet in the stack buffer as an integer.
This function takes no arguments.
#8
Info
#9
Info
Advanced Embedded
June 2011
#2
Info
#3
Info
#4
Info
Some other functions are also available in those files. Go through the header files to know the extra
functions available in the Stack and ENC28J60 driver.
Advanced Embedded
June 2011
97 Appendix
Chapter 16 - Appendix
16.1 ASCII Table
Advanced Embedded
June 2011
98 Appendix
Big-Endian means that the most significant byte of any multibyte data field is stored at the
lowest memory address, which is also the address of the larger field.
Little-Endian means that the least significant byte of any multibyte data field is stored at the
lowest memory address, which is also the address of the larger field.
For example, consider the 32-bit number, 0xDEADBEEF. Following the Big-Endian convention, a
computer will store it as follows:
Big-Endian: The most significant byte is stored at the lowest byte address.
Whereas architectures that follow the Little-Endian rules will store it as depicted in following Figure
Advanced Embedded
June 2011
99 Appendix
Advanced Embedded
June 2011
100 Appendix
16.3.2 Explosion of the Ariane 5
On June 4, 1996 an unmanned Ariane 5 rocket launched by the
European Space Agency exploded just forty seconds after lift-off. The
rocket was on its first voyage, after a decade of development costing $7
billion. The destroyed rocket and its cargo were valued at $500 million.
A board of inquiry investigated the causes of the explosion and in two
weeks issued a report. It turned out that the cause of the failure was a
software error in the inertial reference system. Specifically a 64 bit
floating point number relating to the horizontal velocity of the rocket
with respect to the platform was converted to a 16 bit signed integer.
The number was larger than 32,768, the largest integer storeable in a
16 bit signed integer, and thus the conversion failed.
The following paragraphs are extracted from report of the Inquiry
Board.
On 4 June 1996, the maiden flight of the Ariane 5 launcher ended in a
failure. Only about 40 seconds after initiation of the flight sequence, at
an altitude of about 3700 m, the launcher veered off its flight path,
broke up and exploded.
The failure of the Ariane 501 was caused by the complete loss of guidance and attitude information
37 seconds after start of the main engine ignition sequence (30 seconds after lift-off). This loss of
information was due to specification and design errors in the software of the inertial reference
system.
The internal SRI* software exception was caused during execution of a data conversion from 64-bit
floating point to 16-bit signed integer value. The floating point number which was converted had a
value greater than what could be represented by a 16-bit signed integer.
*SRI stands for Systme de Rfrence Inertielle or Inertial Reference System.
Advanced Embedded
June 2011
101 Appendix
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Experiment
Tool
Peripheral
LED Glow
LED Glow
LED Blink
LED Pattern
Debugging
LED Glow
LED Blink
LED Pattern
Switch-LED-Glow
Switch-LED Blink
Switch-LED Pattern
Debugging
Switch-LED-Glow
Switch-LED Blink
Switch-LED Pattern
LCD Display String
LCD Display Integer
LCD Display Float
LCD Moving String
Switch Control LCD
Debugging
LCD Display String
LCD Display Integer
LCD Display Float
LCD Moving String
Switch Control LCD
Relay Control via Switch/Delay
Sending Data to PC
Receiving Data to uC Display on LCD
Controlling LED/LCD through PC
Relay Control via PC
EEPROM Data saving
EEPROM Data configuring via PC
ENC-MagJack LED Blink
TMP-275 High byte Read to LCD/PC
TMP-275 Low byte Read to LCD/PC
TMP-275 both byte Read to LCD/PC
TMP-275 to Celcius driver Read to LCD/PC
APDS9300 Channel-1 Read to LCD/PC
APDS9300 Channel-2 Read to LCD/PC
AVR-GCC
AVR-Studio
AVR-Studio
AVR-Studio
AVR-Studio
Make-File
Make-File
Make-File
AVR-Studio
AVR-Studio
AVR-Studio
AVR-Studio
Make-File
Make-File
Make-File
AVR-Studio
AVR-Studio
AVR-Studio
AVR-Studio
AVR-Studio
AVR-Studio
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED
GPIO-LED-Switch
GPIO-LED-Switch
GPIO-LED-Switch
GPIO-LED-Switch
GPIO-LED-Switch
GPIO-LED-Switch
GPIO-LED-Switch
LCD
LCD
LCD
LCD
GPIO-LCD-Switch
GPIO-LED-Switch
LCD
LCD
LCD
LCD
GPIO-LCD-Switch
GPIO-Relay
UART-FTDI
UART-FTDI
UART-FTDI
Relay-UART-FTDI
EEPROM
EEPROM-UART
SPI-ENC28J60
I2C-TMP275
I2C-TMP275
I2C-TMP275
I2C-TMP275
I2C-APDS9300
I2C-APDS9300
Advanced Embedded
Done
June 2011
102 Appendix
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Advanced Embedded
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
Make-File
N.A.
N.A.
N.A.
N.A.
N.A.
I2C-APDS9300
I2C-APDS9300
UART-CC2500
UART-CC2500
UART-CC2500
UART-CC2500
UART-CC2500
UART-CC2500
UART-CC2500
Relay-UART-CC2500
SPI-ENC
SPI-ENC
SPI-ENC
SPI-ENC-TMP275
SPI-ENC-APDS9300
SPI-ENC-LED
SPI-ENC-Relay
SPI-ENC-LED-CC2500
SPI-ENC-Relay-CC2500
SPI-ENC
SPI-ENC-EEPROM
Eagle
Eagle
Proteus
Proteus
Proteus
June 2011
103 References
Chapter 17 - References
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
[12]
[13]
Wikipedia: http://www.wikipedia.org
Atmel: http://www.atmel.com
Oreilly: http://www.oreilly.com
Microsoft Support: http://support.microsoft.com
NPTel: http://nptel.iitm.ac.in
TuxGraphics: http://www.tuxgraphics.org
Firewall.cx: http://firewall.cx
The Story of Ping: http://ftp.arl.army.mil/~mike/ping.html
Security-Freak: http://www.security-freak.net
Wireless Sensor Network Topologies: http://www.stevekos.com
CodeProject: http://www.codeproject.com
AVRFreaks: http://www.avrfreaks.net
Robot Electronics: http://www.robot-electronics.co.uk
Advanced Embedded
June 2011